code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def th_accuracy(pad_outputs: torch.Tensor, pad_targets: torch.Tensor,
ignore_label: int) -> torch.Tensor:
"""Calculate accuracy.
Args:
pad_outputs (Tensor): Prediction tensors (B * Lmax, D).
pad_targets (LongTensor): Target label tensors (B, Lmax).
ignore_label (int): Ig... | Calculate accuracy.
Args:
pad_outputs (Tensor): Prediction tensors (B * Lmax, D).
pad_targets (LongTensor): Target label tensors (B, Lmax).
ignore_label (int): Ignore label id.
Returns:
torch.Tensor: Accuracy value (0.0 - 1.0).
| th_accuracy | python | THUDM/GLM-4-Voice | cosyvoice/utils/common.py | https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/common.py | Apache-2.0 |
def subsequent_mask(
size: int,
device: torch.device = torch.device("cpu"),
) -> torch.Tensor:
"""Create mask for subsequent steps (size, size).
This mask is used only in decoder which works in an auto-regressive mode.
This means the current step could only do attention with its left steps.... | Create mask for subsequent steps (size, size).
This mask is used only in decoder which works in an auto-regressive mode.
This means the current step could only do attention with its left steps.
In encoder, fully attention is used when streaming is not necessary and
the sequence is not long. In this c... | subsequent_mask | python | THUDM/GLM-4-Voice | cosyvoice/utils/mask.py | https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/mask.py | Apache-2.0 |
def subsequent_chunk_mask(
size: int,
chunk_size: int,
num_left_chunks: int = -1,
device: torch.device = torch.device("cpu"),
) -> torch.Tensor:
"""Create mask for subsequent steps (size, size) with chunk size,
this is for streaming encoder
Args:
size (int): size ... | Create mask for subsequent steps (size, size) with chunk size,
this is for streaming encoder
Args:
size (int): size of mask
chunk_size (int): size of chunk
num_left_chunks (int): number of left chunks
<0: use full chunk
>=0: use num_left_chunks
device ... | subsequent_chunk_mask | python | THUDM/GLM-4-Voice | cosyvoice/utils/mask.py | https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/mask.py | Apache-2.0 |
def add_optional_chunk_mask(xs: torch.Tensor,
masks: torch.Tensor,
use_dynamic_chunk: bool,
use_dynamic_left_chunk: bool,
decoding_chunk_size: int,
static_chunk_size: int,
... | Apply optional mask for encoder.
Args:
xs (torch.Tensor): padded input, (B, L, D), L for max length
mask (torch.Tensor): mask for xs, (B, 1, L)
use_dynamic_chunk (bool): whether to use dynamic chunk or not
use_dynamic_left_chunk (bool): whether to use dynamic left chunk for
... | add_optional_chunk_mask | python | THUDM/GLM-4-Voice | cosyvoice/utils/mask.py | https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/mask.py | Apache-2.0 |
def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
"""Make mask tensor containing indices of padded part.
See description of make_non_pad_mask.
Args:
lengths (torch.Tensor): Batch of lengths (B,).
Returns:
torch.Tensor: Mask tensor containing indices of padded ... | Make mask tensor containing indices of padded part.
See description of make_non_pad_mask.
Args:
lengths (torch.Tensor): Batch of lengths (B,).
Returns:
torch.Tensor: Mask tensor containing indices of padded part.
Examples:
>>> lengths = [5, 3, 2]
>>> make_pad_mask(leng... | make_pad_mask | python | THUDM/GLM-4-Voice | cosyvoice/utils/mask.py | https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/mask.py | Apache-2.0 |
def __init__(self,
optimizer,
*,
max_steps,
decay_rate=0.5,
min_lr=0.0,
last_epoch=-1,
**kwargs):
"""
From Nemo:
Implementation of the Noam Hold Annealing policy
from th... |
From Nemo:
Implementation of the Noam Hold Annealing policy
from the SqueezeFormer paper.
Unlike NoamAnnealing, the peak learning rate
can be explicitly set for this scheduler.
The schedule first performs linear warmup,
then holds the peak LR, then decays with s... | __init__ | python | THUDM/GLM-4-Voice | cosyvoice/utils/scheduler.py | https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/scheduler.py | Apache-2.0 |
def _median_filter(inputs: torch.Tensor, filter_width: int) -> torch.Tensor:
"""
Applies a median filter of width `filter_width` along the last dimension of the input.
The `inputs` tensor is assumed to be 3- or 4-dimensional.
"""
if filter_width <= 0 or filter_width % 2 != 1:
raise ValueErr... |
Applies a median filter of width `filter_width` along the last dimension of the input.
The `inputs` tensor is assumed to be 3- or 4-dimensional.
| _median_filter | python | THUDM/GLM-4-Voice | speech_tokenizer/generation_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py | Apache-2.0 |
def _dynamic_time_warping(matrix: np.ndarray):
"""
Measures similarity between two temporal sequences: the input audio and the output tokens. Used to generate
token-level timestamps.
"""
output_length, input_length = matrix.shape
cost = np.ones((output_length + 1, input_length + 1), dtype=np.flo... |
Measures similarity between two temporal sequences: the input audio and the output tokens. Used to generate
token-level timestamps.
| _dynamic_time_warping | python | THUDM/GLM-4-Voice | speech_tokenizer/generation_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py | Apache-2.0 |
def _extract_token_timestamps(self, generate_outputs, alignment_heads, time_precision=0.02, num_frames=None):
"""
Calculates token-level timestamps using the encoder-decoder cross-attentions and dynamic time-warping (DTW) to
map each output token to a position in the input audio. If `num_frames`... |
Calculates token-level timestamps using the encoder-decoder cross-attentions and dynamic time-warping (DTW) to
map each output token to a position in the input audio. If `num_frames` is specified, the encoder-decoder
cross-attentions will be cropped before applying DTW.
Returns:
... | _extract_token_timestamps | python | THUDM/GLM-4-Voice | speech_tokenizer/generation_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py | Apache-2.0 |
def generate(
self,
input_features: Optional[torch.Tensor] = None,
generation_config: Optional[GenerationConfig] = None,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
prefix_allowed_tokens_fn: Optional[Ca... |
Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids.
<Tip warning={true}>
Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
model's default generation configuration. You ca... | generate | python | THUDM/GLM-4-Voice | speech_tokenizer/generation_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py | Apache-2.0 |
def replace_or_add(lst: List[int], num: int, itr: Iterator[int]):
"""short function to replace num with a itr in lst"""
found = any(i in lst for i in itr)
if found:
lst = [num if i in itr else i for i in lst]
else:
lst.append(num)
... | short function to replace num with a itr in lst | replace_or_add | python | THUDM/GLM-4-Voice | speech_tokenizer/generation_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py | Apache-2.0 |
def detect_language(
self,
input_features: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
encoder_outputs: Optional[Union[torch.FloatTensor, BaseModelOutput]] = None,
generation_config: Optional[GenerationConfig] = None,
num_segment... |
Detects language from log-mel input features or encoder_outputs
Parameters:
input_features (`torch.Tensor` of shape `(batch_size, feature_size, sequence_length)`, *optional*):
Float values of log-mel features extracted from the raw speech waveform. The raw speech waveform c... | detect_language | python | THUDM/GLM-4-Voice | speech_tokenizer/generation_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py | Apache-2.0 |
def _retrieve_compression_ratio(tokens, vocab_size):
"""Compute byte length of zlib compressed token bytes vs. byte length of raw token bytes"""
length = int(math.log2(vocab_size) / 8) + 1
token_bytes = b"".join([t.to_bytes(length, "little") for t in tokens.tolist()])
compression_ratio =... | Compute byte length of zlib compressed token bytes vs. byte length of raw token bytes | _retrieve_compression_ratio | python | THUDM/GLM-4-Voice | speech_tokenizer/generation_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py | Apache-2.0 |
def _prepare_4d_causal_attention_mask_with_cache_position(
attention_mask: torch.Tensor,
sequence_length: int,
target_length: int,
dtype: torch.dtype,
device: torch.device,
min_dtype: float,
cache_position: torch.Tensor,
batch_size: int,
):
"""
Cre... |
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
Args:
attention_mask (`torch.Tensor`):
A 2D attention mask of shape `(batch_size, ke... | _prepare_4d_causal_attention_mask_with_cache_position | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
"""
Shift input ids one token to the right.
"""
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
shifted_input_ids[:, 0] = decoder_start_t... |
Shift input ids one token to the right.
| shift_tokens_right | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def _compute_mask_indices(
shape: Tuple[int, int],
mask_prob: float,
mask_length: int,
attention_mask: Optional[torch.LongTensor] = None,
min_masks: int = 0,
) -> np.ndarray:
"""
Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data A... |
Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on
CPU as part of the preprocessing during training.
Args:
shape: T... | _compute_mask_indices | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def compute_num_masked_span(input_length):
"""Given input length, compute how many spans should be masked"""
num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
num_masked_span = max(num_masked_span, min_masks)
# make sure num masked span <= sequence_length
i... | Given input length, compute how many spans should be masked | compute_num_masked_span | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
layer_head_mask: torch.Tensor,
output_attentions: bool = False,
) -> torch.Tensor:
"""
Args:
hidden_states (`torch.FloatTensor`): input to the layer o... |
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
... | forward | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = No... |
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
... | forward | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def forward(
self,
input_features,
attention_mask=None,
head_mask=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
quantized_token_ids=None
):
r"""
Args:
input_featur... |
Args:
input_features (`torch.LongTensor` of shape `(batch_size, feature_size, sequence_length)`):
Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be
obtained by loading a `.flac` or `.wav` audio file into an array of type ... | forward | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
head_mask=None,
cross_attn_head_mask=None,
past_key_values=None,
inputs_embeds=None,
po... |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`WhisperTokenizer`]. See [`Pre... | forward | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def _mask_input_features(
self,
input_features: torch.FloatTensor,
attention_mask: Optional[torch.LongTensor] = None,
):
"""
Masks extracted features along time axis and/or along feature axis according to
[SpecAugment](https://arxiv.org/abs/1904.08779).
... |
Masks extracted features along time axis and/or along feature axis according to
[SpecAugment](https://arxiv.org/abs/1904.08779).
| _mask_input_features | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def forward(
self,
input_features: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
head_mask: Op... |
Returns:
Example:
```python
>>> import torch
>>> from transformers import AutoFeatureExtractor, WhisperModel
>>> from datasets import load_dataset
>>> model = WhisperVQModel.from_pretrained("openai/whisper-base")
>>> feature_extractor = AutoFeatur... | forward | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def forward(
self,
input_features: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
head_mask: Op... |
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the language modeling loss. Indices should either be in `[0, ..., config.vocab_size]`
or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the l... | forward | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None,
head_mask: Optional[torch.Tensor] = None,
cross_attn_head_mask: Optional[torch.Tensor]... |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.enc... | forward | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def forward(
self,
input_features: Optional[torch.LongTensor] = None,
head_mask: Optional[torch.Tensor] = None,
encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
labels: Optional[torch.LongTensor] = None,
output_attentions: Optiona... |
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`confi... | forward | python | THUDM/GLM-4-Voice | speech_tokenizer/modeling_whisper.py | https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py | Apache-2.0 |
def NonMaxSuppression(boxes, scores, threshold):
r"""Non-Maximum Suppression
The algorithm begins by storing the highest-scoring bounding
box, and eliminating any box whose intersection-over-union (IoU)
with it is too great. The procedure repeats on the surviving
boxes, and so on until there are no ... | Non-Maximum Suppression
The algorithm begins by storing the highest-scoring bounding
box, and eliminating any box whose intersection-over-union (IoU)
with it is too great. The procedure repeats on the surviving
boxes, and so on until there are no boxes left.
The stored boxes are returned.
NB: T... | NonMaxSuppression | python | junfu1115/DANet | encoding/functions/customize.py | https://github.com/junfu1115/DANet/blob/master/encoding/functions/customize.py | MIT |
def pairwise_cosine(X, C, normalize=False):
r"""Pairwise Cosine Similarity or Dot-product Similarity
Shape:
- Input: :math:`X\in\mathcal{R}^{B\times N\times D}`
:math:`C\in\mathcal{R}^{K\times D}` :math:`S\in \mathcal{R}^K`
(where :math:`B` is batch, :math:`N` is total number of feat... | Pairwise Cosine Similarity or Dot-product Similarity
Shape:
- Input: :math:`X\in\mathcal{R}^{B\times N\times D}`
:math:`C\in\mathcal{R}^{K\times D}` :math:`S\in \mathcal{R}^K`
(where :math:`B` is batch, :math:`N` is total number of features,
:math:`K` is number is codewords, :m... | pairwise_cosine | python | junfu1115/DANet | encoding/functions/encoding.py | https://github.com/junfu1115/DANet/blob/master/encoding/functions/encoding.py | MIT |
def get_deepten(dataset='pascal_voc', backbone='resnet50', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""DeepTen model from the paper `"Deep TEN: Texture Encoding Network"
<https://arxiv.org/pdf/1612.02844v1.pdf>`_
Parameters
----------
dataset : str, default pascal_voc... | DeepTen model from the paper `"Deep TEN: Texture Encoding Network"
<https://arxiv.org/pdf/1612.02844v1.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
pretrained : bool, default False
Whether to load the pretra... | get_deepten | python | junfu1115/DANet | encoding/models/deepten.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/deepten.py | MIT |
def get_model_file(name, root=os.path.join('~', '.encoding', 'models')):
r"""Return location for the pretrained on local file system.
This function will download from online model zoo when model cannot be found or has mismatch.
The root directory will be created if it doesn't exist.
Parameters
---... | Return location for the pretrained on local file system.
This function will download from online model zoo when model cannot be found or has mismatch.
The root directory will be created if it doesn't exist.
Parameters
----------
name : str
Name of the model.
root : str, default '~/.enc... | get_model_file | python | junfu1115/DANet | encoding/models/model_store.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/model_store.py | MIT |
def purge(root=os.path.join('~', '.encoding', 'models')):
r"""Purge all pretrained model files in local file store.
Parameters
----------
root : str, default '~/.encoding/models'
Location for keeping the model parameters.
"""
root = os.path.expanduser(root)
files = os.listdir(root)
... | Purge all pretrained model files in local file store.
Parameters
----------
root : str, default '~/.encoding/models'
Location for keeping the model parameters.
| purge | python | junfu1115/DANet | encoding/models/model_store.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/model_store.py | MIT |
def get_model(name, **kwargs):
"""Returns a pre-defined model by name
Parameters
----------
name : str
Name of the model.
pretrained : bool
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping the model parameter... | Returns a pre-defined model by name
Parameters
----------
name : str
Name of the model.
pretrained : bool
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping the model parameters.
Returns
-------
Module... | get_model | python | junfu1115/DANet | encoding/models/model_zoo.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/model_zoo.py | MIT |
def resnet50(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(torch.load(
... | Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet50 | python | junfu1115/DANet | encoding/models/backbone/resnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet.py | MIT |
def resnet101(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
pretrained=False
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_st... | Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet101 | python | junfu1115/DANet | encoding/models/backbone/resnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet.py | MIT |
def resnet152(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrained:
model.load_state_dict(torch.load(
... | Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet152 | python | junfu1115/DANet | encoding/models/backbone/resnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet.py | MIT |
def resnet50s(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNetS-50 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
kwargs['deep_stem'] = True
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:... | Constructs a ResNetS-50 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet50s | python | junfu1115/DANet | encoding/models/backbone/resnet_variants.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet_variants.py | MIT |
def resnet101s(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNetS-101 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
kwargs['deep_stem'] = True
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrain... | Constructs a ResNetS-101 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet101s | python | junfu1115/DANet | encoding/models/backbone/resnet_variants.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet_variants.py | MIT |
def resnet152s(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a ResNetS-152 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
kwargs['deep_stem'] = True
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrain... | Constructs a ResNetS-152 model as in PSPNet.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| resnet152s | python | junfu1115/DANet | encoding/models/backbone/resnet_variants.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnet_variants.py | MIT |
def resnext50_32x4d(pretrained=False, root='~/.encoding/models', **kwargs):
r"""ResNeXt-50 32x4d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progr... | ResNeXt-50 32x4d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
| resnext50_32x4d | python | junfu1115/DANet | encoding/models/backbone/resnext.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnext.py | MIT |
def resnext101_32x8d(pretrained=False, root='~/.encoding/models', **kwargs):
r"""ResNeXt-101 32x8d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
pro... | ResNeXt-101 32x8d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
| resnext101_32x8d | python | junfu1115/DANet | encoding/models/backbone/resnext.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/resnext.py | MIT |
def wideresnet38(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a WideResNet-38 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = WideResNet([3, 3, 6, 3, 1, 1], **kwargs)
if pretrained:
model.load_state_dict(torch.loa... | Constructs a WideResNet-38 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| wideresnet38 | python | junfu1115/DANet | encoding/models/backbone/wideresnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/wideresnet.py | MIT |
def wideresnet50(pretrained=False, root='~/.encoding/models', **kwargs):
"""Constructs a WideResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = WideResNet([3, 3, 6, 6, 3, 1], **kwargs)
if pretrained:
model.load_state_dict(torch.loa... | Constructs a WideResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| wideresnet50 | python | junfu1115/DANet | encoding/models/backbone/wideresnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/wideresnet.py | MIT |
def xception65(pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = Xception65(**kwargs)
if pretrained:
model.load_state_dict(torch.load(get_model_file('xception65', root=root)))
retur... | Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
| xception65 | python | junfu1115/DANet | encoding/models/backbone/xception.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/backbone/xception.py | MIT |
def get_atten(dataset='pascal_voc', backbone='resnet50s', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""ATTEN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_atten.pdf>`_
Parameters
------... | ATTEN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_atten.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
pretrained : bool, def... | get_atten | python | junfu1115/DANet | encoding/models/sseg/atten.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/atten.py | MIT |
def parallel_forward(self, inputs, **kwargs):
"""Multi-GPU Mult-size Evaluation
Args:
inputs: list of Tensors
"""
inputs = [(input.unsqueeze(0).cuda(device),)
for input, device in zip(inputs, self.device_ids)]
replicas = self.replicate(self, self.de... | Multi-GPU Mult-size Evaluation
Args:
inputs: list of Tensors
| parallel_forward | python | junfu1115/DANet | encoding/models/sseg/base.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/base.py | MIT |
def get_danet(dataset='pascal_voc', backbone='resnet50', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""DANet model from the paper `"Dual Attention Network for Scene Segmentation"
<https://arxiv.org/abs/1809.02983.pdf>`
"""
acronyms = {
'pascal_voc': 'voc',
'pasca... | DANet model from the paper `"Dual Attention Network for Scene Segmentation"
<https://arxiv.org/abs/1809.02983.pdf>`
| get_danet | python | junfu1115/DANet | encoding/models/sseg/danet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/danet.py | MIT |
def get_dran(dataset='pascal_voc', backbone='resnet50', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""Scene Segmentation with Dual Relation-aware Attention Network
"""
acronyms = {
'pascal_voc': 'voc',
'pascal_aug': 'voc',
'pcontext': 'pcontext',
'a... | Scene Segmentation with Dual Relation-aware Attention Network
| get_dran | python | junfu1115/DANet | encoding/models/sseg/dran.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/dran.py | MIT |
def get_encnet(dataset='pascal_voc', backbone='resnet50s', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
dataset : str, default pasca... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
backbone : str, default resnet50s
The backbone networ... | get_encnet | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_encnet_resnet50_pcontext(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrain... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping t... | get_encnet_resnet50_pcontext | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_encnet_resnet101_coco(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained ... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping t... | get_encnet_resnet101_coco | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_encnet_resnet101_pcontext(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrai... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping t... | get_encnet_resnet101_pcontext | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_encnet_resnet50_ade(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained we... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping t... | get_encnet_resnet50_ade | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_encnet_resnet101_ade(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained w... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping t... | get_encnet_resnet101_ade | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_encnet_resnet152_ade(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained w... | EncNet model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping t... | get_encnet_resnet152_ade | python | junfu1115/DANet | encoding/models/sseg/encnet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/encnet.py | MIT |
def get_fcfpn(dataset='pascal_voc', backbone='resnet50', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""FCFPN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcfpn.pdf>`_
Parameters
---------... | FCFPN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcfpn.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
pretrained : bool, def... | get_fcfpn | python | junfu1115/DANet | encoding/models/sseg/fcfpn.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/fcfpn.py | MIT |
def get_fcn(dataset='pascal_voc', backbone='resnet50s', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""FCN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcn.pdf>`_
Parameters
----------
... | FCN model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_fcn.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
pretrained : bool, default... | get_fcn | python | junfu1115/DANet | encoding/models/sseg/fcn.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/fcn.py | MIT |
def get_fcn_resnest50_ade(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained ... | EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keepi... | get_fcn_resnest50_ade | python | junfu1115/DANet | encoding/models/sseg/fcn.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/fcn.py | MIT |
def get_fcn_resnest50_pcontext(pretrained=False, root='~/.encoding/models', **kwargs):
r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretra... | EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keepi... | get_fcn_resnest50_pcontext | python | junfu1115/DANet | encoding/models/sseg/fcn.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/fcn.py | MIT |
def get_upernet(dataset='pascal_voc', backbone='resnet50s', pretrained=False,
root='~/.encoding/models', **kwargs):
r"""UperNet model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_upernet.pdf>`_
Parameters
--... | UperNet model from the paper `"Fully Convolutional Network for semantic segmentation"
<https://people.eecs.berkeley.edu/~jonlong/long_shelhamer_upernet.pdf>`_
Parameters
----------
dataset : str, default pascal_voc
The dataset that model pretrained on. (pascal_voc, ade20k)
pretrained : bool,... | get_upernet | python | junfu1115/DANet | encoding/models/sseg/upernet.py | https://github.com/junfu1115/DANet/blob/master/encoding/models/sseg/upernet.py | MIT |
def forward(self, x):
"""
inputs :
x : input feature maps( B X C X H X W)
returns :
out : attention value + input feature
attention: B X (HxW) X (HxW)
"""
m_batchsize, C, height, width = x.size()
proj_query = self.qu... |
inputs :
x : input feature maps( B X C X H X W)
returns :
out : attention value + input feature
attention: B X (HxW) X (HxW)
| forward | python | junfu1115/DANet | encoding/nn/da_att.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/da_att.py | MIT |
def forward(self,x):
"""
inputs :
x : input feature maps( B X C X H X W)
returns :
out : attention value + input feature
attention: B X C X C
"""
m_batchsize, C, height, width = x.size()
proj_query = x.view(m_batchsi... |
inputs :
x : input feature maps( B X C X H X W)
returns :
out : attention value + input feature
attention: B X C X C
| forward | python | junfu1115/DANet | encoding/nn/da_att.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/da_att.py | MIT |
def forward(self, x,y):
"""
inputs :
x : input feature(N,C,H,W) y:gathering centers(N,K,M)
returns :
out : compact position attention feature
attention map: (H*W)*M
"""
m_batchsize,C,width ,height = x.size()
m_batchs... |
inputs :
x : input feature(N,C,H,W) y:gathering centers(N,K,M)
returns :
out : compact position attention feature
attention map: (H*W)*M
| forward | python | junfu1115/DANet | encoding/nn/dran_att.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/dran_att.py | MIT |
def forward(self, x,y):
"""
inputs :
x : input feature(N,C,H,W) y:gathering centers(N,K,H,W)
returns :
out : compact channel attention feature
attention map: K*C
"""
m_batchsize,C,width ,height = x.size()
x_reshape =... |
inputs :
x : input feature(N,C,H,W) y:gathering centers(N,K,H,W)
returns :
out : compact channel attention feature
attention map: K*C
| forward | python | junfu1115/DANet | encoding/nn/dran_att.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/dran_att.py | MIT |
def forward(self, x,y):
"""
inputs :
x : low level feature(N,C,H,W) y:high level feature(N,C,H,W)
returns :
out : cross-level gating decoder feature
"""
low_lvl_feat = self.conv_low(x)
high_lvl_feat = upsample(y, low_lvl_feat.size... |
inputs :
x : low level feature(N,C,H,W) y:high level feature(N,C,H,W)
returns :
out : cross-level gating decoder feature
| forward | python | junfu1115/DANet | encoding/nn/dran_att.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/dran_att.py | MIT |
def reset_dropblock(start_step, nr_steps, start_value, stop_value, m):
"""
Example:
from functools import partial
apply_drop_prob = partial(reset_dropblock, 0, epochs*iters_per_epoch, 0.0, 0.1)
net.apply(apply_drop_prob)
"""
if isinstance(m, DropBlock2D):
m.reset_steps(st... |
Example:
from functools import partial
apply_drop_prob = partial(reset_dropblock, 0, epochs*iters_per_epoch, 0.0, 0.1)
net.apply(apply_drop_prob)
| reset_dropblock | python | junfu1115/DANet | encoding/nn/dropblock.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/dropblock.py | MIT |
def __init__(self, smoothing=0.1):
"""
Constructor for the LabelSmoothing module.
:param smoothing: label smoothing factor
"""
super(LabelSmoothing, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing |
Constructor for the LabelSmoothing module.
:param smoothing: label smoothing factor
| __init__ | python | junfu1115/DANet | encoding/nn/loss.py | https://github.com/junfu1115/DANet/blob/master/encoding/nn/loss.py | MIT |
def download(url, path=None, overwrite=False, sha1_hash=None):
"""Download an given URL
Parameters
----------
url : str
URL to download
path : str, optional
Destination path to store downloaded file. By default stores to the
current directory with same name as in url.
ove... | Download an given URL
Parameters
----------
url : str
URL to download
path : str, optional
Destination path to store downloaded file. By default stores to the
current directory with same name as in url.
overwrite : bool, optional
Whether to overwrite destination file ... | download | python | junfu1115/DANet | encoding/utils/files.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/files.py | MIT |
def check_sha1(filename, sha1_hash):
"""Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the fil... | Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash.
| check_sha1 | python | junfu1115/DANet | encoding/utils/files.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/files.py | MIT |
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(t... | Computes the accuracy over the k top predictions for the specified values of k | accuracy | python | junfu1115/DANet | encoding/utils/metrics.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/metrics.py | MIT |
def batch_pix_accuracy(output, target):
"""Batch Pixel Accuracy
Args:
predict: input 4D tensor
target: label 3D tensor
"""
_, predict = torch.max(output, 1)
predict = predict.cpu().numpy().astype('int64') + 1
target = target.cpu().numpy().astype('int64') + 1
pixel_labeled =... | Batch Pixel Accuracy
Args:
predict: input 4D tensor
target: label 3D tensor
| batch_pix_accuracy | python | junfu1115/DANet | encoding/utils/metrics.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/metrics.py | MIT |
def batch_intersection_union(output, target, nclass):
"""Batch Intersection of Union
Args:
predict: input 4D tensor
target: label 3D tensor
nclass: number of categories (int)
"""
_, predict = torch.max(output, 1)
mini = 1
maxi = nclass
nbins = nclass
predict = pre... | Batch Intersection of Union
Args:
predict: input 4D tensor
target: label 3D tensor
nclass: number of categories (int)
| batch_intersection_union | python | junfu1115/DANet | encoding/utils/metrics.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/metrics.py | MIT |
def get_mask_pallete(npimg, dataset='detail'):
"""Get image color pallete for visualizing masks"""
# recovery boundary
if dataset == 'pascal_voc':
npimg[npimg==21] = 255
# put colormap
out_img = Image.fromarray(npimg.squeeze().astype('uint8'))
if dataset == 'ade20k':
out_img.putp... | Get image color pallete for visualizing masks | get_mask_pallete | python | junfu1115/DANet | encoding/utils/pallete.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/pallete.py | MIT |
def update_bn_stats(
model: nn.Module, data_loader: Iterable[Any], num_iters: int = 200 # pyre-ignore
) -> None:
"""
Recompute and update the batch norm stats to make them more precise. During
training both BN stats and the weight are changing after every iteration, so
the running average can not p... |
Recompute and update the batch norm stats to make them more precise. During
training both BN stats and the weight are changing after every iteration, so
the running average can not precisely reflect the actual stats of the
current model.
In this function, the BN stats are recomputed with fixed weig... | update_bn_stats | python | junfu1115/DANet | encoding/utils/precise_bn.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/precise_bn.py | MIT |
def get_bn_modules(model: nn.Module) -> List[nn.Module]:
"""
Find all BatchNorm (BN) modules that are in training mode. See
fvcore.precise_bn.BN_MODULE_TYPES for a list of all modules that are
included in this search.
Args:
model (nn.Module): a model possibly containing BN modules.
Retur... |
Find all BatchNorm (BN) modules that are in training mode. See
fvcore.precise_bn.BN_MODULE_TYPES for a list of all modules that are
included in this search.
Args:
model (nn.Module): a model possibly containing BN modules.
Returns:
list[nn.Module]: all BN modules in the model.
| get_bn_modules | python | junfu1115/DANet | encoding/utils/precise_bn.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/precise_bn.py | MIT |
def get_selabel_vector(target, nclass):
r"""Get SE-Loss Label in a batch
Args:
predict: input 4D tensor
target: label 3D tensor (BxHxW)
nclass: number of categories (int)
Output:
2D tensor (BxnClass)
"""
batch = target.size(0)
tvect = torch.zeros(batch, nclass)
... | Get SE-Loss Label in a batch
Args:
predict: input 4D tensor
target: label 3D tensor (BxHxW)
nclass: number of categories (int)
Output:
2D tensor (BxnClass)
| get_selabel_vector | python | junfu1115/DANet | encoding/utils/train_helper.py | https://github.com/junfu1115/DANet/blob/master/encoding/utils/train_helper.py | MIT |
def filepath_enumerate(paths):
"""Enumerate the file paths of all subfiles of the list of paths"""
out = []
for path in paths:
if os.path.isfile(path):
out.append(path)
else:
for root, dirs, files in os.walk(path):
for name in files:
... | Enumerate the file paths of all subfiles of the list of paths | filepath_enumerate | python | junfu1115/DANet | tests/lint.py | https://github.com/junfu1115/DANet/blob/master/tests/lint.py | MIT |
def _print_summary_map(strm, result_map, ftype):
"""Print summary of certain result map."""
if len(result_map) == 0:
return 0
npass = len([x for k, x in result_map.items() if len(x) == 0])
strm.write('=====%d/%d %s files passed check=====\n' % (npass, len(result_map), ftype))... | Print summary of certain result map. | _print_summary_map | python | junfu1115/DANet | tests/lint.py | https://github.com/junfu1115/DANet/blob/master/tests/lint.py | MIT |
def get_header_guard_dmlc(filename):
"""Get Header Guard Convention for DMLC Projects.
For headers in include, directly use the path
For headers in src, use project name plus path
Examples: with project-name = dmlc
include/dmlc/timer.h -> DMLC_TIMTER_H_
src/io/libsvm_parser.h -> DMLC_I... | Get Header Guard Convention for DMLC Projects.
For headers in include, directly use the path
For headers in src, use project name plus path
Examples: with project-name = dmlc
include/dmlc/timer.h -> DMLC_TIMTER_H_
src/io/libsvm_parser.h -> DMLC_IO_LIBSVM_PARSER_H_
| get_header_guard_dmlc | python | junfu1115/DANet | tests/lint.py | https://github.com/junfu1115/DANet/blob/master/tests/lint.py | MIT |
def __init__(self, caption_track: Dict):
"""Construct a :class:`Caption <Caption>`.
:param dict caption_track:
Caption track data extracted from ``watch_html``.
"""
self.url = caption_track.get("baseUrl")
# Certain videos have runs instead of simpleText
# t... | Construct a :class:`Caption <Caption>`.
:param dict caption_track:
Caption track data extracted from ``watch_html``.
| __init__ | python | pytube/pytube | pytube/captions.py | https://github.com/pytube/pytube/blob/master/pytube/captions.py | Unlicense |
def json_captions(self) -> dict:
"""Download and parse the json caption tracks."""
json_captions_url = self.url.replace('fmt=srv3','fmt=json3')
text = request.get(json_captions_url)
parsed = json.loads(text)
assert parsed['wireMagic'] == 'pb3', 'Unexpected captions format'
... | Download and parse the json caption tracks. | json_captions | python | pytube/pytube | pytube/captions.py | https://github.com/pytube/pytube/blob/master/pytube/captions.py | Unlicense |
def float_to_srt_time_format(d: float) -> str:
"""Convert decimal durations into proper srt format.
:rtype: str
:returns:
SubRip Subtitle (str) formatted time duration.
float_to_srt_time_format(3.89) -> '00:00:03,890'
"""
fraction, whole = math.modf(d)
... | Convert decimal durations into proper srt format.
:rtype: str
:returns:
SubRip Subtitle (str) formatted time duration.
float_to_srt_time_format(3.89) -> '00:00:03,890'
| float_to_srt_time_format | python | pytube/pytube | pytube/captions.py | https://github.com/pytube/pytube/blob/master/pytube/captions.py | Unlicense |
def xml_caption_to_srt(self, xml_captions: str) -> str:
"""Convert xml caption tracks to "SubRip Subtitle (srt)".
:param str xml_captions:
XML formatted caption tracks.
"""
segments = []
root = ElementTree.fromstring(xml_captions)
for i, child in enumerate(li... | Convert xml caption tracks to "SubRip Subtitle (srt)".
:param str xml_captions:
XML formatted caption tracks.
| xml_caption_to_srt | python | pytube/pytube | pytube/captions.py | https://github.com/pytube/pytube/blob/master/pytube/captions.py | Unlicense |
def download(
self,
title: str,
srt: bool = True,
output_path: Optional[str] = None,
filename_prefix: Optional[str] = None,
) -> str:
"""Write the media stream to disk.
:param title:
Output filename (stem only) for writing media file.
... | Write the media stream to disk.
:param title:
Output filename (stem only) for writing media file.
If one is not specified, the default filename is used.
:type title: str
:param srt:
Set to True to download srt, false to download xml. Defaults to True.
... | download | python | pytube/pytube | pytube/captions.py | https://github.com/pytube/pytube/blob/master/pytube/captions.py | Unlicense |
def calculate_n(self, initial_n: list):
"""Converts n to the correct value to prevent throttling."""
if self.calculated_n:
return self.calculated_n
# First, update all instances of 'b' with the list(initial_n)
for i in range(len(self.throttling_array)):
if self.t... | Converts n to the correct value to prevent throttling. | calculate_n | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_signature(self, ciphered_signature: str) -> str:
"""Decipher the signature.
Taking the ciphered signature, applies the transform functions.
:param str ciphered_signature:
The ciphered signature sent in the ``player_config``.
:rtype: str
:returns:
... | Decipher the signature.
Taking the ciphered signature, applies the transform functions.
:param str ciphered_signature:
The ciphered signature sent in the ``player_config``.
:rtype: str
:returns:
Decrypted signature required to download the media content.
... | get_signature | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def parse_function(self, js_func: str) -> Tuple[str, int]:
"""Parse the Javascript transform function.
Break a JavaScript transform function down into a two element ``tuple``
containing the function name and some integer-based argument.
:param str js_func:
The JavaScript ve... | Parse the Javascript transform function.
Break a JavaScript transform function down into a two element ``tuple``
containing the function name and some integer-based argument.
:param str js_func:
The JavaScript version of the transform function.
:rtype: tuple
:return... | parse_function | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_initial_function_name(js: str) -> str:
"""Extract the name of the function responsible for computing the signature.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
Function name from regex match
"""
function_patterns = [
r"\b[cs]\s*&&... | Extract the name of the function responsible for computing the signature.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
Function name from regex match
| get_initial_function_name | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_transform_plan(js: str) -> List[str]:
"""Extract the "transform plan".
The "transform plan" is the functions that the ciphered signature is
cycled through to obtain the actual signature.
:param str js:
The contents of the base.js asset file.
**Example**:
['DE.AJ(a,15)',
'... | Extract the "transform plan".
The "transform plan" is the functions that the ciphered signature is
cycled through to obtain the actual signature.
:param str js:
The contents of the base.js asset file.
**Example**:
['DE.AJ(a,15)',
'DE.VR(a,3)',
'DE.AJ(a,51)',
'DE.VR(a,3)',
... | get_transform_plan | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_transform_object(js: str, var: str) -> List[str]:
"""Extract the "transform object".
The "transform object" contains the function definitions referenced in the
"transform plan". The ``var`` argument is the obfuscated variable name
which contains these functions, for example, given the function ... | Extract the "transform object".
The "transform object" contains the function definitions referenced in the
"transform plan". The ``var`` argument is the obfuscated variable name
which contains these functions, for example, given the function call
``DE.AJ(a,15)`` returned by the transform plan, "DE" wou... | get_transform_object | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_transform_map(js: str, var: str) -> Dict:
"""Build a transform function lookup.
Build a lookup table of obfuscated JavaScript function names to the
Python equivalents.
:param str js:
The contents of the base.js asset file.
:param str var:
The obfuscated variable name that s... | Build a transform function lookup.
Build a lookup table of obfuscated JavaScript function names to the
Python equivalents.
:param str js:
The contents of the base.js asset file.
:param str var:
The obfuscated variable name that stores an object with all functions
that descrambl... | get_transform_map | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_throttling_function_name(js: str) -> str:
"""Extract the name of the function that computes the throttling parameter.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
The name of the function used to compute the throttling parameter.
"""
funct... | Extract the name of the function that computes the throttling parameter.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
The name of the function used to compute the throttling parameter.
| get_throttling_function_name | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_throttling_function_code(js: str) -> str:
"""Extract the raw code for the throttling function.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
The name of the function used to compute the throttling parameter.
"""
# Begin by extracting the co... | Extract the raw code for the throttling function.
:param str js:
The contents of the base.js asset file.
:rtype: str
:returns:
The name of the function used to compute the throttling parameter.
| get_throttling_function_code | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_throttling_function_array(js: str) -> List[Any]:
"""Extract the "c" array.
:param str js:
The contents of the base.js asset file.
:returns:
The array of various integers, arrays, and functions.
"""
raw_code = get_throttling_function_code(js)
array_start = r",c=\["
a... | Extract the "c" array.
:param str js:
The contents of the base.js asset file.
:returns:
The array of various integers, arrays, and functions.
| get_throttling_function_array | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def get_throttling_plan(js: str):
"""Extract the "throttling plan".
The "throttling plan" is a list of tuples used for calling functions
in the c array. The first element of the tuple is the index of the
function to call, and any remaining elements of the tuple are arguments
to pass to that functio... | Extract the "throttling plan".
The "throttling plan" is a list of tuples used for calling functions
in the c array. The first element of the tuple is the index of the
function to call, and any remaining elements of the tuple are arguments
to pass to that function.
:param str js:
The conten... | get_throttling_plan | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def swap(arr: List, b: int):
"""Swap positions at b modulus the list length.
This function is equivalent to:
.. code-block:: javascript
function(a, b) { var c=a[0];a[0]=a[b%a.length];a[b]=c }
**Example**:
>>> swap([1, 2, 3, 4], 2)
[3, 2, 1, 4]
"""
r = b % len(arr)
return... | Swap positions at b modulus the list length.
This function is equivalent to:
.. code-block:: javascript
function(a, b) { var c=a[0];a[0]=a[b%a.length];a[b]=c }
**Example**:
>>> swap([1, 2, 3, 4], 2)
[3, 2, 1, 4]
| swap | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def throttling_reverse(arr: list):
"""Reverses the input list.
Needs to do an in-place reversal so that the passed list gets changed.
To accomplish this, we create a reversed copy, and then change each
indvidual element.
"""
reverse_copy = arr.copy()[::-1]
for i in range(len(reverse_copy)):... | Reverses the input list.
Needs to do an in-place reversal so that the passed list gets changed.
To accomplish this, we create a reversed copy, and then change each
indvidual element.
| throttling_reverse | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def throttling_unshift(d: list, e: int):
"""Rotates the elements of the list to the right.
In the javascript, the operation is as follows:
for(e=(e%d.length+d.length)%d.length;e--;)d.unshift(d.pop())
"""
e = throttling_mod_func(d, e)
new_arr = d[-e:] + d[:-e]
d.clear()
for el in new_arr... | Rotates the elements of the list to the right.
In the javascript, the operation is as follows:
for(e=(e%d.length+d.length)%d.length;e--;)d.unshift(d.pop())
| throttling_unshift | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def throttling_cipher_function(d: list, e: str):
"""This ciphers d with e to generate a new list.
In the javascript, the operation is as follows:
var h = [A-Za-z0-9-_], f = 96; // simplified from switch-case loop
d.forEach(
function(l,m,n){
this.push(
n[m]=h[
... | This ciphers d with e to generate a new list.
In the javascript, the operation is as follows:
var h = [A-Za-z0-9-_], f = 96; // simplified from switch-case loop
d.forEach(
function(l,m,n){
this.push(
n[m]=h[
(h.indexOf(l)-h.indexOf(this[m])+m-32+f--)... | throttling_cipher_function | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def throttling_nested_splice(d: list, e: int):
"""Nested splice function in throttling js.
In the javascript, the operation is as follows:
function(d,e){
e=(e%d.length+d.length)%d.length;
d.splice(
0,
1,
d.splice(
e,
1,
... | Nested splice function in throttling js.
In the javascript, the operation is as follows:
function(d,e){
e=(e%d.length+d.length)%d.length;
d.splice(
0,
1,
d.splice(
e,
1,
d[0]
)[0]
)
}
... | throttling_nested_splice | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
def throttling_prepend(d: list, e: int):
"""
In the javascript, the operation is as follows:
function(d,e){
e=(e%d.length+d.length)%d.length;
d.splice(-e).reverse().forEach(
function(f){
d.unshift(f)
}
)
}
Effectively, this moves the ... |
In the javascript, the operation is as follows:
function(d,e){
e=(e%d.length+d.length)%d.length;
d.splice(-e).reverse().forEach(
function(f){
d.unshift(f)
}
)
}
Effectively, this moves the last e elements of d to the beginning.
| throttling_prepend | python | pytube/pytube | pytube/cipher.py | https://github.com/pytube/pytube/blob/master/pytube/cipher.py | Unlicense |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.