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 experiment_setup(models: Sequence[ModelInfo], c_ref: int, batch_size: int): """Return information related to training `models` under compute budget `c_ref`.""" data = [] for m in models: c_self_per_token = m.self_attn_flops() d_iso = c_ref / c_self_per_token s_iso = num_traini...
Return information related to training `models` under compute budget `c_ref`.
experiment_setup
python
krasserm/perceiver-io
examples/scaling/clm/article.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/article.py
Apache-2.0
def experiment_ratios(models: Sequence[ModelInfo]): """Return compute- and parameter-related ratios, independent of compute budget.""" data = [] for m in models: c_self_approx_per_token = m.self_attn_flops_approx() c_self_per_token = m.self_attn_flops() c_cross_per_token = m.cross_...
Return compute- and parameter-related ratios, independent of compute budget.
experiment_ratios
python
krasserm/perceiver-io
examples/scaling/clm/article.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/article.py
Apache-2.0
def self_attn(self, num_channels, num_layers): """Self-attention FLOPs per latent token. Equivalent to a decoder-only transformer. :param num_channels: model dimension :param num_layers: number of self attention layers incl hybrid layer """ embed = self._input_embed(num...
Self-attention FLOPs per latent token. Equivalent to a decoder-only transformer. :param num_channels: model dimension :param num_layers: number of self attention layers incl hybrid layer
self_attn
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def cross_attn(self, num_channels, prefix_dropout=0.5): """Prefix cross-attention FLOPS per latent token. Perceiver AR extra compute compared to a decoder-only transformer. :param num_channels: model dimension :param prefix_dropout: dropout probability of prefix positions """ ...
Prefix cross-attention FLOPS per latent token. Perceiver AR extra compute compared to a decoder-only transformer. :param num_channels: model dimension :param prefix_dropout: dropout probability of prefix positions
cross_attn
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def _self_attn_layer(self, num_channels): """Self-attention FLOPs per latent token per layer.""" qkv = 6 * num_channels**2 attn = 2 * num_channels * self.num_latents out = 2 * num_channels**2 return qkv + attn + out
Self-attention FLOPs per latent token per layer.
_self_attn_layer
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def _cross_attn_layer(self, num_channels): """Cross-attention FLOPs per prefix token per layer.""" kv = 4 * num_channels**2 attn = 2 * num_channels * self.num_latents return kv + attn
Cross-attention FLOPs per prefix token per layer.
_cross_attn_layer
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def __init__(self, num_channels: int, num_layers: int, compute_estimator: ComputeEstimator): """... :param num_channels: model dimension. :param num_layers: number of self attention layers incl hybrid layer. """ self.num_channels = num_channels self.num_layers = num_laye...
... :param num_channels: model dimension. :param num_layers: number of self attention layers incl hybrid layer.
__init__
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def num_self_attn_params(self): """Parameter count of self-attention part. Equivalent to a decoder-only transformer. """ return num_self_attn_params( num_channels=self.num_channels, num_layers=self.num_layers, num_latents=self.num_latents, ...
Parameter count of self-attention part. Equivalent to a decoder-only transformer.
num_self_attn_params
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def num_cross_attn_params(self): """Parameter count of cross-attention part..""" # parameters for prefix position embedding return num_cross_attn_params(self.num_channels, self.num_prefix)
Parameter count of cross-attention part..
num_cross_attn_params
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def encode_midi_files(files: List[Path], num_workers: int) -> List[np.ndarray]: """Encode a list of midi files using multiple cpu workers.""" with Pool(processes=num_workers) as pool: res = list(tqdm(pool.imap(_encode_midi_file, files), total=len(files))) return [r for r in res if r is not None]
Encode a list of midi files using multiple cpu workers.
encode_midi_files
python
krasserm/perceiver-io
perceiver/data/audio/midi_processor.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/audio/midi_processor.py
Apache-2.0
def __init__( self, dataset_dir: str, max_seq_len: int, min_seq_len: Optional[int] = None, padding_side: str = "left", batch_size: int = 16, num_workers: int = 1, preproc_workers: Optional[int] = None, pin_memory: bool = True, ): """Bas...
Base class for data preprocessing and loading across different audio data sources using MIDI as the source data format. :param dataset_dir: Directory for storing the preprocessed dataset. :param max_seq_len: Maximum sequence length generated by this data module. :param min_seq_len: Mini...
__init__
python
krasserm/perceiver-io
perceiver/data/audio/symbolic.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/audio/symbolic.py
Apache-2.0
def mask_words(self, examples): """A modified version of whole word masking as described in https://huggingface.co/course/chapter7/3. The implementation in the linked document replaces words, randomly selected with `wwm_probability`, with mask tokens (one or more per word). The implementation h...
A modified version of whole word masking as described in https://huggingface.co/course/chapter7/3. The implementation in the linked document replaces words, randomly selected with `wwm_probability`, with mask tokens (one or more per word). The implementation here, however, only replaces 80% of selected...
mask_words
python
krasserm/perceiver-io
perceiver/data/text/collator.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/text/collator.py
Apache-2.0
def __init__( self, dataset_dir: str, tokenizer: str, max_seq_len: int, task: Task = Task.mlm, mask_prob: float = 0.15, mask_words: bool = True, static_masking: bool = False, add_special_tokens: bool = False, add_eos_token: bool = False, ...
Base class for consistent data preprocessing and loading across different text data sources. :param dataset_dir: Directory for storing the preprocessed dataset. :param tokenizer: Reference to a Hugging Face fast tokenizer (or the `deepmind/language-perceiver` tokenizer). :param max_seq_len: Max...
__init__
python
krasserm/perceiver-io
perceiver/data/text/common.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/text/common.py
Apache-2.0
def word_ids(self, token_ids): """Creates word ids from `token_ids`. Words boundaries are defined using whitespace boundaries. Whitespaces preceding a word have the same word id as the actual word following these whitespaces. Special tokens are assigned a `None` word id. Consecutive words do ...
Creates word ids from `token_ids`. Words boundaries are defined using whitespace boundaries. Whitespaces preceding a word have the same word id as the actual word following these whitespaces. Special tokens are assigned a `None` word id. Consecutive words do not necessarily have consecutive wor...
word_ids
python
krasserm/perceiver-io
perceiver/data/text/utils.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/text/utils.py
Apache-2.0
def _extract_image_patches(self, x: torch.Tensor, kernel: int, stride: int = 1, dilation: int = 1): """Equivalent to the implementation of https://www.tensorflow.org/api_docs/python/tf/image/extract_patches using "SAME" padding. From: https://discuss.pytorch.org/t/tf-extract-image-patches-in-py...
Equivalent to the implementation of https://www.tensorflow.org/api_docs/python/tf/image/extract_patches using "SAME" padding. From: https://discuss.pytorch.org/t/tf-extract-image-patches-in-pytorch/43837/9
_extract_image_patches
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def _pad(x: torch.Tensor, kernel: int, stride: int = 1, dilation: int = 1) -> torch.Tensor: """Applies a pad to the input using "SAME" strategy.""" *_, h, w = x.shape h2 = math.ceil(h / stride) w2 = math.ceil(w / stride) pad_row = (h2 - 1) * stride + (kernel - 1) * dilation + 1 -...
Applies a pad to the input using "SAME" strategy.
_pad
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def _compute_patch_grid_indices(self, img_shape: Tuple[int, ...]) -> List[Tuple[int, int]]: """From https://github.com/deepmind/deepmind-research/blob/master/perceiver/colabs/optical_flow.ipynb.""" ys = list(range(0, img_shape[0], self.patch_size[0] - self.patch_min_overlap)) xs = list(range(0, ...
From https://github.com/deepmind/deepmind-research/blob/master/perceiver/colabs/optical_flow.ipynb.
_compute_patch_grid_indices
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def preprocess( self, image_pair: Union[Tuple[np.ndarray, np.ndarray], Tuple[torch.Tensor, torch.Tensor]] ) -> torch.Tensor: """Creates the input features for the model for a pair of images. The input images are stacked and split into image patches of size `patch_size`. For each pixel of ea...
Creates the input features for the model for a pair of images. The input images are stacked and split into image patches of size `patch_size`. For each pixel of each individual patch, 3x3 patches are extracted and stacked in the channel dimension. Output shape: torch.Size(nr_patches, 2, 27, pa...
preprocess
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def preprocess_batch( self, image_pairs: Union[List[Tuple[np.ndarray, np.ndarray]], List[Tuple[torch.Tensor, torch.Tensor]]], ) -> torch.Tensor: """Creates the input features for the model for a batch of image pairs. For each image pair the images are stacked and split into image pa...
Creates the input features for the model for a batch of image pairs. For each image pair the images are stacked and split into image patches of size `patch_size`. For each pixel of each individual patch, 3x3 patches are extracted and stacked in the channel dimension. Output shape: torch.Size(b...
preprocess_batch
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def postprocess(self, predictions: torch.Tensor, img_shape: Tuple[int, ...]) -> torch.Tensor: """Combines optical flow predictions for individual image patches into a single prediction per image pair. Predictions can be supplied for a single image pair or a batch of image pairs, hence the supported inp...
Combines optical flow predictions for individual image patches into a single prediction per image pair. Predictions can be supplied for a single image pair or a batch of image pairs, hence the supported input shapes are: * (nr_patches, patch_size[0], patch_size[1], 2) and * (batch_size,...
postprocess
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def process( self, model, image_pairs: Union[List[Tuple[np.ndarray, np.ndarray]], List[Tuple[torch.Tensor, torch.Tensor]]], batch_size: int, ) -> torch.Tensor: """Combines preprocessing, inference and postprocessing steps for the optical flow. The input features for ...
Combines preprocessing, inference and postprocessing steps for the optical flow. The input features for model are created by stacking each image pair in the channel dimension and splitting the result into image patches of size `patch_size`. For each pixel in each individual patch, 3x3 patches a...
process
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def render_optical_flow(flow: np.ndarray) -> np.ndarray: """Renders optical flow predictions produced by an optical flow model.""" hsv = np.zeros((flow.shape[0], flow.shape[1], 3), dtype=np.uint8) mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1]) hsv[..., 0] = ang / np.pi / 2 * 180 hsv[..., 1...
Renders optical flow predictions produced by an optical flow model.
render_optical_flow
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def __init__(self, num_input_channels: int, *args, **kwargs): """Transforms and position-encodes task-specific input to generic encoder input. :param num_input_channels: Number of channels of the generic encoder input produced by this adapter. """ super().__init__() self._num_in...
Transforms and position-encodes task-specific input to generic encoder input. :param num_input_channels: Number of channels of the generic encoder input produced by this adapter.
__init__
python
krasserm/perceiver-io
perceiver/model/core/adapter.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/adapter.py
Apache-2.0
def __init__(self, rotated_channels_per_head: int, *args, **kwargs): """An input adapter mixin that additionally generates a frequency position encoding for input sequence `x`.""" super().__init__(*args, **kwargs) self.frq_pos_encoding = FrequencyPositionEncoding(dim=rotated_channels_per...
An input adapter mixin that additionally generates a frequency position encoding for input sequence `x`.
__init__
python
krasserm/perceiver-io
perceiver/model/core/adapter.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/adapter.py
Apache-2.0
def generate( self, inputs: Optional[torch.Tensor] = None, input_ids: Optional[torch.Tensor] = None, num_latents: int = 1, **kwargs, ): """Augments `GenerationMixin.generate` to support a `num_latents` argument. This argument determines the initial number of ...
Augments `GenerationMixin.generate` to support a `num_latents` argument. This argument determines the initial number of latents positions assigned to the end of a prompt. During generation, first, the number of latent positions grows until `self.backend_model.max_latents` is reached, then the p...
generate
python
krasserm/perceiver-io
perceiver/model/core/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/huggingface.py
Apache-2.0
def __init__( self, num_heads: int, num_q_input_channels: int, num_kv_input_channels: int, num_qk_channels: Optional[int] = None, num_v_channels: Optional[int] = None, num_output_channels: Optional[int] = None, max_heads_parallel: Optional[int] = None, ...
Multi-head attention as specified in https://arxiv.org/abs/2107.14795 Appendix E plus support for rotary position embeddings (https://arxiv.org/abs/2104.09864) and causal attention. Causal attention requires queries and keys to be right-aligned, if they have different length. :param num_heads: ...
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def forward( self, x_q: torch.Tensor, x_kv: torch.Tensor, pad_mask: Optional[torch.Tensor] = None, rot_pos_emb_q: Optional[RotaryPositionEmbedding] = None, rot_pos_emb_k: Optional[RotaryPositionEmbedding] = None, kv_cache: Optional[KVCache] = None, ): ...
... :param x_q: Query input of shape (B, N, D) where B is the batch size, N the query sequence length and D the number of query input channels (= `num_q_input_channels`) :param x_kv: Key/value input of shape (B, L, C) where B is the batch size, L the key/value sequence length and C ...
forward
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def __init__( self, num_heads: int, num_q_input_channels: int, num_kv_input_channels: int, num_qk_channels: Optional[int] = None, num_v_channels: Optional[int] = None, max_heads_parallel: Optional[int] = None, causal_attention: bool = False, dropou...
Pre-layer-norm cross-attention (see `MultiHeadAttention` for attention details).
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def forward( self, x_q: torch.Tensor, x_kv: Optional[torch.Tensor] = None, x_kv_prefix: Optional[torch.Tensor] = None, pad_mask: Optional[torch.Tensor] = None, rot_pos_emb_q: Optional[RotaryPositionEmbedding] = None, rot_pos_emb_k: Optional[RotaryPositionEmbedding...
Pre-layer-norm cross-attention of query input `x_q` to key/value input (`x_kv` or `x_kv_prefix`). If `x_kv_prefix` is defined, the entire key/value input is a concatenation of `x_kv_prefix` and `x_q` along the sequence dimension. In this case, the query attends to itself at the end of the key/value seq...
forward
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def __init__( self, num_heads: int, num_channels: int, num_qk_channels: Optional[int] = None, num_v_channels: Optional[int] = None, max_heads_parallel: Optional[int] = None, causal_attention: bool = False, dropout: float = 0.0, qkv_bias: bool = Tru...
Pre-layer norm self-attention (see `MultiHeadAttention` and for attention details).
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def forward( self, x: torch.Tensor, pad_mask: Optional[torch.Tensor] = None, rot_pos_emb: Optional[RotaryPositionEmbedding] = None, kv_cache: Optional[KVCache] = None, ): """Pre-layer-norm self-attention of input `x`.""" x = self.norm(x) return self.at...
Pre-layer-norm self-attention of input `x`.
forward
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def __init__( self, input_adapter: InputAdapter, num_latents: int, num_latent_channels: int, num_cross_attention_heads: int = 4, num_cross_attention_qk_channels: Optional[int] = None, num_cross_attention_v_channels: Optional[int] = None, num_cross_attentio...
Generic Perceiver IO encoder. :param input_adapter: Transforms and position-encodes task-specific input to generic encoder input of shape (B, M, C) where B is the batch size, M the input sequence length and C the number of key/value input channels. C is determined by the `num_in...
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def __init__( self, output_adapter: OutputAdapter, output_query_provider: QueryProvider, num_latent_channels: int, num_cross_attention_heads: int = 4, num_cross_attention_qk_channels: Optional[int] = None, num_cross_attention_v_channels: Optional[int] = None, ...
Generic Perceiver IO decoder. :param output_adapter: Transforms generic decoder cross-attention output of shape (B, O, F) to task-specific output. B is the batch size, O the output sequence length and F the number of cross-attention output channels. :param output_query_p...
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def __init__( self, input_adapter: RotarySupport, num_heads: int = 8, max_heads_parallel: Optional[int] = None, num_self_attention_layers: int = 6, num_self_attention_rotary_layers: int = 1, self_attention_widening_factor: int = 4, cross_attention_widening...
Implementation of Perceiver AR (https://arxiv.org/abs/2202.07765). :param input_adapter: Transforms an input sequence to generic Perceiver AR input. An input adapter may choose to add (absolute) position information to transformed inputs while `PerceiverAR` additionally computes a ...
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def _positions(self, v_min=-1.0, v_max=1.0): """Create evenly spaced position coordinates for self.spatial_shape with values in [v_min, v_max]. :param v_min: minimum coordinate value per dimension. :param v_max: maximum coordinate value per dimension. :return: position coordinates tenso...
Create evenly spaced position coordinates for self.spatial_shape with values in [v_min, v_max]. :param v_min: minimum coordinate value per dimension. :param v_max: maximum coordinate value per dimension. :return: position coordinates tensor of shape (*shape, len(shape)).
_positions
python
krasserm/perceiver-io
perceiver/model/core/position.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/position.py
Apache-2.0
def _position_encodings( self, p: torch.Tensor, max_frequencies: Optional[Tuple[int, ...]] = None, include_positions: bool = True ) -> torch.Tensor: """Fourier-encode positions p using self.num_bands frequency bands. :param p: positions of shape (*d, c) where c = len(d). :param max_...
Fourier-encode positions p using self.num_bands frequency bands. :param p: positions of shape (*d, c) where c = len(d). :param max_frequencies: maximum frequency for each dimension (1-tuple for sequences, 2-tuple for images, ...). If `None` values are derived from shape of p. :p...
_position_encodings
python
krasserm/perceiver-io
perceiver/model/core/position.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/position.py
Apache-2.0
def convert_checkpoint(save_dir, ckpt_url, tokenizer_name, id2label=None, label2id=None, **kwargs): """Convert a `LitTextClassifier` checkpoint to a persistent `PerceiverTextClassifier`.""" tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, verbose=False) tokenizer.save_pretrained(save_dir, **kwargs...
Convert a `LitTextClassifier` checkpoint to a persistent `PerceiverTextClassifier`.
convert_checkpoint
python
krasserm/perceiver-io
perceiver/model/text/classifier/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/text/classifier/huggingface.py
Apache-2.0
def convert_checkpoint(save_dir, ckpt_url, tokenizer_name, **kwargs): """Convert a `LitCausalLanguageModel` checkpoint to a persistent `PerceiverCausalLanguageModel`.""" tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, padding_side="left", verbose=False) tokenizer.save_pretrained(save_dir, **kwarg...
Convert a `LitCausalLanguageModel` checkpoint to a persistent `PerceiverCausalLanguageModel`.
convert_checkpoint
python
krasserm/perceiver-io
perceiver/model/text/clm/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/text/clm/huggingface.py
Apache-2.0
def convert_checkpoint(save_dir, ckpt_url, tokenizer_name, **kwargs): """Convert a `LitMaskedLanguageModel` checkpoint to a persistent `PerceiverMaskedLanguageModel`.""" tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, verbose=False) tokenizer.save_pretrained(save_dir, **kwargs) model = Perce...
Convert a `LitMaskedLanguageModel` checkpoint to a persistent `PerceiverMaskedLanguageModel`.
convert_checkpoint
python
krasserm/perceiver-io
perceiver/model/text/mlm/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/text/mlm/huggingface.py
Apache-2.0
def convert_model(save_dir, source_repo_id="deepmind/language-perceiver", **kwargs): """Convert a Hugging Face `PerceiverForMaskedLM` to a persistent `PerceiverMaskedLanguageModel`.""" src_model = transformers.PerceiverForMaskedLM.from_pretrained(source_repo_id) tgt_config = PerceiverMaskedLanguageModelCon...
Convert a Hugging Face `PerceiverForMaskedLM` to a persistent `PerceiverMaskedLanguageModel`.
convert_model
python
krasserm/perceiver-io
perceiver/model/text/mlm/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/text/mlm/huggingface.py
Apache-2.0
def convert_config(config: transformers.PerceiverConfig) -> MaskedLanguageModelConfig: """Convert a Hugging Face `PerceiverConfig` to a `PerceiverMaskedLanguageModelConfig`.""" assert config.hidden_act == "gelu" assert config.tie_word_embeddings encoder_config = TextEncoderConfig( vocab_size=c...
Convert a Hugging Face `PerceiverConfig` to a `PerceiverMaskedLanguageModelConfig`.
convert_config
python
krasserm/perceiver-io
perceiver/model/text/mlm/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/text/mlm/huggingface.py
Apache-2.0
def convert_checkpoint(save_dir, ckpt_url, image_processor, id2label=None, label2id=None, **kwargs): """Convert a `LitImageClassifier` checkpoint to a persistent `PerceiverImageClassifier`.""" image_processor.save_pretrained(save_dir, **kwargs) model = PerceiverImageClassifier.from_checkpoint(ckpt_url) ...
Convert a `LitImageClassifier` checkpoint to a persistent `PerceiverImageClassifier`.
convert_checkpoint
python
krasserm/perceiver-io
perceiver/model/vision/image_classifier/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/vision/image_classifier/huggingface.py
Apache-2.0
def convert_config(config: transformers.PerceiverConfig) -> ImageClassifierConfig: """Convert a Hugging Face `PerceiverConfig` to a `PerceiverImageClassifierConfig`.""" assert config.hidden_act == "gelu" encoder_config = ImageEncoderConfig( image_shape=(224, 224, 3), num_frequency_bands=64...
Convert a Hugging Face `PerceiverConfig` to a `PerceiverImageClassifierConfig`.
convert_config
python
krasserm/perceiver-io
perceiver/model/vision/image_classifier/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/vision/image_classifier/huggingface.py
Apache-2.0
def convert_model(save_dir, source_repo_id="deepmind/vision-perceiver-fourier", **kwargs): """Convert a Hugging Face `PerceiverForImageClassificationFourier` to a persistent `PerceiverImageClassifier`.""" src_model = transformers.PerceiverForImageClassificationFourier.from_pretrained(source_repo_id) tg...
Convert a Hugging Face `PerceiverForImageClassificationFourier` to a persistent `PerceiverImageClassifier`.
convert_model
python
krasserm/perceiver-io
perceiver/model/vision/image_classifier/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/vision/image_classifier/huggingface.py
Apache-2.0
def convert_model(save_dir, source_repo_id="deepmind/optical-flow-perceiver", **kwargs): """Convert a Hugging Face `PerceiverForOpticalFlow` to a persistent `OpticalFlowPerceiver`.""" src_model = transformers.PerceiverForOpticalFlow.from_pretrained(source_repo_id) tgt_config = OpticalFlowPerceiverConfig(co...
Convert a Hugging Face `PerceiverForOpticalFlow` to a persistent `OpticalFlowPerceiver`.
convert_model
python
krasserm/perceiver-io
perceiver/model/vision/optical_flow/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/vision/optical_flow/huggingface.py
Apache-2.0
def is_datetime_naive(dt): """ This method returns true if the datetime is naive else returns false """ if dt.tzinfo is None: return True else: return False
This method returns true if the datetime is naive else returns false
is_datetime_naive
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def _move_datetime(dt, direction, delta): """ Move datetime given delta by given direction """ if direction == 'next': dt = dt + delta elif direction == 'last': dt = dt - delta else: pass # raise some delorean error here return dt
Move datetime given delta by given direction
_move_datetime
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def move_datetime_month(dt, direction, num_shifts): """ Move datetime 1 month in the chosen direction. unit is a no-op, to keep the API the same as the day case """ delta = relativedelta(months=+num_shifts) return _move_datetime(dt, direction, delta)
Move datetime 1 month in the chosen direction. unit is a no-op, to keep the API the same as the day case
move_datetime_month
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def move_datetime_week(dt, direction, num_shifts): """ Move datetime 1 week in the chosen direction. unit is a no-op, to keep the API the same as the day case """ delta = relativedelta(weeks=+num_shifts) return _move_datetime(dt, direction, delta)
Move datetime 1 week in the chosen direction. unit is a no-op, to keep the API the same as the day case
move_datetime_week
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def move_datetime_year(dt, direction, num_shifts): """ Move datetime 1 year in the chosen direction. unit is a no-op, to keep the API the same as the day case """ delta = relativedelta(years=+num_shifts) return _move_datetime(dt, direction, delta)
Move datetime 1 year in the chosen direction. unit is a no-op, to keep the API the same as the day case
move_datetime_year
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def datetime_timezone(tz): """ This method given a timezone returns a localized datetime object. """ utc_datetime_naive = datetime.utcnow() # return a localized datetime to UTC utc_localized_datetime = localize(utc_datetime_naive, 'UTC') # normalize the datetime to given timezone normali...
This method given a timezone returns a localized datetime object.
datetime_timezone
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def localize(dt, tz): """ Given a naive datetime object this method will return a localized datetime object """ if not isinstance(tz, tzinfo): tz = pytz.timezone(tz) return tz.localize(dt)
Given a naive datetime object this method will return a localized datetime object
localize
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def normalize(dt, tz): """ Given a object with a timezone return a datetime object normalized to the proper timezone. This means take the give localized datetime and returns the datetime normalized to match the specified timezone. """ if not isinstance(tz, tzinfo): tz = pytz.timezon...
Given a object with a timezone return a datetime object normalized to the proper timezone. This means take the give localized datetime and returns the datetime normalized to match the specified timezone.
normalize
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def __getattr__(self, name): """ Implement __getattr__ to call `shift_date` function when function called does not exist """ func_parts = name.split('_') # is the func we are trying to call the right length? if len(func_parts) != 2: raise AttributeErro...
Implement __getattr__ to call `shift_date` function when function called does not exist
__getattr__
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def _shift_date(self, direction, unit, *args): """ Shift datetime in `direction` in _VALID_SHIFT_DIRECTIONS and by some unit in _VALID_SHIFTS and shift that amount by some multiple, defined by by args[0] if it exists """ this_module = sys.modules[__name__] num_sh...
Shift datetime in `direction` in _VALID_SHIFT_DIRECTIONS and by some unit in _VALID_SHIFTS and shift that amount by some multiple, defined by by args[0] if it exists
_shift_date
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def truncate(self, s): """ Truncate the delorian object to the nearest s (second, minute, hour, day, month, year) This is a destructive method, modifies the internal datetime object associated with the Delorean object. .. testsetup:: from datetime import da...
Truncate the delorian object to the nearest s (second, minute, hour, day, month, year) This is a destructive method, modifies the internal datetime object associated with the Delorean object. .. testsetup:: from datetime import datetime from delorean i...
truncate
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def shift(self, timezone): """ Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object, modifying the Delorean object and returning the modified object. .. testsetup:: from datetime import datetime from delorea...
Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object, modifying the Delorean object and returning the modified object. .. testsetup:: from datetime import datetime from delorean import Delorean .. doctest:...
shift
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def epoch(self): """ Returns the total seconds since epoch associated with the Delorean object. .. testsetup:: from datetime import datetime from delorean import Delorean .. doctest:: >>> d = Delorean(datetime(2015, 1, 1), timezone='US/Paci...
Returns the total seconds since epoch associated with the Delorean object. .. testsetup:: from datetime import datetime from delorean import Delorean .. doctest:: >>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific') >>> d.epoc...
epoch
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def humanize(self): """ Humanize relative to now: .. testsetup:: from datetime import timedelta from delorean import Delorean .. doctest:: >>> past = Delorean.utcnow() - timedelta(hours=1) >>> past.humanize() 'an hour ago' ...
Humanize relative to now: .. testsetup:: from datetime import timedelta from delorean import Delorean .. doctest:: >>> past = Delorean.utcnow() - timedelta(hours=1) >>> past.humanize() 'an hour ago'
humanize
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def parse(datetime_str, timezone=None, isofirst=True, dayfirst=True, yearfirst=True): """ Parses a datetime string and returns a `Delorean` object. :param datetime_str: The string to be interpreted into a `Delorean` object. :param timezone: Pass this parameter and the returned Delorean object will be n...
Parses a datetime string and returns a `Delorean` object. :param datetime_str: The string to be interpreted into a `Delorean` object. :param timezone: Pass this parameter and the returned Delorean object will be normalized to this timezone. Any offsets passed as part of datetime_str will be ignore...
parse
python
myusuf3/delorean
delorean/interface.py
https://github.com/myusuf3/delorean/blob/master/delorean/interface.py
MIT
def stops(freq, interval=1, count=None, wkst=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, timezone='UTC', start=None, stop=None): """ This will create a list of delorean ...
This will create a list of delorean objects the apply to setting possed in.
stops
python
myusuf3/delorean
delorean/interface.py
https://github.com/myusuf3/delorean/blob/master/delorean/interface.py
MIT
def test_timezone_delorean_to_datetime_to_delorean_non_utc(self): """Test if when you create Delorean object from Delorean's datetime it still behaves the same """ d1 = delorean.Delorean(timezone='America/Chicago') d2 = delorean.Delorean(d1.datetime) # these deloreans sh...
Test if when you create Delorean object from Delorean's datetime it still behaves the same
test_timezone_delorean_to_datetime_to_delorean_non_utc
python
myusuf3/delorean
tests/delorean_tests.py
https://github.com/myusuf3/delorean/blob/master/tests/delorean_tests.py
MIT
def test_stops_bymonth(self): """Test if create stops, checks bymonth, bymonthday, count and start parameters work properly """ days = list(delorean.interface.stops( delorean.MONTHLY, bymonth=(1, 4, 7, 10), bymonthday=15, count=4, ...
Test if create stops, checks bymonth, bymonthday, count and start parameters work properly
test_stops_bymonth
python
myusuf3/delorean
tests/delorean_tests.py
https://github.com/myusuf3/delorean/blob/master/tests/delorean_tests.py
MIT
def create_table(): """ Creates the 'images' table in the SQLite database if it doesn't exist. """ with connection: connection.execute(''' CREATE TABLE IF NOT EXISTS images ( id INTEGER PRIMARY KEY, filename TEXT NOT NULL, file_path TEX...
Creates the 'images' table in the SQLite database if it doesn't exist.
create_table
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def file_generator(directory): """ Generates file paths for all files in the specified directory and its subdirectories. :param directory: The directory path to search for files. :return: A generator yielding file paths. """ logger.debug(f"Generating file paths for directory: {directory}") ...
Generates file paths for all files in the specified directory and its subdirectories. :param directory: The directory path to search for files. :return: A generator yielding file paths.
file_generator
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def hydrate_cache(directory, cache_file_path): """ Loads or generates a cache of file paths for the specified directory. :param directory: The directory path to search for files. :param cache_file_path: The path to the cache file. :return: A list of cached file paths. """ logger.info(f"Hydr...
Loads or generates a cache of file paths for the specified directory. :param directory: The directory path to search for files. :param cache_file_path: The path to the cache file. :return: A list of cached file paths.
hydrate_cache
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def update_db(image): """ Updates the database with the image embeddings. :param image: A dictionary containing image information. """ try: embeddings_blob = sqlite3.Binary(msgpack.dumps(image.get('embeddings', []))) with sqlite3.connect(SQLITE_DB_FILEPATH) as conn: conn...
Updates the database with the image embeddings. :param image: A dictionary containing image information.
update_db
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def process_image(file_path): """ Processes an image file by extracting metadata and inserting it into the database. :param file_path: The path to the image file. """ file = os.path.basename(file_path) file_date = time.ctime(os.path.getmtime(file_path)) with open(file_path, 'rb') as f: ...
Processes an image file by extracting metadata and inserting it into the database. :param file_path: The path to the image file.
process_image
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def process_embeddings(photo): """ Processes image embeddings by uploading them to the embedding server and updating the database. :param photo: A dictionary containing photo information. """ logger.debug(f"Processing photo: {photo['filename']}") if photo['embeddings']: logger.debug(f"P...
Processes image embeddings by uploading them to the embedding server and updating the database. :param photo: A dictionary containing photo information.
process_embeddings
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def main(): """ Main function to process images and embeddings. """ cache_start_time = time.time() cached_files = hydrate_cache(SOURCE_IMAGE_DIRECTORY, FILELIST_CACHE_FILEPATH) cache_end_time = time.time() logger.info(f"Cache operation took {cache_end_time - cache_start_time:.2f} seconds") ...
Main function to process images and embeddings.
main
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def serve_image(filename): """ Serve a resized image directly from the filesystem outside of the static directory. """ # Construct the full file path. Be careful with security implications. # Ensure that you validate `filename` to prevent directory traversal attacks. filepath = os.path.join(SO...
Serve a resized image directly from the filesystem outside of the static directory.
serve_image
python
harperreed/photo-similarity-search
start_web.py
https://github.com/harperreed/photo-similarity-search/blob/master/start_web.py
MIT
def preprocess_rpn_training_data(self): """ Discard samples which don't have current classes, which will not be used for training. Valid sample_id is stored in self.sample_id_list """ self.logger.info('Loading %s samples from %s ...' % (self.mode, self.label_dir)) for idx...
Discard samples which don't have current classes, which will not be used for training. Valid sample_id is stored in self.sample_id_list
preprocess_rpn_training_data
python
sshaoshuai/PointRCNN
lib/datasets/kitti_rcnn_dataset.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/datasets/kitti_rcnn_dataset.py
MIT
def filtrate_objects(self, obj_list): """ Discard objects which are not in self.classes (or its similar classes) :param obj_list: list :return: list """ type_whitelist = self.classes if self.mode == 'TRAIN' and cfg.INCLUDE_SIMILAR_TYPE: type_whitelist ...
Discard objects which are not in self.classes (or its similar classes) :param obj_list: list :return: list
filtrate_objects
python
sshaoshuai/PointRCNN
lib/datasets/kitti_rcnn_dataset.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/datasets/kitti_rcnn_dataset.py
MIT
def get_valid_flag(pts_rect, pts_img, pts_rect_depth, img_shape): """ Valid point should be in the image (and in the PC_AREA_SCOPE) :param pts_rect: :param pts_img: :param pts_rect_depth: :param img_shape: :return: """ val_flag_1 = np.logical_and(p...
Valid point should be in the image (and in the PC_AREA_SCOPE) :param pts_rect: :param pts_img: :param pts_rect_depth: :param img_shape: :return:
get_valid_flag
python
sshaoshuai/PointRCNN
lib/datasets/kitti_rcnn_dataset.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/datasets/kitti_rcnn_dataset.py
MIT
def aug_roi_by_noise(self, roi_info): """ add noise to original roi to get aug_box3d :param roi_info: :return: """ roi_box3d, gt_box3d = roi_info['roi_box3d'], roi_info['gt_box3d'] original_iou = roi_info['iou3d'] temp_iou = cnt = 0 pos_thresh = mi...
add noise to original roi to get aug_box3d :param roi_info: :return:
aug_roi_by_noise
python
sshaoshuai/PointRCNN
lib/datasets/kitti_rcnn_dataset.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/datasets/kitti_rcnn_dataset.py
MIT
def distance_based_proposal(self, scores, proposals, order): """ propose rois in two area based on the distance :param scores: (N) :param proposals: (N, 7) :param order: (N) """ nms_range_list = [0, 40.0, 80.0] pre_tot_top_n = cfg[self.mode].RPN_PRE_NMS_T...
propose rois in two area based on the distance :param scores: (N) :param proposals: (N, 7) :param order: (N)
distance_based_proposal
python
sshaoshuai/PointRCNN
lib/rpn/proposal_layer.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/rpn/proposal_layer.py
MIT
def data_augmentation(self, pts, rois, gt_of_rois): """ :param pts: (B, M, 512, 3) :param rois: (B, M. 7) :param gt_of_rois: (B, M, 7) :return: """ batch_size, boxes_num = pts.shape[0], pts.shape[1] # rotation augmentation angles = (torch.rand((ba...
:param pts: (B, M, 512, 3) :param rois: (B, M. 7) :param gt_of_rois: (B, M, 7) :return:
data_augmentation
python
sshaoshuai/PointRCNN
lib/rpn/proposal_target_layer.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/rpn/proposal_target_layer.py
MIT
def decode_bbox_target(roi_box3d, pred_reg, loc_scope, loc_bin_size, num_head_bin, anchor_size, get_xz_fine=True, get_y_by_bin=False, loc_y_scope=0.5, loc_y_bin_size=0.25, get_ry_fine=False): """ :param roi_box3d: (N, 7) :param pred_reg: (N, C) :param loc_scope: :param loc_bin...
:param roi_box3d: (N, 7) :param pred_reg: (N, C) :param loc_scope: :param loc_bin_size: :param num_head_bin: :param anchor_size: :param get_xz_fine: :param get_y_by_bin: :param loc_y_scope: :param loc_y_bin_size: :param get_ry_fine: :return:
decode_bbox_target
python
sshaoshuai/PointRCNN
lib/utils/bbox_transform.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/bbox_transform.py
MIT
def camera_dis_to_rect(self, u, v, d): """ Can only process valid u, v, d, which means u, v can not beyond the image shape, reprojection error 0.02 :param u: (N) :param v: (N) :param d: (N), the distance between camera and 3d points, d^2 = x^2 + y^2 + z^2 :return: ...
Can only process valid u, v, d, which means u, v can not beyond the image shape, reprojection error 0.02 :param u: (N) :param v: (N) :param d: (N), the distance between camera and 3d points, d^2 = x^2 + y^2 + z^2 :return:
camera_dis_to_rect
python
sshaoshuai/PointRCNN
lib/utils/calibration.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/calibration.py
MIT
def dist_to_plane(plane, points): """ Calculates the signed distance from a 3D plane to each point in a list of points :param plane: (a, b, c, d) :param points: (N, 3) :return: (N), signed distance of each point to the plane """ a, b, c, d = plane points = np.array(points) x = point...
Calculates the signed distance from a 3D plane to each point in a list of points :param plane: (a, b, c, d) :param points: (N, 3) :return: (N), signed distance of each point to the plane
dist_to_plane
python
sshaoshuai/PointRCNN
lib/utils/kitti_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/kitti_utils.py
MIT
def rotate_pc_along_y(pc, rot_angle): """ params pc: (N, 3+C), (N, 3) is in the rectified camera coordinate params rot_angle: rad scalar Output pc: updated pc with XYZ rotated """ cosval = np.cos(rot_angle) sinval = np.sin(rot_angle) rotmat = np.array([[cosval, -sinval], [sinval, cosval]...
params pc: (N, 3+C), (N, 3) is in the rectified camera coordinate params rot_angle: rad scalar Output pc: updated pc with XYZ rotated
rotate_pc_along_y
python
sshaoshuai/PointRCNN
lib/utils/kitti_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/kitti_utils.py
MIT
def rotate_pc_along_y_torch(pc, rot_angle): """ :param pc: (N, 512, 3 + C) :param rot_angle: (N) :return: TODO: merge with rotate_pc_along_y_torch in bbox_transform.py """ cosa = torch.cos(rot_angle).view(-1, 1) # (N, 1) sina = torch.sin(rot_angle).view(-1, 1) # (N, 1) raw_1 = tor...
:param pc: (N, 512, 3 + C) :param rot_angle: (N) :return: TODO: merge with rotate_pc_along_y_torch in bbox_transform.py
rotate_pc_along_y_torch
python
sshaoshuai/PointRCNN
lib/utils/kitti_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/kitti_utils.py
MIT
def get_iou3d(corners3d, query_corners3d, need_bev=False): """ :param corners3d: (N, 8, 3) in rect coords :param query_corners3d: (M, 8, 3) :return: """ from shapely.geometry import Polygon A, B = corners3d, query_corners3d N, M = A.shape[0], B.shape[0] iou3d = np.zeros((N, M), d...
:param corners3d: (N, 8, 3) in rect coords :param query_corners3d: (M, 8, 3) :return:
get_iou3d
python
sshaoshuai/PointRCNN
lib/utils/kitti_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/kitti_utils.py
MIT
def forward(self, input, target): """ :param input: (N), logit :param target: (N), {0, 1} :return: """ input = torch.sigmoid(input.view(-1)) target = target.float().view(-1) mask = (target != self.ignore_target).float() return 1.0 - (torch.min(inpu...
:param input: (N), logit :param target: (N), {0, 1} :return:
forward
python
sshaoshuai/PointRCNN
lib/utils/loss_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/loss_utils.py
MIT
def __init__(self, gamma=2.0, alpha=0.25): """Constructor. Args: gamma: exponent of the modulating factor (1 - p_t) ^ gamma. alpha: optional alpha weighting factor to balance positives vs negatives. all_zero_negative: bool. if True, will treat all zero as background. ...
Constructor. Args: gamma: exponent of the modulating factor (1 - p_t) ^ gamma. alpha: optional alpha weighting factor to balance positives vs negatives. all_zero_negative: bool. if True, will treat all zero as background. else, will treat first label as background...
__init__
python
sshaoshuai/PointRCNN
lib/utils/loss_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/loss_utils.py
MIT
def forward(self, prediction_tensor, target_tensor, weights): """Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing the predicted logits for each class ...
Compute loss function. Args: prediction_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing the predicted logits for each class target_tensor: A float tensor of shape [batch_size, num_anchors, num_classes] representing one-hot ...
forward
python
sshaoshuai/PointRCNN
lib/utils/loss_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/loss_utils.py
MIT
def get_reg_loss(pred_reg, reg_label, loc_scope, loc_bin_size, num_head_bin, anchor_size, get_xz_fine=True, get_y_by_bin=False, loc_y_scope=0.5, loc_y_bin_size=0.25, get_ry_fine=False): """ Bin-based 3D bounding boxes regression loss. See https://arxiv.org/abs/1812.04244 for more details. ...
Bin-based 3D bounding boxes regression loss. See https://arxiv.org/abs/1812.04244 for more details. :param pred_reg: (N, C) :param reg_label: (N, 7) [dx, dy, dz, h, w, l, ry] :param loc_scope: constant :param loc_bin_size: constant :param num_head_bin: constant :param anchor_size: (N, ...
get_reg_loss
python
sshaoshuai/PointRCNN
lib/utils/loss_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/loss_utils.py
MIT
def to_bev_box2d(self, oblique=True, voxel_size=0.1): """ :param bev_shape: (2) for bev shape (h, w), => (y_max, x_max) in image :param voxel_size: float, 0.1m :param oblique: :return: box2d (4, 2)/ (4) in image coordinate """ if oblique: corners3d = s...
:param bev_shape: (2) for bev shape (h, w), => (y_max, x_max) in image :param voxel_size: float, 0.1m :param oblique: :return: box2d (4, 2)/ (4) in image coordinate
to_bev_box2d
python
sshaoshuai/PointRCNN
lib/utils/object3d.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/object3d.py
MIT
def nms_gpu(boxes, scores, thresh): """ :param boxes: (N, 5) [x1, y1, x2, y2, ry] :param scores: (N) :param thresh: :return: """ # areas = (x2 - x1) * (y2 - y1) order = scores.sort(0, descending=True)[1] boxes = boxes[order].contiguous() keep = torch.LongTensor(boxes.size(0)) ...
:param boxes: (N, 5) [x1, y1, x2, y2, ry] :param scores: (N) :param thresh: :return:
nms_gpu
python
sshaoshuai/PointRCNN
lib/utils/iou3d/iou3d_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/iou3d/iou3d_utils.py
MIT
def roipool3d_gpu(pts, pts_feature, boxes3d, pool_extra_width, sampled_pt_num=512): """ :param pts: (B, N, 3) :param pts_feature: (B, N, C) :param boxes3d: (B, M, 7) :param pool_extra_width: float :param sampled_pt_num: int :return: pooled_features: (B, M, 512, 3 + C) pooled_...
:param pts: (B, N, 3) :param pts_feature: (B, N, C) :param boxes3d: (B, M, 7) :param pool_extra_width: float :param sampled_pt_num: int :return: pooled_features: (B, M, 512, 3 + C) pooled_empty_flag: (B, M)
roipool3d_gpu
python
sshaoshuai/PointRCNN
lib/utils/roipool3d/roipool3d_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/roipool3d/roipool3d_utils.py
MIT
def pts_in_boxes3d_cpu(pts, boxes3d): """ :param pts: (N, 3) in rect-camera coords :param boxes3d: (M, 7) :return: boxes_pts_mask_list: (M), list with [(N), (N), ..] """ if not pts.is_cuda: pts = pts.float().contiguous() boxes3d = boxes3d.float().contiguous() pts_flag = t...
:param pts: (N, 3) in rect-camera coords :param boxes3d: (M, 7) :return: boxes_pts_mask_list: (M), list with [(N), (N), ..]
pts_in_boxes3d_cpu
python
sshaoshuai/PointRCNN
lib/utils/roipool3d/roipool3d_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/roipool3d/roipool3d_utils.py
MIT
def roipool_pc_cpu(pts, pts_feature, boxes3d, sampled_pt_num): """ :param pts: (N, 3) :param pts_feature: (N, C) :param boxes3d: (M, 7) :param sampled_pt_num: int :return: """ pts = pts.cpu().float().contiguous() pts_feature = pts_feature.cpu().float().contiguous() boxes3d = boxe...
:param pts: (N, 3) :param pts_feature: (N, C) :param boxes3d: (M, 7) :param sampled_pt_num: int :return:
roipool_pc_cpu
python
sshaoshuai/PointRCNN
lib/utils/roipool3d/roipool3d_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/roipool3d/roipool3d_utils.py
MIT
def roipool3d_cpu(boxes3d, pts, pts_feature, pts_extra_input, pool_extra_width, sampled_pt_num=512, canonical_transform=True): """ :param boxes3d: (N, 7) :param pts: (N, 3) :param pts_feature: (N, C) :param pts_extra_input: (N, C2) :param pool_extra_width: constant :param s...
:param boxes3d: (N, 7) :param pts: (N, 3) :param pts_feature: (N, C) :param pts_extra_input: (N, C2) :param pool_extra_width: constant :param sampled_pt_num: constant :return:
roipool3d_cpu
python
sshaoshuai/PointRCNN
lib/utils/roipool3d/roipool3d_utils.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/utils/roipool3d/roipool3d_utils.py
MIT
def extend_body_states( self, extend_body_pos: torch.Tensor, extend_body_parent_ids: list[int], ): """ This function is for appending the link states to the robot state. For example, the H1 robot doesn't have hands and a head in its robot state. However, we are still ...
This function is for appending the link states to the robot state. For example, the H1 robot doesn't have hands and a head in its robot state. However, we are still interested in computing its error and considering these as important key points. Thus, we will use this function to add the head a...
extend_body_states
python
NVlabs/HOVER
neural_wbc/core/neural_wbc/core/body_state.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/body_state.py
Apache-2.0
def get_observations(self) -> torch.Tensor: """Gets policy observations for each environment based on the mode.""" if self._mode.is_distill_mode(): return self.get_student_observations() return self.get_teacher_observations()
Gets policy observations for each environment based on the mode.
get_observations
python
NVlabs/HOVER
neural_wbc/core/neural_wbc/core/environment_wrapper.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/environment_wrapper.py
Apache-2.0
def _init_empty_frames(self, frame: Frame): """Initialize empty frame buffers to store trajectory data for all environments. Creates zero-filled tensors/arrays sized to hold the maximum possible number of frames and environments, matching the data types and shapes of the input frame. ""...
Initialize empty frame buffers to store trajectory data for all environments. Creates zero-filled tensors/arrays sized to hold the maximum possible number of frames and environments, matching the data types and shapes of the input frame.
_init_empty_frames
python
NVlabs/HOVER
neural_wbc/core/neural_wbc/core/evaluator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py
Apache-2.0
def add_frame(self, frame: Frame): """Add a frame to each trajectory in the episode. Args: frame (Frame): Frame containing trajectory data for all environments at this timestep """ # Initialize frame buffers if this is the first frame being added if len(self._frames)...
Add a frame to each trajectory in the episode. Args: frame (Frame): Frame containing trajectory data for all environments at this timestep
add_frame
python
NVlabs/HOVER
neural_wbc/core/neural_wbc/core/evaluator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py
Apache-2.0
def complete(self): """Aggregate frames into episode data more efficiently. Instead of splitting data environment by environment, we can use tensor operations to split all environments at once, significantly reducing loop overhead. """ num_envs = self.max_frames_per_env.shape[0]...
Aggregate frames into episode data more efficiently. Instead of splitting data environment by environment, we can use tensor operations to split all environments at once, significantly reducing loop overhead.
complete
python
NVlabs/HOVER
neural_wbc/core/neural_wbc/core/evaluator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py
Apache-2.0
def filter(self, ids: list[int]) -> Episode: """Filter episode data to only include specified environment indices.""" # Create new empty episode to store filtered data filtered = Episode(self.max_frames_per_env) # Iterate through all attributes of this episode for attr, data in ...
Filter episode data to only include specified environment indices.
filter
python
NVlabs/HOVER
neural_wbc/core/neural_wbc/core/evaluator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py
Apache-2.0
def trim(self, terminated_frame: torch.Tensor, end_id: int): """Helper method to cut data based on terminated frame. This function creates a new Episode object with truncated data. For each environment, it keeps only the frames up to the termination point specified in terminated_frame. ...
Helper method to cut data based on terminated frame. This function creates a new Episode object with truncated data. For each environment, it keeps only the frames up to the termination point specified in terminated_frame. It then further filters to keep only environments up to end_id. ...
trim
python
NVlabs/HOVER
neural_wbc/core/neural_wbc/core/evaluator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py
Apache-2.0