repo_name
stringlengths
7
71
file_path
stringlengths
5
118
context
list
import_statement
stringlengths
45
12.5k
token_num
int64
641
99.4k
cropped_code
stringlengths
44
17k
all_code
stringlengths
43
754k
next_line
stringlengths
2
330
gold_snippet_index
int64
0
68
created_at
stringlengths
25
25
level
stringclasses
9 values
microsoft/Everything-of-Thoughts-XoT
xot_all_in_one/xot/controller/controller.py
[ { "identifier": "IO_Solver", "path": "xot_all_in_one/xot/controller/solver/io_solver.py", "snippet": "class IO_Solver:\n def __init__(self, args, gpt, game, prompter, parser, to_print=False):\n self.args = args\n self.gpt = gpt\n self.game = game\n self.prompter = prompter...
import os import json import itertools import random import ast import re import numpy as np import pandas as pd from collections import Counter from .utils import * from .solver.io_solver import IO_Solver from .solver.cot_solver import CoT_Solver from .solver.tot_solver import ToT_Solver from .solver.got_solver import GoT_Solver from .solver.xot_solver import XoT_Solver
9,493
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. class Controller: """ Controller class to manage the execution flow This involves language models, operations, prompting, and parsing. """ def __init__(self, config, gpt, game, prompter, parser): self.config = config self.gpt = gpt self.game = game self.prompter = prompter self.parser = parser def initial_logs(self, config): if config.method == 'io' or config.method == 'cot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_sample{config.param.n_generate_sample}_multi{config.multi_solution}_start{config.task.task_start_index}_end{config.task.task_end_index}.json' elif config.method == 'tot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_propose{config.param.n_generate_sample}_value{config.param.n_evaluate_sample}_greedy{config.param.n_select_sample}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' elif config.method == 'got': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_multi{config.multi_solution}_propose{config.param.n_generate_sample}_value{config.param.n_evaluate_sample}_greedy{config.param.n_select_sample}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' elif config.method == 'xot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_multi{config.multi_solution}_revised{config.xot.revised}_reviseTimes{config.xot.revise_times}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' else: raise ValueError("invalid method") os.makedirs(os.path.dirname(file), exist_ok=True) return file def initial_solver(self, config): if config.method == 'io': return IO_Solver(config, self.gpt, self.game, self.prompter, self.parser) elif config.method == 'cot': return CoT_Solver(config, self.gpt, self.game, self.prompter, self.parser) elif config.method == 'tot':
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. class Controller: """ Controller class to manage the execution flow This involves language models, operations, prompting, and parsing. """ def __init__(self, config, gpt, game, prompter, parser): self.config = config self.gpt = gpt self.game = game self.prompter = prompter self.parser = parser def initial_logs(self, config): if config.method == 'io' or config.method == 'cot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_sample{config.param.n_generate_sample}_multi{config.multi_solution}_start{config.task.task_start_index}_end{config.task.task_end_index}.json' elif config.method == 'tot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_propose{config.param.n_generate_sample}_value{config.param.n_evaluate_sample}_greedy{config.param.n_select_sample}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' elif config.method == 'got': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_multi{config.multi_solution}_propose{config.param.n_generate_sample}_value{config.param.n_evaluate_sample}_greedy{config.param.n_select_sample}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' elif config.method == 'xot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_multi{config.multi_solution}_revised{config.xot.revised}_reviseTimes{config.xot.revise_times}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' else: raise ValueError("invalid method") os.makedirs(os.path.dirname(file), exist_ok=True) return file def initial_solver(self, config): if config.method == 'io': return IO_Solver(config, self.gpt, self.game, self.prompter, self.parser) elif config.method == 'cot': return CoT_Solver(config, self.gpt, self.game, self.prompter, self.parser) elif config.method == 'tot':
return ToT_Solver(config, self.gpt, self.game, self.prompter, self.parser)
2
2023-11-08 09:48:34+00:00
12k
UMass-Foundation-Model/CoVLM
transformers/src/transformers/models/opt/modeling_tf_opt.py
[ { "identifier": "get_tf_activation", "path": "transformers/src/transformers/activations_tf.py", "snippet": "def get_tf_activation(activation_string):\n if activation_string in ACT2FN:\n return ACT2FN[activation_string]\n else:\n raise KeyError(f\"function {activation_string} not foun...
from typing import Optional, Tuple, Union from ...activations_tf import get_tf_activation from ...modeling_tf_outputs import TFBaseModelOutputWithPast, TFCausalLMOutputWithPast from ...modeling_tf_utils import ( TFCausalLanguageModelingLoss, TFModelInputType, TFPreTrainedModel, TFSharedEmbeddings, keras_serializable, unpack_inputs, ) from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax from ...utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from .configuration_opt import OPTConfig import numpy as np import tensorflow as tf
9,912
) @add_start_docstrings( "The bare TF OPT Model outputting raw hidden-states without any specific head on top.", OPT_START_DOCSTRING, ) @keras_serializable class TFOPTModel(TFOPTPreTrainedModel): config_class = OPTConfig def __init__(self, config: OPTConfig, **kwargs): super().__init__(config, **kwargs) self.config = config self.model = TFOPTMainLayer(config, name="model") def get_input_embeddings(self): return self.model.decoder.embed_tokens def set_input_embeddings(self, new_embeddings): self.model.set_input_embeddings(new_embeddings) @unpack_inputs @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=TFBaseModelOutputWithPast, config_class=_CONFIG_FOR_DOC, expected_output=_EXPECTED_OUTPUT_SHAPE, ) def call( self, input_ids: TFModelInputType | None = None, attention_mask: np.ndarray | tf.Tensor | None = None, head_mask: np.ndarray | tf.Tensor | None = None, past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None, inputs_embeds: np.ndarray | tf.Tensor | None = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, training: Optional[bool] = False, **kwargs, ) -> Union[TFBaseModelOutputWithPast, Tuple[tf.Tensor]]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.model( input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training, ) if not return_dict: return outputs return TFBaseModelOutputWithPast( last_hidden_state=outputs.last_hidden_state, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def serving_output(self, output): pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None return TFBaseModelOutputWithPast( last_hidden_state=output.last_hidden_state, past_key_values=pkv, hidden_states=hs, attentions=attns, ) @add_start_docstrings( """ The OPT Model transformer with a language modeling head on top. """, OPT_START_DOCSTRING, ) @keras_serializable class TFOPTForCausalLM(TFOPTPreTrainedModel, TFCausalLanguageModelingLoss): config_class = OPTConfig def __init__(self, config: OPTConfig, **kwargs): super().__init__(config, **kwargs) self.config = config self.model = TFOPTMainLayer(config, name="model") def get_output_embeddings(self): return self.model.get_input_embeddings() def prepare_inputs_for_generation(self, inputs, past_key_values=None, use_cache=None, **kwargs): attention_mask = kwargs.get("attention_mask", None) # only last token for inputs_ids if past is defined in kwargs if past_key_values: inputs = tf.expand_dims(inputs[:, -1], -1) return { "input_ids": inputs, "attention_mask": attention_mask, "past_key_values": past_key_values, "use_cache": use_cache, } @unpack_inputs
# coding=utf-8 # Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ TF 2.0 OPT model.""" from __future__ import annotations # Public API logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "facebook/opt-350m" _CONFIG_FOR_DOC = "OPTConfig" # Base model docstring _EXPECTED_OUTPUT_SHAPE = [1, 8, 1024] # Causal LM output _CAUSAL_LM_EXPECTED_OUTPUT = ( "Hey, are you conscious? Can you talk to me?\nI'm not conscious. I'm just a little bit of a weirdo." ) LARGE_NEGATIVE = -1e8 def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0): """ Make causal mask used for bi-directional self-attention. """ bsz = input_ids_shape[0] tgt_len = input_ids_shape[1] # We need triu with k = 1 but TF expects known compile-time dims for that, so we hack around it mask = tf.fill((tgt_len, tgt_len), tf.cast(LARGE_NEGATIVE, tf.float32)) mask = tf.linalg.band_part(mask, 0, -1) - tf.linalg.band_part(mask, 0, 0) if past_key_values_length > 0: mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1) return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1)) # Copied from transformers.models.bart.modeling_tf_bart._expand_mask def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None): """ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. """ src_len = shape_list(mask)[1] tgt_len = tgt_len if tgt_len is not None else src_len one_cst = tf.constant(1.0) mask = tf.cast(mask, dtype=one_cst.dtype) expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1)) return (one_cst - expanded_mask) * LARGE_NEGATIVE class TFOPTLearnedPositionalEmbedding(tf.keras.layers.Embedding): """ This module learns positional embeddings up to a fixed maximum size. """ def __init__(self, num_embeddings: int, embedding_dim: int, **kwargs): # OPT is set up so that if padding_idx is specified then offset the embedding ids by 2 # and adjust num_embeddings appropriately. Other models don't have this hack self.offset = 2 super().__init__(num_embeddings + self.offset, embedding_dim, **kwargs) def call(self, attention_mask, past_key_values_length: int = 0): """`input_ids_shape` is expected to be [bsz x seqlen].""" attention_mask = tf.cast(attention_mask, tf.int64) # create positions depending on attention_mask positions = tf.math.cumsum(attention_mask, axis=1) * attention_mask - 1 # cut positions if `past_key_values_length` is > 0 positions = positions[:, past_key_values_length:] return super().call(positions + self.offset) # Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with Bart->OPT class TFOPTAttention(tf.keras.layers.Layer): """Multi-headed attention from "Attention Is All You Need""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, **kwargs, ): super().__init__(**kwargs) self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = tf.keras.layers.Dropout(dropout) self.head_dim = embed_dim // num_heads if (self.head_dim * num_heads) != self.embed_dim: raise ValueError( f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" f" and `num_heads`: {num_heads})." ) self.scaling = self.head_dim**-0.5 self.is_decoder = is_decoder self.k_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj") self.q_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj") self.v_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj") self.out_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj") def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int): return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3)) def call( self, hidden_states: tf.Tensor, key_value_states: tf.Tensor | None = None, past_key_value: Tuple[Tuple[tf.Tensor]] | None = None, attention_mask: tf.Tensor | None = None, layer_head_mask: tf.Tensor | None = None, training: Optional[bool] = False, ) -> Tuple[tf.Tensor, tf.Tensor | None]: """Input shape: Batch x Time x Channel""" # if key_value_states are provided this layer is used as a cross-attention layer # for the decoder is_cross_attention = key_value_states is not None bsz, tgt_len, embed_dim = shape_list(hidden_states) # get query proj query_states = self.q_proj(hidden_states) * self.scaling # get key, value proj if is_cross_attention and past_key_value is not None: # reuse k,v, cross_attentions key_states = past_key_value[0] value_states = past_key_value[1] elif is_cross_attention: # cross_attentions key_states = self._shape(self.k_proj(key_value_states), -1, bsz) value_states = self._shape(self.v_proj(key_value_states), -1, bsz) elif past_key_value is not None: # reuse k, v, self_attention key_states = self._shape(self.k_proj(hidden_states), -1, bsz) value_states = self._shape(self.v_proj(hidden_states), -1, bsz) key_states = tf.concat([past_key_value[0], key_states], axis=2) value_states = tf.concat([past_key_value[1], value_states], axis=2) else: # self_attention key_states = self._shape(self.k_proj(hidden_states), -1, bsz) value_states = self._shape(self.v_proj(hidden_states), -1, bsz) if self.is_decoder: # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states. # Further calls to cross_attention layer can then reuse all cross-attention # key/value_states (first "if" case) # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of # all previous decoder key/value_states. Further calls to uni-directional self-attention # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) # if encoder bi-directional self-attention `past_key_value` is always `None` past_key_value = (key_states, value_states) proj_shape = (bsz * self.num_heads, -1, self.head_dim) query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape) key_states = tf.reshape(key_states, proj_shape) value_states = tf.reshape(value_states, proj_shape) src_len = shape_list(key_states)[1] attn_weights = tf.matmul(query_states, key_states, transpose_b=True) tf.debugging.assert_equal( shape_list(attn_weights), [bsz * self.num_heads, tgt_len, src_len], message=( f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is" f" {shape_list(attn_weights)}" ), ) if attention_mask is not None: tf.debugging.assert_equal( shape_list(attention_mask), [bsz, 1, tgt_len, src_len], message=( f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is" f" {shape_list(attention_mask)}" ), ) attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype) attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) attn_weights = stable_softmax(attn_weights, axis=-1) if layer_head_mask is not None: tf.debugging.assert_equal( shape_list(layer_head_mask), [self.num_heads], message=( f"Head mask for a single layer should be of size {(self.num_heads)}, but is" f" {shape_list(layer_head_mask)}" ), ) attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( attn_weights, (bsz, self.num_heads, tgt_len, src_len) ) attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) attn_probs = self.dropout(attn_weights, training=training) attn_output = tf.matmul(attn_probs, value_states) tf.debugging.assert_equal( shape_list(attn_output), [bsz * self.num_heads, tgt_len, self.head_dim], message=( f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" f" {shape_list(attn_output)}" ), ) attn_output = tf.transpose( tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3) ) attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim)) attn_output = self.out_proj(attn_output) attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) return attn_output, attn_weights, past_key_value class TFOPTDecoderLayer(tf.keras.layers.Layer): def __init__(self, config: OPTConfig, **kwargs): super().__init__(**kwargs) self.do_layer_norm_before = config.do_layer_norm_before self.embed_dim = config.hidden_size self.self_attn = TFOPTAttention( embed_dim=self.embed_dim, num_heads=config.num_attention_heads, dropout=config.attention_dropout, name="self_attn", is_decoder=True, ) self.dropout = tf.keras.layers.Dropout(config.dropout) self.activation_fn = get_tf_activation(config.activation_function) self.self_attn_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm") self.fc1 = tf.keras.layers.Dense(config.ffn_dim, name="fc1") self.fc2 = tf.keras.layers.Dense(self.embed_dim, name="fc2") self.final_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm") def call( self, hidden_states: tf.Tensor, attention_mask: np.ndarray | tf.Tensor | None = None, layer_head_mask: tf.Tensor | None = None, past_key_value: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None, training: Optional[bool] = False, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, ) -> Tuple[tf.Tensor, tf.Tensor, Tuple[Tuple[tf.Tensor]]]: """ Args: hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`tf.Tensor`, *optional*): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. layer_head_mask (`tf.Tensor`, *optional*): mask for attention heads in a given layer of size `(decoder_attention_heads,)` past_key_value (`Tuple(tf.Tensor)`, *optional*): cached past key and value projection states training (`bool`, *optional*, defaults to `False`): Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation). """ residual = hidden_states # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention if self.do_layer_norm_before: hidden_states = self.self_attn_layer_norm(hidden_states) # Self Attention # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None # add present self-attn cache to positions 1,2 of present_key_value tuple hidden_states, self_attn_weights, present_key_value = self.self_attn( hidden_states=hidden_states, past_key_value=self_attn_past_key_value, attention_mask=attention_mask, layer_head_mask=layer_head_mask, ) hidden_states = self.dropout(hidden_states, training=training) hidden_states = residual + hidden_states # 350m applies layer norm AFTER attention if not self.do_layer_norm_before: hidden_states = self.self_attn_layer_norm(hidden_states) # Fully Connected residual = hidden_states # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention if self.do_layer_norm_before: hidden_states = self.final_layer_norm(hidden_states) hidden_states = self.fc1(hidden_states) hidden_states = self.activation_fn(hidden_states) hidden_states = self.fc2(hidden_states) hidden_states = self.dropout(hidden_states, training=training) hidden_states = residual + hidden_states # 350m applies layer norm AFTER attention if not self.do_layer_norm_before: hidden_states = self.final_layer_norm(hidden_states) return (hidden_states, self_attn_weights, present_key_value) OPT_START_DOCSTRING = r""" This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior. <Tip> TensorFlow models and layers in `transformers` accept two formats as input: - having all inputs as keyword arguments (like PyTorch models), or - having all inputs as a list, tuple or dict in the first positional argument. The reason the second format is supported is that Keras methods prefer this format when passing inputs to models and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first positional argument: - a single Tensor with `input_ids` only and nothing else: `model(input_ids)` - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring: `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])` - a dictionary with one or several input Tensors associated to the input names given in the docstring: `model({"input_ids": input_ids, "token_type_ids": token_type_ids})` Note that when creating models and layers with [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry about any of this, as you can just pass inputs like you would to any other Python function! </Tip> Args: config ([`OPTConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ @add_start_docstrings( "The bare OPT Model outputting raw hidden-states without any specific head on top.", OPT_START_DOCSTRING, ) class TFOPTPreTrainedModel(TFPreTrainedModel): """ TFOPT Pretrained Model that inheritates from transformers.TFPreTrainedModel Args: config: OPTConfig """ config_class = OPTConfig base_model_prefix = "model" OPT_INPUTS_DOCSTRING = r""" Args: input_ids (`tf.Tensor` of shape `({0})`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`tf.Tensor` of shape `({0})`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*): Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`) contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. use_cache (`bool`, *optional*, defaults to `True`): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). Set to `False` during training, `True` during generation output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the config will be used instead. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the config will be used instead. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in eager mode, in graph mode the value will always be set to True. training (`bool`, *optional*, defaults to `False`): Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation). """ @keras_serializable class TFOPTDecoder(tf.keras.layers.Layer): config_class = OPTConfig def __init__(self, config: OPTConfig, **kwargs): super().__init__(**kwargs) self.config = config self.padding_idx = config.pad_token_id self.layerdrop = config.layerdrop num_embeddings = config.max_position_embeddings self.embed_tokens = TFSharedEmbeddings( config.vocab_size, config.word_embed_proj_dim, config.pad_token_id, name="embed_tokens" ) self.embed_positions = TFOPTLearnedPositionalEmbedding( num_embeddings, config.hidden_size, name="embed_positions", ) # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility # with checkpoints that have been fine-tuned before transformers v4.20.1 # see https://github.com/facebookresearch/metaseq/pull/164 if config.do_layer_norm_before and not config._remove_final_layer_norm: self.final_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm") else: self.final_layer_norm = None if config.word_embed_proj_dim != config.hidden_size: self.project_out = tf.keras.layers.Dense(config.word_embed_proj_dim, name="project_out", use_bias=False) self.project_in = tf.keras.layers.Dense(config.hidden_size, name="project_in", use_bias=False) else: self.project_in = None self.project_out = None self.layers = [TFOPTDecoderLayer(config, name=f"layers.{i}") for i in range(config.num_hidden_layers)] self.dropout = tf.keras.layers.Dropout(config.dropout) def get_embed_tokens(self): return self.embed_tokens def set_embed_tokens(self, embed_tokens): self.embed_tokens = embed_tokens def set_input_embeddings(self, new_embeddings): self.embed_tokens.vocab_size = new_embeddings.shape[0] self.embed_tokens.weight = new_embeddings def get_input_embeddings(self): return self.embed_tokens def _prepare_decoder_attention_mask(self, attention_mask, input_shape, past_key_values_length): # create causal mask # # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] _, seq_length = input_shape tf.debugging.assert_equal( seq_length + past_key_values_length, shape_list(attention_mask)[1], message="Attention mask shape should be (batch_size, seq_length + past_key_values_length)" f" but is {shape_list(attention_mask)[1]} with input_ids shape {input_shape} and past length" f" {past_key_values_length}.", ) expanded_attn_mask = _expand_mask(attention_mask, tgt_len=input_shape[-1]) if seq_length > 1: combined_attention_mask = ( _make_causal_mask(input_shape, past_key_values_length=past_key_values_length) + expanded_attn_mask ) else: combined_attention_mask = expanded_attn_mask return combined_attention_mask @unpack_inputs def call( self, input_ids: TFModelInputType | None = None, inputs_embeds: np.ndarray | tf.Tensor | None = None, attention_mask: np.ndarray | tf.Tensor | None = None, head_mask: np.ndarray | tf.Tensor | None = None, past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, training: Optional[bool] = False, ) -> Union[TFBaseModelOutputWithPast, Tuple[tf.Tensor]]: r""" Args: input_ids (`tf.Tensor` 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.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. training (`bool`, *optional*, defaults to `False`): Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation). """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") elif input_ids is not None: input_shape = shape_list(input_ids) elif inputs_embeds is not None: input_shape = shape_list(inputs_embeds)[:-1] else: raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0 if inputs_embeds is None: check_embeddings_within_bounds(input_ids, self.embed_tokens.vocab_size) inputs_embeds = self.embed_tokens(input_ids) if attention_mask is None: attention_mask = tf.ones((input_shape[0], input_shape[1] + past_key_values_length), dtype=tf.bool) else: tf.debugging.assert_equal( shape_list(attention_mask)[1], past_key_values_length + input_shape[1], message=( f"The provided attention mask has length {tf.shape(attention_mask)[1]}, but its length should be " f"{past_key_values_length + input_shape[1]} (sum of the lengths of current and past inputs)" ), ) pos_embeds = self.embed_positions(attention_mask, past_key_values_length) attention_mask = self._prepare_decoder_attention_mask(attention_mask, input_shape, past_key_values_length) if self.project_in is not None: inputs_embeds = self.project_in(inputs_embeds) hidden_states = inputs_embeds + pos_embeds # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None present_key_values = () if use_cache else None # check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired for attn_mask_name, attn_mask in [("head_mask", head_mask)]: if attn_mask is not None: tf.debugging.assert_equal( shape_list(attn_mask)[0], len(self.layers), message=( f"The {attn_mask_name} should be specified for {len(self.layers)} layers, but it is for" f" {shape_list(attn_mask)[0]}." ), ) for idx, decoder_layer in enumerate(self.layers): if output_hidden_states: all_hidden_states += (hidden_states,) past_key_value = past_key_values[idx] if past_key_values is not None else None hidden_states, layer_self_attn, present_key_value = decoder_layer( hidden_states, attention_mask=attention_mask, layer_head_mask=head_mask[idx] if head_mask is not None else None, past_key_value=past_key_value, ) if use_cache: present_key_values += (present_key_value,) if output_attentions: all_self_attns += (layer_self_attn,) if self.final_layer_norm is not None: hidden_states = self.final_layer_norm(hidden_states) if self.project_out is not None: hidden_states = self.project_out(hidden_states) if output_hidden_states: all_hidden_states += (hidden_states,) if not return_dict: return tuple( v for v in [hidden_states, present_key_values, all_hidden_states, all_self_attns] if v is not None ) else: return TFBaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=present_key_values, hidden_states=all_hidden_states, attentions=all_self_attns, ) @keras_serializable class TFOPTMainLayer(tf.keras.layers.Layer): config_class = OPTConfig def __init__(self, config: OPTConfig, **kwargs): super().__init__(**kwargs) self.config = config self.decoder = TFOPTDecoder(config, name="decoder") def get_input_embeddings(self): return self.decoder.embed_tokens def set_input_embeddings(self, new_embeddings): self.decoder.set_input_embeddings(new_embeddings) @unpack_inputs def call( self, input_ids: TFModelInputType | None = None, attention_mask: np.ndarray | tf.Tensor | None = None, head_mask: np.ndarray | tf.Tensor | None = None, past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None, inputs_embeds: np.ndarray | tf.Tensor | None = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, training: Optional[bool] = False, **kwargs, ) -> Union[TFBaseModelOutputWithPast, Tuple[tf.Tensor]]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.decoder( input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training, ) if not return_dict: return outputs return TFBaseModelOutputWithPast( last_hidden_state=outputs.last_hidden_state, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( "The bare TF OPT Model outputting raw hidden-states without any specific head on top.", OPT_START_DOCSTRING, ) @keras_serializable class TFOPTModel(TFOPTPreTrainedModel): config_class = OPTConfig def __init__(self, config: OPTConfig, **kwargs): super().__init__(config, **kwargs) self.config = config self.model = TFOPTMainLayer(config, name="model") def get_input_embeddings(self): return self.model.decoder.embed_tokens def set_input_embeddings(self, new_embeddings): self.model.set_input_embeddings(new_embeddings) @unpack_inputs @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=TFBaseModelOutputWithPast, config_class=_CONFIG_FOR_DOC, expected_output=_EXPECTED_OUTPUT_SHAPE, ) def call( self, input_ids: TFModelInputType | None = None, attention_mask: np.ndarray | tf.Tensor | None = None, head_mask: np.ndarray | tf.Tensor | None = None, past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None, inputs_embeds: np.ndarray | tf.Tensor | None = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, training: Optional[bool] = False, **kwargs, ) -> Union[TFBaseModelOutputWithPast, Tuple[tf.Tensor]]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.model( input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training, ) if not return_dict: return outputs return TFBaseModelOutputWithPast( last_hidden_state=outputs.last_hidden_state, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def serving_output(self, output): pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None return TFBaseModelOutputWithPast( last_hidden_state=output.last_hidden_state, past_key_values=pkv, hidden_states=hs, attentions=attns, ) @add_start_docstrings( """ The OPT Model transformer with a language modeling head on top. """, OPT_START_DOCSTRING, ) @keras_serializable class TFOPTForCausalLM(TFOPTPreTrainedModel, TFCausalLanguageModelingLoss): config_class = OPTConfig def __init__(self, config: OPTConfig, **kwargs): super().__init__(config, **kwargs) self.config = config self.model = TFOPTMainLayer(config, name="model") def get_output_embeddings(self): return self.model.get_input_embeddings() def prepare_inputs_for_generation(self, inputs, past_key_values=None, use_cache=None, **kwargs): attention_mask = kwargs.get("attention_mask", None) # only last token for inputs_ids if past is defined in kwargs if past_key_values: inputs = tf.expand_dims(inputs[:, -1], -1) return { "input_ids": inputs, "attention_mask": attention_mask, "past_key_values": past_key_values, "use_cache": use_cache, } @unpack_inputs
@replace_return_docstrings(output_type=TFCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
2
2023-11-07 04:23:57+00:00
12k
HKU-BAL/ClairS-TO
src/extract_candidates_calling.py
[ { "identifier": "VcfReader", "path": "shared/vcf.py", "snippet": "class VcfReader(object):\n def __init__(self, vcf_fn,\n ctg_name=None,\n ctg_start=None,\n ctg_end=None,\n is_var_format=False,\n is_happy_format=False,\n ...
import sys import shlex import os import logging import subprocess import shared.param as param from argparse import ArgumentParser, SUPPRESS from collections import Counter, defaultdict from shared.vcf import VcfReader, VcfWriter from shared.utils import subprocess_popen, file_path_from, region_from, \ reference_sequence_from, str2bool, str_none from shared.interval_tree import bed_tree_from, is_region_in
8,269
DP=10, AF=float(tumor_af)) vcf_writer.close() if select_indel_candidates: print("[INFO] {} chunk {}/{}: Total snv candidates found: {}, total indel candidates found: {}".format(ctg_name, \ chunk_id, chunk_num, len(snv_candidates_list), len(indel_candidates_list))) else: print("[INFO] {} chunk {}/{}: Total candidates found: {}".format(ctg_name, chunk_id, chunk_num, len(snv_candidates_list))) if candidates_folder is not None and len(snv_candidates_list): all_candidates_regions = [] region_num = len(snv_candidates_list) // split_bed_size + 1 if len( snv_candidates_list) % split_bed_size else len(snv_candidates_list) // split_bed_size for idx in range(region_num): # a windows region for create tensor # samtools mpileup not include last position split_output = snv_candidates_list[idx * split_bed_size: (idx + 1) * split_bed_size] output_path = os.path.join(candidates_folder, '{}.{}_{}_{}'.format(ctg_name, chunk_id, idx, region_num)) all_candidates_regions.append(output_path) with open(output_path, 'w') as output_file: output_file.write('\n'.join( ['\t'.join([ctg_name, str(x - flankingBaseNum - 1), str(x + flankingBaseNum + 1)]) for x in split_output]) + '\n') # bed format all_candidates_regions_path = os.path.join(candidates_folder, 'CANDIDATES_FILE_{}_{}'.format(ctg_name, chunk_id)) with open(all_candidates_regions_path, 'w') as output_file: output_file.write('\n'.join(all_candidates_regions) + '\n') if select_indel_candidates and candidates_folder is not None and len(indel_candidates_list): all_candidates_regions = [] region_num = len(indel_candidates_list) // split_bed_size + 1 if len( indel_candidates_list) % split_bed_size else len(indel_candidates_list) // split_bed_size for idx in range(region_num): # a windows region for create tensor # samtools mpileup not include last position split_output = indel_candidates_list[idx * split_bed_size: (idx + 1) * split_bed_size] output_path = os.path.join(candidates_folder, '{}.{}_{}_{}_indel'.format(ctg_name, chunk_id, idx, region_num)) all_candidates_regions.append(output_path) with open(output_path, 'w') as output_file: output_file.write('\n'.join( ['\t'.join([ctg_name, str(x - flankingBaseNum - 1), str(x + flankingBaseNum + 1)]) for x in split_output]) + '\n') # bed format all_candidates_regions_path = os.path.join(candidates_folder, 'INDEL_CANDIDATES_FILE_{}_{}'.format(ctg_name, chunk_id)) with open(all_candidates_regions_path, 'w') as output_file: output_file.write('\n'.join(all_candidates_regions) + '\n') if hybrid_mode_vcf_fn is not None or genotyping_mode_vcf_fn is not None: hybrid_output_path = os.path.join(candidates_folder, '{}.{}_hybrid_info'.format(ctg_name, chunk_id)) with open(hybrid_output_path, 'w') as output_file: for k, v in hybrid_info_dict.items(): output_info = '\t'.join([ctg_name, str(k), v.ref_base, v.tumor_alt_info]) output_file.write(output_info + '\n') samtools_mpileup_process.stdout.close() samtools_mpileup_process.wait() if alt_fn: alt_fp.close() def main(): parser = ArgumentParser(description="Generate tumor variant candidates for tensor creation in calling") parser.add_argument('--platform', type=str, default='ont', help="Select the sequencing platform of the input. Default: %(default)s") parser.add_argument('--candidates_folder', type=str, default=None, help="Output candidate folder to store the candidate bed information, required") parser.add_argument('--tumor_bam_fn', type=str, default=None, help="Sorted tumor BAM file input, required") parser.add_argument('--ref_fn', type=str, default=None, help="Reference fasta file input, required") parser.add_argument('--snv_min_af', type=float, default=param.snv_min_af, help="Minimum SNV allele frequency in the tumor sample for a site to be considered as a candidate site in tumor sample, default: %(default)f") parser.add_argument('--ctg_name', type=str, default=None, help="The name of sequence to be processed, required if --bed_fn is not defined") parser.add_argument('--ctg_start', type=int, default=None, help="The 1-based starting position of the sequence to be processed, optional, will process the whole --ctg_name if not set") parser.add_argument('--ctg_end', type=int, default=None, help="The 1-based inclusive ending position of the sequence to be processed, optional, will process the whole --ctg_name if not set") parser.add_argument('--bed_fn', type=str, default=None, help="Call variant only in the provided regions. Will take an intersection if --ctg_name and/or (--ctg_start, --ctg_end) are set") parser.add_argument('--samtools', type=str, default="samtools", help="Path to the 'samtools', samtools version >= 1.10 is required. default: %(default)s") # options for advanced users parser.add_argument('--min_coverage', type=float, default=param.min_coverage, help="EXPERIMENTAL: Minimum coverage required in both normal and tumor sample to call a variant, default: %(default)f") parser.add_argument('--min_mq', type=int, default=param.min_mq, help="EXPERIMENTAL: If set, reads with mapping quality with <$min_mq are filtered, default: %(default)d") parser.add_argument('--min_bq', type=int, default=None, help="EXPERIMENTAL: If set, bases with base quality with <$min_bq are filtered, default: %(default)d") parser.add_argument('--max_depth', type=int, default=None, help="EXPERIMENTAL: Maximum depth to be processed. default: %(default)s") parser.add_argument('--alternative_base_num', type=int, default=param.alternative_base_num, help="EXPERIMENTAL: Minimum alternative base number to process a candidate. default: %(default)s")
# BSD 3-Clause License # # Copyright 2023 The University of Hong Kong, Department of Computer Science # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. logging.basicConfig(format='%(message)s', level=logging.INFO) class AltInfo(object): def __init__(self, ref_base='', tumor_alt_info=""): self.ref_base = ref_base self.tumor_alt_info = tumor_alt_info def decode_pileup_bases(pileup_bases, reference_base, min_coverage, minimum_snv_af_for_candidate, minimum_indel_af_for_candidate, alternative_base_num, has_pileup_candidates, read_name_list, is_tumor, select_indel_candidates=False, platform="ont"): """ Decode mpileup input string. pileup_bases: pileup base string for each position, include all mapping information. reference_base: upper reference base for cigar calculation. pileup_dict: dictionary (pos: pos info) which keep read information that cover specific position. ref_seq: chunked reference sequence in window, start: center pos - flankingBaseNum, end: center + flankingBaseNum + 1. reference_sequence: reference sequence index by contig:start-end. 0-based. minimum_af_for_candidate: default minimum alleic frequency for candidate filtering, filter if below specific thredshold. has_pileup_candidates: if the candidate is directly obtained from pileup output, then no need to check the af filtering. """ base_idx = 0 base_list = [] while base_idx < len(pileup_bases): base = pileup_bases[base_idx] if base == '+' or base == '-': base_idx += 1 advance = 0 while True: num = pileup_bases[base_idx] if num.isdigit(): advance = advance * 10 + int(num) base_idx += 1 else: break base_list[-1][1] = base + pileup_bases[base_idx: base_idx + advance] # add indel seq base_idx += advance - 1 elif base in "ACGTNacgtn#*": base_list.append([base, ""]) elif base == '^': # start of read, next base is mq, update mq info base_idx += 1 # skip $, the end of read base_idx += 1 pileup_dict = defaultdict(int) base_counter = Counter([''.join(item) for item in base_list]) alt_dict = dict(Counter([''.join(item).upper() for item in base_list])) tumor_alt_dict = dict(Counter([''.join(item).upper() for item, read_name in zip(base_list, read_name_list) if read_name.startswith('t')])) if is_tumor else None depth = 0 for key, count in base_counter.items(): if key[0].upper() in 'ACGT': pileup_dict[key[0].upper()] += count depth += count elif key[0] in "#*": depth += count if len(key) > 1 and key[1] == '+': if select_indel_candidates: pileup_dict['I' + key[0].upper() + key[2:].upper()] += count else: pileup_dict['I'] += count elif len(key) > 1 and key[1] == '-': if select_indel_candidates: pileup_dict['D' + len(key[2:]) * "N"] += count else: pileup_dict['D'] += count denominator = depth if depth > 0 else 1 pileup_list = sorted(list(pileup_dict.items()), key=lambda x: x[1], reverse=True) pass_snv_af = False pass_indel_af = False pass_depth = depth > min_coverage for item, count in pileup_list: if item == reference_base: continue elif item[0] in 'ID': if select_indel_candidates: pass_indel_af = (pass_indel_af or (float(count) / denominator >= minimum_indel_af_for_candidate and ( alternative_base_num is not None and count >= alternative_base_num))) continue pass_snv_af = pass_snv_af or (float(count) / denominator >= minimum_snv_af_for_candidate) and ( alternative_base_num is not None and count >= alternative_base_num) af = (float(pileup_list[1][1]) / denominator) if len(pileup_list) > 1 else 0.0 af = (float(pileup_list[0][1]) / denominator) if len(pileup_list) >= 1 and pileup_list[0][ 0] != reference_base else af pass_af = (pass_snv_af or pass_indel_af) and pass_depth alt_list = sorted(list(alt_dict.items()), key=lambda x: x[1], reverse=True) alt_list = [[item[0], str(round(item[1] / denominator, 3))] for item in alt_list if item[0].upper() != reference_base] if not pass_af: return base_list, depth, pass_af, af, "", "", "", alt_list, pass_snv_af, pass_indel_af, pileup_list pileup_list = [[item[0], str(round(item[1] / denominator, 3))] for item in pileup_list] af_infos = ','.join([item[1] for item in pileup_list if item[0] != reference_base]) pileup_infos = ' '.join([item[0] + ':' + item[1] for item in alt_list]) if tumor_alt_dict is not None: tumor_alt_list = sorted(list(tumor_alt_dict.items()), key=lambda x: x[1], reverse=True) tumor_alt_list = [[item[0], str(round(item[1] / denominator, 3))] for item in tumor_alt_list] tumor_pileup_infos = ' '.join([item[0] + ':' + item[1] for item in tumor_alt_list]) else: tumor_pileup_infos = "" return base_list, depth, pass_af, af, af_infos, pileup_infos, tumor_pileup_infos, alt_list, pass_snv_af, pass_indel_af, pileup_list def extract_pair_candidates(args): ctg_start = args.ctg_start ctg_end = args.ctg_end fasta_file_path = args.ref_fn ctg_name = args.ctg_name samtools_execute_command = args.samtools output_depth = args.output_depth output_alt_info = args.output_alt_info tumor_bam_file_path = args.tumor_bam_fn chunk_id = args.chunk_id - 1 if args.chunk_id else None # 1-base to 0-base chunk_num = args.chunk_num minimum_snv_af_for_candidate = args.snv_min_af minimum_indel_af_for_candidate = args.indel_min_af minimum_snv_af_for_truth = args.min_truth_snv_af minimum_indel_af_for_truth = args.min_truth_snv_af alternative_base_num = args.alternative_base_num split_bed_size = param.split_bed_size candidates_folder = args.candidates_folder min_coverage = args.min_coverage platform = args.platform store_tumor_infos = args.store_tumor_infos alt_fn = args.alt_fn confident_bed_fn = file_path_from(args.bed_fn, allow_none=True, exit_on_not_found=False) is_confident_bed_file_given = confident_bed_fn is not None min_mapping_quality = args.min_mq min_base_quality = args.min_bq flankingBaseNum = param.flankingBaseNum if args.flanking is None else args.flanking no_of_positions = 2 * flankingBaseNum + 1 genotyping_mode_vcf_fn = args.genotyping_mode_vcf_fn hybrid_mode_vcf_fn = args.hybrid_mode_vcf_fn truth_vcf_fn = args.truth_vcf_fn is_truth_vcf_provided = truth_vcf_fn is not None select_indel_candidates = args.select_indel_candidates candidates_set = set() indel_candidates_list = [] snv_candidates_set = set() indel_candidates_set = set() truths_variant_dict = {} if is_truth_vcf_provided: unified_vcf_reader = VcfReader(vcf_fn=truth_vcf_fn, ctg_name=ctg_name, is_var_format=False) unified_vcf_reader.read_vcf() truths_variant_dict = unified_vcf_reader.variant_dict candidates_pos_set = set() add_read_regions = True hybrid_candidate_set = set() indel_hybrid_candidate_set = set() if hybrid_mode_vcf_fn is not None or genotyping_mode_vcf_fn is not None: vcf_fn = hybrid_mode_vcf_fn if hybrid_mode_vcf_fn is not None else genotyping_mode_vcf_fn vcf_reader = VcfReader(vcf_fn=vcf_fn, ctg_name=ctg_name, is_var_format=False) vcf_reader.read_vcf() hybrid_variant_dict = vcf_reader.variant_dict for k, v in hybrid_variant_dict.items(): ref_base, alt_base = v.reference_bases, v.alternate_bases[0] if len(ref_base) > 1 or len(alt_base) > 1: if select_indel_candidates: indel_hybrid_candidate_set.add(k) candidates_set.add(k) hybrid_candidate_set.add(k) hybrid_info_dict = defaultdict(AltInfo) fai_fn = file_path_from(fasta_file_path, suffix=".fai", exit_on_not_found=True, sep='.') if chunk_id is not None: """ Whole genome calling option, acquire contig start end position from reference fasta index(.fai), then split the reference accroding to chunk id and total chunk numbers. """ if is_confident_bed_file_given: # consistent with pileup generation, faster to extract tensor using bed region tree, bed_start, bed_end = bed_tree_from(bed_file_path=confident_bed_fn, contig_name=ctg_name, return_bed_region=True) chunk_size = (bed_end - bed_start) // chunk_num + 1 if (bed_end - bed_start) % chunk_num else ( bed_end - bed_start) // chunk_num ctg_start = bed_start + 1 + chunk_size * chunk_id # 0-base to 1-base ctg_end = ctg_start + chunk_size else: contig_length = 0 with open(fai_fn, 'r') as fai_fp: for row in fai_fp: columns = row.strip().split("\t") contig_name = columns[0] if contig_name != ctg_name: continue contig_length = int(columns[1]) chunk_size = contig_length // chunk_num + 1 if contig_length % chunk_num else contig_length // chunk_num ctg_start = chunk_size * chunk_id # 0-base to 1-base ctg_end = ctg_start + chunk_size candidates_pos_set = set([item for item in candidates_pos_set if item >= ctg_start and item <= ctg_end]) # 1-based regions [start, end] (start and end inclusive) ref_regions = [] reads_regions = [] is_ctg_name_given = ctg_name is not None is_ctg_range_given = is_ctg_name_given and ctg_start is not None and ctg_end is not None if is_ctg_range_given: extend_start = max(ctg_start - ( no_of_positions), 1) extend_end = ctg_end + no_of_positions reads_regions.append(region_from(ctg_name=ctg_name, ctg_start=extend_start, ctg_end=extend_end)) reference_start, reference_end = ctg_start - param.expandReferenceRegion, ctg_end + param.expandReferenceRegion reference_start = 1 if reference_start < 1 else reference_start ref_regions.append(region_from(ctg_name=ctg_name, ctg_start=reference_start, ctg_end=reference_end)) elif is_ctg_name_given: reads_regions.append(region_from(ctg_name=ctg_name)) ref_regions.append(region_from(ctg_name=ctg_name)) reference_start = 1 reference_sequence = reference_sequence_from( samtools_execute_command=samtools_execute_command, fasta_file_path=fasta_file_path, regions=ref_regions ) if reference_sequence is None or len(reference_sequence) == 0: sys.exit("[ERROR] Failed to load reference sequence from file ({}).".format(fasta_file_path)) mq_option = ' --min-MQ {}'.format(min_mapping_quality) bq_option = ' --min-BQ {}'.format(min_base_quality) read_name_option = ' --output-QNAME' if store_tumor_infos else ' ' bed_option = ' -l {}'.format( confident_bed_fn) if is_confident_bed_file_given else "" flags_option = ' --excl-flags {} '.format(param.SAMTOOLS_VIEW_FILTER_FLAG) max_depth_option = ' --max-depth {} '.format(args.max_depth) if args.max_depth is not None else " " reads_regions_option = ' -r {}'.format(" ".join(reads_regions)) if add_read_regions else "" stdin = None if tumor_bam_file_path != "PIPE" else sys.stdin tumor_bam_file_path = tumor_bam_file_path if tumor_bam_file_path != "PIPE" else "-" samtools_command = samtools_execute_command + " mpileup --reverse-del" + read_name_option + reads_regions_option + \ mq_option + bq_option + bed_option + flags_option + max_depth_option samtools_mpileup_process = subprocess_popen( shlex.split(samtools_command + ' ' + tumor_bam_file_path), stdin=stdin, stderr=subprocess.PIPE) if alt_fn: output_alt_fn = alt_fn alt_fp = open(output_alt_fn, 'w') is_tumor = alt_fn.split('/')[-2].startswith('tumor') if alt_fn else False has_pileup_candidates = len(candidates_pos_set) candidates_dict = defaultdict(str) for row in samtools_mpileup_process.stdout: # chr position N depth seq BQ read_name mapping_quality phasing_info columns = row.strip().split('\t') pos = int(columns[1]) pileup_bases = columns[4] read_name_list = columns[6].split(',') if store_tumor_infos else [] reference_base = reference_sequence[pos - reference_start].upper() if reference_base.upper() not in "ACGT": continue is_truth_candidate = pos in truths_variant_dict minimum_snv_af_for_candidate = minimum_snv_af_for_truth if is_truth_candidate and minimum_snv_af_for_truth else minimum_snv_af_for_candidate minimum_indel_af_for_candidate = minimum_indel_af_for_truth if is_truth_candidate and minimum_indel_af_for_truth else minimum_indel_af_for_candidate base_list, depth, pass_af, af, af_infos, pileup_infos, tumor_pileup_infos, alt_list, pass_snv_af, pass_indel_af, pileup_list = decode_pileup_bases( pileup_bases=pileup_bases, reference_base=reference_base, min_coverage=min_coverage, minimum_snv_af_for_candidate=minimum_snv_af_for_candidate, minimum_indel_af_for_candidate=minimum_indel_af_for_candidate, alternative_base_num=alternative_base_num, has_pileup_candidates=has_pileup_candidates, read_name_list=read_name_list, is_tumor=is_tumor, select_indel_candidates=select_indel_candidates ) if pos in hybrid_candidate_set: tumor_alt_info = str(depth) + '-' + ' '.join([' '.join([item[0], str(item[1])]) for item in pileup_list]) hybrid_info_dict[pos] = AltInfo(ref_base=reference_base, tumor_alt_info=tumor_alt_info) if pass_af and alt_fn: depth_list = [str(depth)] if output_depth else [] alt_info_list = [af_infos, pileup_infos, tumor_pileup_infos] if output_alt_info else [] alt_fp.write('\t'.join([ctg_name, str(pos), reference_base] + depth_list + alt_info_list) + '\n') if pass_af: candidates_set.add(pos) candidates_dict[pos] = (alt_list, depth) if pass_snv_af: snv_candidates_set.add(pos) tumor_info = [item for item in alt_list if item[0] in "ACGT"] if len(tumor_info) == 0: snv_candidates_set.remove(pos) if select_indel_candidates and pass_indel_af: indel_candidates_set.add(pos) tumor_info = [item for item in alt_list if '+' in item[0] or '-' in item[0]] if len(tumor_info) == 0: indel_candidates_set.remove(pos) if not pass_af and (pos in hybrid_candidate_set): candidates_set.add(pos) snv_candidates_set.add(pos) tumor_info = [item for item in alt_list if item[0] in "ACGT"] if len(tumor_info) == 0: snv_candidates_set.remove(pos) if select_indel_candidates: indel_candidates_set.add(pos) tumor_info = [item for item in alt_list if '+' in item[0] or '-' in item[0]] if len(tumor_info) == 0: indel_candidates_set.remove(pos) bed_path = os.path.join(candidates_folder, "bed", '{}_{}.bed'.format(ctg_name, chunk_id)) if not os.path.exists(os.path.join(candidates_folder, 'bed')): output = subprocess.run("mkdir -p {}".format(os.path.join(candidates_folder, 'bed')), shell=True) output_bed = open(bed_path, 'w') for pos in sorted(list(candidates_set)): output_bed.write('\t'.join([ctg_name, str(pos - 1), str(pos)]) + '\n') output_bed.close() snv_candidates_list = sorted([pos for pos in candidates_set if pos in snv_candidates_set]) if select_indel_candidates: indel_candidates_list = sorted([pos for pos in candidates_set if pos in indel_candidates_set]) gen_vcf = False if gen_vcf: truth_vcf_fn = args.truth_vcf_fn truth_vcf_reader = VcfReader(vcf_fn=truth_vcf_fn, ctg_name=ctg_name, show_ref=False, keep_row_str=True, skip_genotype=True) truth_vcf_reader.read_vcf() truth_variant_dict = truth_vcf_reader.variant_dict vcf_writer = VcfWriter(vcf_fn=os.path.join(candidates_folder, "{}_{}.vcf".format(ctg_name, chunk_id)), ref_fn=fasta_file_path, ctg_name=ctg_name, show_ref_calls=True) for pos in snv_candidates_list: genotype = '1/1' ref_base, alt_base = "A", "A" if pos in truth_variant_dict: print(ctg_name, pos, "in truth set") continue tumor_alt_list, tumor_depth = candidates_dict[pos] tumor_info = [item for item in tumor_alt_list if item[0] in "ACGT"] if len(tumor_info) == 0: # candidates_set.remove(pos) print(pos, "gen vcf not found tumor") continue alt_base, tumor_af = tumor_info[0] ref_base = reference_sequence[pos - reference_start].upper() vcf_writer.write_row(POS=pos, REF=ref_base, ALT=alt_base, QUAL=10, GT=genotype, DP=10, AF=float(tumor_af)) vcf_writer.close() if select_indel_candidates: print("[INFO] {} chunk {}/{}: Total snv candidates found: {}, total indel candidates found: {}".format(ctg_name, \ chunk_id, chunk_num, len(snv_candidates_list), len(indel_candidates_list))) else: print("[INFO] {} chunk {}/{}: Total candidates found: {}".format(ctg_name, chunk_id, chunk_num, len(snv_candidates_list))) if candidates_folder is not None and len(snv_candidates_list): all_candidates_regions = [] region_num = len(snv_candidates_list) // split_bed_size + 1 if len( snv_candidates_list) % split_bed_size else len(snv_candidates_list) // split_bed_size for idx in range(region_num): # a windows region for create tensor # samtools mpileup not include last position split_output = snv_candidates_list[idx * split_bed_size: (idx + 1) * split_bed_size] output_path = os.path.join(candidates_folder, '{}.{}_{}_{}'.format(ctg_name, chunk_id, idx, region_num)) all_candidates_regions.append(output_path) with open(output_path, 'w') as output_file: output_file.write('\n'.join( ['\t'.join([ctg_name, str(x - flankingBaseNum - 1), str(x + flankingBaseNum + 1)]) for x in split_output]) + '\n') # bed format all_candidates_regions_path = os.path.join(candidates_folder, 'CANDIDATES_FILE_{}_{}'.format(ctg_name, chunk_id)) with open(all_candidates_regions_path, 'w') as output_file: output_file.write('\n'.join(all_candidates_regions) + '\n') if select_indel_candidates and candidates_folder is not None and len(indel_candidates_list): all_candidates_regions = [] region_num = len(indel_candidates_list) // split_bed_size + 1 if len( indel_candidates_list) % split_bed_size else len(indel_candidates_list) // split_bed_size for idx in range(region_num): # a windows region for create tensor # samtools mpileup not include last position split_output = indel_candidates_list[idx * split_bed_size: (idx + 1) * split_bed_size] output_path = os.path.join(candidates_folder, '{}.{}_{}_{}_indel'.format(ctg_name, chunk_id, idx, region_num)) all_candidates_regions.append(output_path) with open(output_path, 'w') as output_file: output_file.write('\n'.join( ['\t'.join([ctg_name, str(x - flankingBaseNum - 1), str(x + flankingBaseNum + 1)]) for x in split_output]) + '\n') # bed format all_candidates_regions_path = os.path.join(candidates_folder, 'INDEL_CANDIDATES_FILE_{}_{}'.format(ctg_name, chunk_id)) with open(all_candidates_regions_path, 'w') as output_file: output_file.write('\n'.join(all_candidates_regions) + '\n') if hybrid_mode_vcf_fn is not None or genotyping_mode_vcf_fn is not None: hybrid_output_path = os.path.join(candidates_folder, '{}.{}_hybrid_info'.format(ctg_name, chunk_id)) with open(hybrid_output_path, 'w') as output_file: for k, v in hybrid_info_dict.items(): output_info = '\t'.join([ctg_name, str(k), v.ref_base, v.tumor_alt_info]) output_file.write(output_info + '\n') samtools_mpileup_process.stdout.close() samtools_mpileup_process.wait() if alt_fn: alt_fp.close() def main(): parser = ArgumentParser(description="Generate tumor variant candidates for tensor creation in calling") parser.add_argument('--platform', type=str, default='ont', help="Select the sequencing platform of the input. Default: %(default)s") parser.add_argument('--candidates_folder', type=str, default=None, help="Output candidate folder to store the candidate bed information, required") parser.add_argument('--tumor_bam_fn', type=str, default=None, help="Sorted tumor BAM file input, required") parser.add_argument('--ref_fn', type=str, default=None, help="Reference fasta file input, required") parser.add_argument('--snv_min_af', type=float, default=param.snv_min_af, help="Minimum SNV allele frequency in the tumor sample for a site to be considered as a candidate site in tumor sample, default: %(default)f") parser.add_argument('--ctg_name', type=str, default=None, help="The name of sequence to be processed, required if --bed_fn is not defined") parser.add_argument('--ctg_start', type=int, default=None, help="The 1-based starting position of the sequence to be processed, optional, will process the whole --ctg_name if not set") parser.add_argument('--ctg_end', type=int, default=None, help="The 1-based inclusive ending position of the sequence to be processed, optional, will process the whole --ctg_name if not set") parser.add_argument('--bed_fn', type=str, default=None, help="Call variant only in the provided regions. Will take an intersection if --ctg_name and/or (--ctg_start, --ctg_end) are set") parser.add_argument('--samtools', type=str, default="samtools", help="Path to the 'samtools', samtools version >= 1.10 is required. default: %(default)s") # options for advanced users parser.add_argument('--min_coverage', type=float, default=param.min_coverage, help="EXPERIMENTAL: Minimum coverage required in both normal and tumor sample to call a variant, default: %(default)f") parser.add_argument('--min_mq', type=int, default=param.min_mq, help="EXPERIMENTAL: If set, reads with mapping quality with <$min_mq are filtered, default: %(default)d") parser.add_argument('--min_bq', type=int, default=None, help="EXPERIMENTAL: If set, bases with base quality with <$min_bq are filtered, default: %(default)d") parser.add_argument('--max_depth', type=int, default=None, help="EXPERIMENTAL: Maximum depth to be processed. default: %(default)s") parser.add_argument('--alternative_base_num', type=int, default=param.alternative_base_num, help="EXPERIMENTAL: Minimum alternative base number to process a candidate. default: %(default)s")
parser.add_argument('--select_indel_candidates', type=str2bool, default=0,
6
2023-11-07 04:39:16+00:00
12k
sb-ai-lab/HypEx
tests/test_aa.py
[ { "identifier": "AATest", "path": "hypex/ab_test/aa_tester.py", "snippet": "class AATest:\n \"\"\"\n A class for conducting AA testing (random split testing) to assess the\n statistical uniform of two samples.\n\n AA testing is used to validate that the splitting mechanism of an A/B test\n ...
import pandas as pd import pytest import sys from pathlib import Path from hypex import AATest from hypex.utils.tutorial_data_creation import create_test_data
9,093
sys.path.append(str(Path(".").absolute().parent)) @pytest.fixture def data(): return create_test_data(rs=52) @pytest.fixture def iterations(): return 20 @pytest.fixture def info_col(): return "user_id" def test_aa_simple(data, iterations, info_col):
sys.path.append(str(Path(".").absolute().parent)) @pytest.fixture def data(): return create_test_data(rs=52) @pytest.fixture def iterations(): return 20 @pytest.fixture def info_col(): return "user_id" def test_aa_simple(data, iterations, info_col):
model = AATest(target_fields=["pre_spends", "post_spends"], info_cols=info_col)
0
2023-11-01 08:58:57+00:00
12k
mileswyn/SAMIHS
models/segment_anything_samihs/automatic_mask_generator.py
[ { "identifier": "Samihs", "path": "models/segment_anything_samihs/modeling/samihs.py", "snippet": "class Samihs(nn.Module):\n mask_threshold: float = 0.0\n image_format: str = \"RGB\"\n\n def __init__(\n self,\n image_encoder: ImageEncoderViT,\n prompt_encoder: PromptEncode...
import numpy as np import torch import cv2 # type: ignore # noqa: F401 from torchvision.ops.boxes import batched_nms, box_area # type: ignore from typing import Any, Dict, List, Optional, Tuple from .modeling import Samihs from .utils.amg import ( MaskData, area_from_rle, batch_iterator, batched_mask_to_box, box_xyxy_to_xywh, build_all_layer_point_grids, calculate_stability_score, coco_encode_rle, generate_crop_boxes, is_box_near_crop_edge, mask_to_rle_pytorch, remove_small_regions, rle_to_mask, uncrop_boxes_xyxy, uncrop_masks, uncrop_points, ) from pycocotools import mask as mask_utils # type: ignore # noqa: F401
8,703
Arguments: image (np.ndarray): The image to generate masks for, in HWC uint8 format. Returns: list(dict(str, any)): A list over records for masks. Each record is a dict containing the following keys: segmentation (dict(str, any) or np.ndarray): The mask. If output_mode='binary_mask', is an array of shape HW. Otherwise, is a dictionary containing the RLE. bbox (list(float)): The box around the mask, in XYWH format. area (int): The area in pixels of the mask. predicted_iou (float): The model's own prediction of the mask's quality. This is filtered by the pred_iou_thresh parameter. point_coords (list(list(float))): The point coordinates input to the model to generate this mask. stability_score (float): A measure of the mask's quality. This is filtered on using the stability_score_thresh parameter. crop_box (list(float)): The crop of the image used to generate the mask, given in XYWH format. """ # Generate masks mask_data = self._generate_masks(image) # Filter small disconnected regions and holes in masks if self.min_mask_region_area > 0: mask_data = self.postprocess_small_regions( mask_data, self.min_mask_region_area, max(self.box_nms_thresh, self.crop_nms_thresh), ) # Encode masks if self.output_mode == "coco_rle": mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]] elif self.output_mode == "binary_mask": mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] else: mask_data["segmentations"] = mask_data["rles"] # Write mask records curr_anns = [] for idx in range(len(mask_data["segmentations"])): ann = { "segmentation": mask_data["segmentations"][idx], "area": area_from_rle(mask_data["rles"][idx]), "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), "predicted_iou": mask_data["iou_preds"][idx].item(), "point_coords": [mask_data["points"][idx].tolist()], "stability_score": mask_data["stability_score"][idx].item(), "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), } curr_anns.append(ann) return curr_anns def _generate_masks(self, image: np.ndarray) -> MaskData: orig_size = image.shape[:2] crop_boxes, layer_idxs = generate_crop_boxes( orig_size, self.crop_n_layers, self.crop_overlap_ratio ) # Iterate over image crops data = MaskData() for crop_box, layer_idx in zip(crop_boxes, layer_idxs): crop_data = self._process_crop(image, crop_box, layer_idx, orig_size) data.cat(crop_data) # Remove duplicate masks between crops if len(crop_boxes) > 1: # Prefer masks from smaller crops scores = 1 / box_area(data["crop_boxes"]) scores = scores.to(data["boxes"].device) keep_by_nms = batched_nms( data["boxes"].float(), scores, torch.zeros_like(data["boxes"][:, 0]), # categories iou_threshold=self.crop_nms_thresh, ) data.filter(keep_by_nms) data.to_numpy() return data def _process_crop( self, image: np.ndarray, crop_box: List[int], crop_layer_idx: int, orig_size: Tuple[int, ...], ) -> MaskData: # Crop the image and calculate embeddings x0, y0, x1, y1 = crop_box cropped_im = image[y0:y1, x0:x1, :] cropped_im_size = cropped_im.shape[:2] self.predictor.set_image(cropped_im) # Get points for this crop points_scale = np.array(cropped_im_size)[None, ::-1] points_for_image = self.point_grids[crop_layer_idx] * points_scale # Generate masks for this crop in batches data = MaskData() for (points,) in batch_iterator(self.points_per_batch, points_for_image): batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size) data.cat(batch_data) del batch_data self.predictor.reset_image() # Remove duplicates within this crop. keep_by_nms = batched_nms( data["boxes"].float(), data["iou_preds"], torch.zeros_like(data["boxes"][:, 0]), # categories iou_threshold=self.box_nms_thresh, ) data.filter(keep_by_nms) # Return to the original image frame data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box)
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. class SamAutomaticMaskGenerator: def __init__( self, model: Samihs, points_per_side: Optional[int] = 32, points_per_batch: int = 64, pred_iou_thresh: float = 0.88, stability_score_thresh: float = 0.95, stability_score_offset: float = 1.0, box_nms_thresh: float = 0.7, crop_n_layers: int = 0, crop_nms_thresh: float = 0.7, crop_overlap_ratio: float = 512 / 1500, crop_n_points_downscale_factor: int = 1, point_grids: Optional[List[np.ndarray]] = None, min_mask_region_area: int = 0, output_mode: str = "binary_mask", ) -> None: """ Using a SAM model, generates masks for the entire image. Generates a grid of point prompts over the image, then filters low quality and duplicate masks. The default settings are chosen for SAM with a ViT-H backbone. Arguments: model (Sam): The SAM model to use for mask prediction. points_per_side (int or None): The number of points to be sampled along one side of the image. The total number of points is points_per_side**2. If None, 'point_grids' must provide explicit point sampling. points_per_batch (int): Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU memory. pred_iou_thresh (float): A filtering threshold in [0,1], using the model's predicted mask quality. stability_score_thresh (float): A filtering threshold in [0,1], using the stability of the mask under changes to the cutoff used to binarize the model's mask predictions. stability_score_offset (float): The amount to shift the cutoff when calculated the stability score. box_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks. crop_n_layers (int): If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops. crop_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks between different crops. crop_overlap_ratio (float): Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. crop_n_points_downscale_factor (int): The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n. point_grids (list(np.ndarray) or None): A list over explicit grids of points used for sampling, normalized to [0,1]. The nth grid in the list is used in the nth crop layer. Exclusive with points_per_side. min_mask_region_area (int): If >0, postprocessing will be applied to remove disconnected regions and holes in masks with area smaller than min_mask_region_area. Requires opencv. output_mode (str): The form masks are returned in. Can be 'binary_mask', 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. For large resolutions, 'binary_mask' may consume large amounts of memory. """ assert (points_per_side is None) != ( point_grids is None ), "Exactly one of points_per_side or point_grid must be provided." if points_per_side is not None: self.point_grids = build_all_layer_point_grids( points_per_side, crop_n_layers, crop_n_points_downscale_factor, ) elif point_grids is not None: self.point_grids = point_grids else: raise ValueError("Can't have both points_per_side and point_grid be None.") assert output_mode in [ "binary_mask", "uncompressed_rle", "coco_rle", ], f"Unknown output_mode {output_mode}." if output_mode == "coco_rle": if min_mask_region_area > 0: self.points_per_batch = points_per_batch self.pred_iou_thresh = pred_iou_thresh self.stability_score_thresh = stability_score_thresh self.stability_score_offset = stability_score_offset self.box_nms_thresh = box_nms_thresh self.crop_n_layers = crop_n_layers self.crop_nms_thresh = crop_nms_thresh self.crop_overlap_ratio = crop_overlap_ratio self.crop_n_points_downscale_factor = crop_n_points_downscale_factor self.min_mask_region_area = min_mask_region_area self.output_mode = output_mode @torch.no_grad() def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: """ Generates masks for the given image. Arguments: image (np.ndarray): The image to generate masks for, in HWC uint8 format. Returns: list(dict(str, any)): A list over records for masks. Each record is a dict containing the following keys: segmentation (dict(str, any) or np.ndarray): The mask. If output_mode='binary_mask', is an array of shape HW. Otherwise, is a dictionary containing the RLE. bbox (list(float)): The box around the mask, in XYWH format. area (int): The area in pixels of the mask. predicted_iou (float): The model's own prediction of the mask's quality. This is filtered by the pred_iou_thresh parameter. point_coords (list(list(float))): The point coordinates input to the model to generate this mask. stability_score (float): A measure of the mask's quality. This is filtered on using the stability_score_thresh parameter. crop_box (list(float)): The crop of the image used to generate the mask, given in XYWH format. """ # Generate masks mask_data = self._generate_masks(image) # Filter small disconnected regions and holes in masks if self.min_mask_region_area > 0: mask_data = self.postprocess_small_regions( mask_data, self.min_mask_region_area, max(self.box_nms_thresh, self.crop_nms_thresh), ) # Encode masks if self.output_mode == "coco_rle": mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]] elif self.output_mode == "binary_mask": mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] else: mask_data["segmentations"] = mask_data["rles"] # Write mask records curr_anns = [] for idx in range(len(mask_data["segmentations"])): ann = { "segmentation": mask_data["segmentations"][idx], "area": area_from_rle(mask_data["rles"][idx]), "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), "predicted_iou": mask_data["iou_preds"][idx].item(), "point_coords": [mask_data["points"][idx].tolist()], "stability_score": mask_data["stability_score"][idx].item(), "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), } curr_anns.append(ann) return curr_anns def _generate_masks(self, image: np.ndarray) -> MaskData: orig_size = image.shape[:2] crop_boxes, layer_idxs = generate_crop_boxes( orig_size, self.crop_n_layers, self.crop_overlap_ratio ) # Iterate over image crops data = MaskData() for crop_box, layer_idx in zip(crop_boxes, layer_idxs): crop_data = self._process_crop(image, crop_box, layer_idx, orig_size) data.cat(crop_data) # Remove duplicate masks between crops if len(crop_boxes) > 1: # Prefer masks from smaller crops scores = 1 / box_area(data["crop_boxes"]) scores = scores.to(data["boxes"].device) keep_by_nms = batched_nms( data["boxes"].float(), scores, torch.zeros_like(data["boxes"][:, 0]), # categories iou_threshold=self.crop_nms_thresh, ) data.filter(keep_by_nms) data.to_numpy() return data def _process_crop( self, image: np.ndarray, crop_box: List[int], crop_layer_idx: int, orig_size: Tuple[int, ...], ) -> MaskData: # Crop the image and calculate embeddings x0, y0, x1, y1 = crop_box cropped_im = image[y0:y1, x0:x1, :] cropped_im_size = cropped_im.shape[:2] self.predictor.set_image(cropped_im) # Get points for this crop points_scale = np.array(cropped_im_size)[None, ::-1] points_for_image = self.point_grids[crop_layer_idx] * points_scale # Generate masks for this crop in batches data = MaskData() for (points,) in batch_iterator(self.points_per_batch, points_for_image): batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size) data.cat(batch_data) del batch_data self.predictor.reset_image() # Remove duplicates within this crop. keep_by_nms = batched_nms( data["boxes"].float(), data["iou_preds"], torch.zeros_like(data["boxes"][:, 0]), # categories iou_threshold=self.box_nms_thresh, ) data.filter(keep_by_nms) # Return to the original image frame data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box)
data["points"] = uncrop_points(data["points"], crop_box)
16
2023-11-09 07:26:33+00:00
12k
tianhaowuhz/human-assisting-dex-grasp
Runners/TrainSDE_update.py
[ { "identifier": "loss_fn_cond", "path": "Algorithms/SDE_update.py", "snippet": "def loss_fn_cond(model, x, marginal_prob_fn, sde_fn, is_likelihood_weighting=False, eps=1e-5, device='cuda:0', hand_pcl=False, full_state=None, envs=None, hand_model=None, space='euler', relative=True):\n \"\"\"\n is_l...
import isaacgym import condexenvs import argparse import functools import sys import os import cv2 import numpy as np import tqdm import time import pickle import random import torch import torch.optim as optim from ipdb import set_trace from tensorboardX import SummaryWriter from torch.utils.data import DataLoader from torchvision.utils import make_grid from Algorithms.SDE_update import loss_fn_cond, cond_ode_sampler, init_sde, ExponentialMovingAverage from Networks.SDENets_update import CondScoreModel from utils.utils import exists_or_mkdir, save_video, get_dict_key, DexDataset
8,098
# mode parser.add_argument('--model_name', type=str, default='fine', metavar='NAME', help="the name of the model (default: fine") parser.add_argument('--quick', action='store_true', help="test on small cases") parser.add_argument('--train_model', action='store_true', help="train model") parser.add_argument('--con', action='store_true', help="continue train the given model") parser.add_argument('--demo_gen', action='store_true', help="demo gen mode") parser.add_argument('--demo_nums', type=int, default=8, help='total demo nums') parser.add_argument('--demo_name', type=str, default='small_test', help='demo names') parser.add_argument('--space', type=str, default='riemann', help='angle space') parser.add_argument('--eval_demo_name', type=str, default='small_test', help='demo names') parser.add_argument('--constrained', action='store_false', help="whether constrain base") parser.add_argument('--gt', action='store_true', help="gt mode") parser.add_argument('--device_id', type=int, default=0, help='device_id') # tensorboard parser.add_argument("--log_dir", type=str, default='gf_overfit') parser.add_argument("--pt_version", type=str, default='pt2') args = parser.parse_args() device = f'cuda:{args.device_id}' ''' make env ''' num_envs = args.num_envs # 53 envs = condexenvs.make( seed=args.seed, task="ShadowHandCon", num_envs=num_envs, sim_device=device, rl_device=device, graphics_device_id = args.device_id, virtual_screen_capture=False, headless=args.gui, force_render = False, mode = args.mode, num_run_envs = args.num_run_envs, method = args.method, dataset_type = args.dataset_type, ) envs.reset(env_init=True) print(args) # set_trace() ''' seed ''' np.random.seed(args.seed) torch.manual_seed(args.seed) torch.set_num_threads(4) random.seed(args.seed) ''' logging ''' exists_or_mkdir('./logs') ckpt_path = f'./logs/{args.log_dir}/' exists_or_mkdir(ckpt_path) tb_path = f'./logs/{args.log_dir}/tb' exists_or_mkdir(tb_path) writer = SummaryWriter(tb_path) ''' create train dataset and dataloader ''' dataset_path = f'./ExpertDatasets/grasp_data/ground/{args.demo_name}.pth' assert os.path.exists(dataset_path), 'Dataset not found!' with open(dataset_path, 'rb') as f: data_samples = pickle.load(f) print(len(data_samples)) ''' eval ''' eval_dataset_path = f'./ExpertDatasets/grasp_data/ground/{args.eval_demo_name}_rc.pth' assert os.path.exists(eval_dataset_path), 'Eval Dataset not found!' with open(eval_dataset_path, 'rb') as f: eval_data_samples = pickle.load(f) eval_dataset_ot_path = f'./ExpertDatasets/grasp_data/ground/{args.eval_demo_name}_rc_ot.pth' assert os.path.exists(eval_dataset_ot_path), 'Eval Dataset oti not found!' with open(eval_dataset_ot_path, 'rb') as f: eval_data_ot = pickle.load(f) # change data object type id eval_dataset_oti_path = f'./ExpertDatasets/grasp_data/ground/{args.eval_demo_name}_oti.pth' with open(eval_dataset_oti_path, 'rb') as f: eval_data_oti = pickle.load(f) for (i, data) in enumerate(eval_data_samples): env_id_in_full = int(data[25+points_per_object*3+7:25+points_per_object*3+8]) object_type = get_dict_key(eval_data_oti, env_id_in_full) env_id_in_current = envs.obj_type_id[object_type] eval_data_samples[i,3104] = env_id_in_current eval_dataset = torch.tensor(eval_data_samples, device=device) eval_dataset = eval_dataset.reshape(-1, eval_dataset.shape[-1]) args.num_envs = len(eval_data_ot) num_envs = len(eval_data_ot) test_per_object = int(len(eval_dataset)/num_envs) eval_demo_number = len(eval_data_samples) total_data_number = len(data_samples) # augment demos if total_data_number < args.demo_nums: new_data_samples = data_samples for i in range(args.demo_nums - total_data_number): new_data_samples = np.vstack((new_data_samples,data_samples[i%total_data_number])) dataset = new_data_samples else: dataset = data_samples dataset = dataset[: args.demo_nums] dataset = dataset.reshape(-1, dataset.shape[-1]) # set_trace() if 'all' in dataset_path: print('balance data') dataset = DexDataset(dataset) print(len(dataset)) if args.relative: dataloader = DataLoader(dataset=dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, drop_last=True) else: dataloader = DataLoader(dataset=dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, drop_last=True) ''' SDE ''' # init SDE config
#!/usr/bin/env python sys.path.append(os.path.dirname(os.path.dirname(__file__))) points_per_object = 1024 vis_image = False max_bz = 256 if __name__ == "__main__": parser = argparse.ArgumentParser() ''' configurator ''' # score matching parameter parser.add_argument('--test_decay', type=str, default='False') parser.add_argument('--score_mode', type=str, default='target') parser.add_argument('--sde_mode', type=str, default='vp') # ['ve', 'vp', 'subvp'] parser.add_argument('--sde_min', type=float, default=0.1) parser.add_argument('--sde_max', type=float, default=10.0) parser.add_argument('--n_epoches', type=int, default=50000) parser.add_argument('--eval_freq', type=int, default=1000) parser.add_argument('--eval_times', type=int, default=5) parser.add_argument('--batch_size', type=int, default=64) parser.add_argument('--lr', type=float, default=2e-4) parser.add_argument('--t0', type=float, default=0.5) parser.add_argument('--ema_rate', type=float, default=0.999) parser.add_argument('--repeat_num', type=int, default=1) parser.add_argument('--warmup', type=int, default=100) parser.add_argument('--grad_clip', type=float, default=1.) parser.add_argument('--beta1', type=float, default=0.9) parser.add_argument('--test_ratio', type=float, default=0.1) parser.add_argument('--base_noise_scale', type=float, default=0.01) parser.add_argument('--workers', type=int, default=4) parser.add_argument('--hidden_dim', type=int, default=1024) parser.add_argument('--embed_dim', type=int, default=512) parser.add_argument('--seed', type=int, default=0) parser.add_argument('--relative', action='store_true', help="relative obj pcl state") # env parser.add_argument('--num_envs', type=int, default=4, help='total env nums') parser.add_argument('--num_run_envs', type=int, default=1, help='running env nums') parser.add_argument('--max_episode_steps', type=int, default=200, help='step numbers for each episode') parser.add_argument("--method", type=str, default='filter') parser.add_argument('--gui', action='store_false', help="enable gui") parser.add_argument("--mode", type=str, default='eval') parser.add_argument("--dataset_type", type=str, default='train') # mode parser.add_argument('--model_name', type=str, default='fine', metavar='NAME', help="the name of the model (default: fine") parser.add_argument('--quick', action='store_true', help="test on small cases") parser.add_argument('--train_model', action='store_true', help="train model") parser.add_argument('--con', action='store_true', help="continue train the given model") parser.add_argument('--demo_gen', action='store_true', help="demo gen mode") parser.add_argument('--demo_nums', type=int, default=8, help='total demo nums') parser.add_argument('--demo_name', type=str, default='small_test', help='demo names') parser.add_argument('--space', type=str, default='riemann', help='angle space') parser.add_argument('--eval_demo_name', type=str, default='small_test', help='demo names') parser.add_argument('--constrained', action='store_false', help="whether constrain base") parser.add_argument('--gt', action='store_true', help="gt mode") parser.add_argument('--device_id', type=int, default=0, help='device_id') # tensorboard parser.add_argument("--log_dir", type=str, default='gf_overfit') parser.add_argument("--pt_version", type=str, default='pt2') args = parser.parse_args() device = f'cuda:{args.device_id}' ''' make env ''' num_envs = args.num_envs # 53 envs = condexenvs.make( seed=args.seed, task="ShadowHandCon", num_envs=num_envs, sim_device=device, rl_device=device, graphics_device_id = args.device_id, virtual_screen_capture=False, headless=args.gui, force_render = False, mode = args.mode, num_run_envs = args.num_run_envs, method = args.method, dataset_type = args.dataset_type, ) envs.reset(env_init=True) print(args) # set_trace() ''' seed ''' np.random.seed(args.seed) torch.manual_seed(args.seed) torch.set_num_threads(4) random.seed(args.seed) ''' logging ''' exists_or_mkdir('./logs') ckpt_path = f'./logs/{args.log_dir}/' exists_or_mkdir(ckpt_path) tb_path = f'./logs/{args.log_dir}/tb' exists_or_mkdir(tb_path) writer = SummaryWriter(tb_path) ''' create train dataset and dataloader ''' dataset_path = f'./ExpertDatasets/grasp_data/ground/{args.demo_name}.pth' assert os.path.exists(dataset_path), 'Dataset not found!' with open(dataset_path, 'rb') as f: data_samples = pickle.load(f) print(len(data_samples)) ''' eval ''' eval_dataset_path = f'./ExpertDatasets/grasp_data/ground/{args.eval_demo_name}_rc.pth' assert os.path.exists(eval_dataset_path), 'Eval Dataset not found!' with open(eval_dataset_path, 'rb') as f: eval_data_samples = pickle.load(f) eval_dataset_ot_path = f'./ExpertDatasets/grasp_data/ground/{args.eval_demo_name}_rc_ot.pth' assert os.path.exists(eval_dataset_ot_path), 'Eval Dataset oti not found!' with open(eval_dataset_ot_path, 'rb') as f: eval_data_ot = pickle.load(f) # change data object type id eval_dataset_oti_path = f'./ExpertDatasets/grasp_data/ground/{args.eval_demo_name}_oti.pth' with open(eval_dataset_oti_path, 'rb') as f: eval_data_oti = pickle.load(f) for (i, data) in enumerate(eval_data_samples): env_id_in_full = int(data[25+points_per_object*3+7:25+points_per_object*3+8]) object_type = get_dict_key(eval_data_oti, env_id_in_full) env_id_in_current = envs.obj_type_id[object_type] eval_data_samples[i,3104] = env_id_in_current eval_dataset = torch.tensor(eval_data_samples, device=device) eval_dataset = eval_dataset.reshape(-1, eval_dataset.shape[-1]) args.num_envs = len(eval_data_ot) num_envs = len(eval_data_ot) test_per_object = int(len(eval_dataset)/num_envs) eval_demo_number = len(eval_data_samples) total_data_number = len(data_samples) # augment demos if total_data_number < args.demo_nums: new_data_samples = data_samples for i in range(args.demo_nums - total_data_number): new_data_samples = np.vstack((new_data_samples,data_samples[i%total_data_number])) dataset = new_data_samples else: dataset = data_samples dataset = dataset[: args.demo_nums] dataset = dataset.reshape(-1, dataset.shape[-1]) # set_trace() if 'all' in dataset_path: print('balance data') dataset = DexDataset(dataset) print(len(dataset)) if args.relative: dataloader = DataLoader(dataset=dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, drop_last=True) else: dataloader = DataLoader(dataset=dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, drop_last=True) ''' SDE ''' # init SDE config
prior_fn, marginal_prob_fn, sde_fn = init_sde(args.sde_mode, min=args.sde_min, max=args.sde_max)
2
2023-11-09 06:08:40+00:00
12k
ApolloAuto/apollo-model-centerpoint
paddle3d/transforms/reader.py
[ { "identifier": "manager", "path": "paddle3d/apis/manager.py", "snippet": "class ComponentManager:\n def __init__(self, *, name: str, description: str = ''):\n def __len__(self):\n def __repr__(self):\n def __getitem__(self, item: str):\n def components_dict(self) -> dict:\n def name(s...
import os import cv2 import numpy as np from pathlib import Path from typing import List, Union from PIL import Image from paddle3d.apis import manager from paddle3d.datasets.kitti import kitti_utils from paddle3d.datasets.semantic_kitti.semantic_kitti import \ SemanticKITTIDataset from paddle3d.geometries import PointCloud from paddle3d.geometries.bbox import points_in_convex_polygon_3d_jit from paddle3d.sample import Sample from paddle3d.transforms import functional as F from paddle3d.transforms.base import TransformABC from paddle3d.utils.logger import logger
9,127
@manager.TRANSFORMS.add_component class LoadSemanticKITTIRange(TransformABC): """ Load SemanticKITTI range image. Please refer to <https://github.com/PRBonn/semantic-kitti-api/blob/master/auxiliary/laserscan.py>. Args: project_label (bool, optional): Whether project label to range view or not. """ def __init__(self, project_label=True): self.project_label = project_label self.proj_H = 64 self.proj_W = 1024 self.upper_inclination = 3. / 180. * np.pi self.lower_inclination = -25. / 180. * np.pi self.fov = self.upper_inclination - self.lower_inclination self.remap_lut = SemanticKITTIDataset.build_remap_lut() def _remap_semantic_labels(self, sem_label): """ Remap semantic labels to cross entropy format. Please refer to <https://github.com/PRBonn/semantic-kitti-api/blob/master/remap_semantic_labels.py>. """ return self.remap_lut[sem_label] def __call__(self, sample: Sample) -> Sample: raw_scan = np.fromfile(sample.path, dtype=np.float32).reshape((-1, 4)) points = raw_scan[:, 0:3] remissions = raw_scan[:, 3] # get depth of all points (L-2 norm of [x, y, z]) depth = np.linalg.norm(points, ord=2, axis=1) # get angles of all points scan_x = points[:, 0] scan_y = points[:, 1] scan_z = points[:, 2] yaw = -np.arctan2(scan_y, scan_x) pitch = np.arcsin(scan_z / depth) # get projections in image coords proj_x = 0.5 * (yaw / np.pi + 1.0) # in [0.0, 1.0] proj_y = 1.0 - ( pitch + abs(self.lower_inclination)) / self.fov # in [0.0, 1.0] # scale to image size using angular resolution proj_x *= self.proj_W # in [0.0, W] proj_y *= self.proj_H # in [0.0, H] # round and clamp for use as index proj_x = np.floor(proj_x) proj_x = np.minimum(self.proj_W - 1, proj_x) proj_x = np.maximum(0, proj_x).astype(np.int32) # in [0,W-1] proj_x_copy = np.copy( proj_x ) # save a copy in original order, for each point, where it is in the range image proj_y = np.floor(proj_y) proj_y = np.minimum(self.proj_H - 1, proj_y) proj_y = np.maximum(0, proj_y).astype(np.int32) # in [0,H-1] proj_y_copy = np.copy( proj_y ) # save a copy in original order, for each point, where it is in the range image # unproj_range_copy = np.copy(depth) # copy of depth in original order # order in decreasing depth indices = np.arange(depth.shape[0]) order = np.argsort(depth)[::-1] depth = depth[order] indices = indices[order] points = points[order] remission = remissions[order] proj_y = proj_y[order] proj_x = proj_x[order] # projected range image - [H,W] range (-1 is no data) proj_range = np.full((self.proj_H, self.proj_W), -1, dtype=np.float32) # projected point cloud xyz - [H,W,3] xyz coord (-1 is no data) proj_xyz = np.full((self.proj_H, self.proj_W, 3), -1, dtype=np.float32) # projected remission - [H,W] intensity (-1 is no data) proj_remission = np.full((self.proj_H, self.proj_W), -1, dtype=np.float32) # projected index (for each pixel, what I am in the pointcloud) # [H,W] index (-1 is no data) proj_idx = np.full((self.proj_H, self.proj_W), -1, dtype=np.int32) proj_range[proj_y, proj_x] = depth proj_xyz[proj_y, proj_x] = points proj_remission[proj_y, proj_x] = remission proj_idx[proj_y, proj_x] = indices proj_mask = proj_idx > 0 # mask containing for each pixel, if it contains a point or not sample.data = np.concatenate([ proj_range[None, ...], proj_xyz.transpose([2, 0, 1]), proj_remission[None, ...] ]) sample.meta["proj_mask"] = proj_mask.astype(np.float32) sample.meta["proj_x"] = proj_x_copy sample.meta["proj_y"] = proj_y_copy if sample.labels is not None: # load labels raw_label = np.fromfile( sample.labels, dtype=np.uint32).reshape((-1)) # only fill in attribute if the right size if raw_label.shape[0] == points.shape[0]: sem_label = raw_label & 0xFFFF # semantic label in lower half sem_label = self._remap_semantic_labels(sem_label) # inst_label = raw_label >> 16 # instance id in upper half else:
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = [ "LoadImage", "LoadPointCloud", "RemoveCameraInvisiblePointsKITTI", "RemoveCameraInvisiblePointsKITTIV2", "LoadSemanticKITTIRange" ] @manager.TRANSFORMS.add_component class LoadImage(TransformABC): """ """ _READER_MAPPER = {"cv2": cv2.imread, "pillow": Image.open} def __init__(self, to_chw: bool = True, to_rgb: bool = True, reader: str = "cv2"): if reader not in self._READER_MAPPER.keys(): raise ValueError('Unsupported reader {}'.format(reader)) self.reader = reader self.to_rgb = to_rgb self.to_chw = to_chw def __call__(self, sample: Sample) -> Sample: """ """ sample.data = np.array(self._READER_MAPPER[self.reader](sample.path)) sample.meta.image_reader = self.reader sample.meta.image_format = "bgr" if self.reader == "cv2" else "rgb" sample.meta.channel_order = "hwc" if sample.meta.image_format != "rgb" and self.to_rgb: if sample.meta.image_format == "bgr": sample.data = cv2.cvtColor(sample.data, cv2.COLOR_BGR2RGB) sample.meta.image_format = "rgb" else: raise RuntimeError('Unsupported image format {}'.format( sample.meta.image_format)) elif sample.meta.image_format != "bgr" and (self.to_rgb is False): if sample.meta.image_format == "rgb": sample.data = sample.data[:, :, ::-1] sample.meta.image_format = "bgr" else: raise RuntimeError('Unsupported image format {}'.format( sample.meta.image_format)) if self.to_chw: sample.data = sample.data.transpose((2, 0, 1)) sample.meta.channel_order = "chw" return sample @manager.TRANSFORMS.add_component class LoadPointCloud(TransformABC): """ Load point cloud. Args: dim: The dimension of each point. use_dim: The dimension of each point to use. use_time_lag: Whether to use time lag. sweep_remove_radius: The radius within which points are removed in sweeps. """ def __init__(self, dim, use_dim: Union[int, List[int]] = None, use_time_lag: bool = False, sweep_remove_radius: float = 1, sep: str = ''): self.dim = dim self.use_dim = range(use_dim) if isinstance(use_dim, int) else use_dim self.use_time_lag = use_time_lag self.sweep_remove_radius = sweep_remove_radius self.sep = sep def __call__(self, sample: Sample): """ """ if sample.modality != "lidar": raise ValueError('{} Only Support samples in modality lidar'.format( self.__class__.__name__)) if sample.data is not None: raise ValueError( 'The data for this sample has been processed before.') data = np.fromfile(sample.path, np.float32, sep=self.sep).reshape(-1, self.dim) if self.use_dim is not None: data = data[:, self.use_dim] if self.use_time_lag: time_lag = np.zeros((data.shape[0], 1), dtype=data.dtype) data = np.hstack([data, time_lag]) if len(sample.sweeps) > 0: data_sweep_list = [ data, ] for i in np.random.choice( len(sample.sweeps), len(sample.sweeps), replace=False): sweep = sample.sweeps[i] sweep_data = np.fromfile(sweep.path, np.float32).reshape( -1, self.dim) if self.use_dim: sweep_data = sweep_data[:, self.use_dim] sweep_data = sweep_data.T # Remove points that are in a certain radius from origin. x_filter_mask = np.abs( sweep_data[0, :]) < self.sweep_remove_radius y_filter_mask = np.abs( sweep_data[1, :]) < self.sweep_remove_radius not_close = np.logical_not( np.logical_and(x_filter_mask, y_filter_mask)) sweep_data = sweep_data[:, not_close] # Homogeneous transform of current sample to reference coordinate if sweep.meta.ref_from_curr is not None: sweep_data[:3, :] = sweep.meta.ref_from_curr.dot( np.vstack((sweep_data[:3, :], np.ones(sweep_data.shape[1]))))[:3, :] sweep_data = sweep_data.T if self.use_time_lag: curr_time_lag = sweep.meta.time_lag * np.ones( (sweep_data.shape[0], 1)).astype(sweep_data.dtype) sweep_data = np.hstack([sweep_data, curr_time_lag]) data_sweep_list.append(sweep_data) data = np.concatenate(data_sweep_list, axis=0) sample.data = PointCloud(data) return sample @manager.TRANSFORMS.add_component class RemoveCameraInvisiblePointsKITTI(TransformABC): """ Remove camera invisible points for KITTI dataset. """ def __call__(self, sample: Sample): calibs = sample.calibs C, Rinv, T = kitti_utils.projection_matrix_decomposition(calibs[2]) im_path = (Path(sample.path).parents[1] / "image_2" / Path( sample.path).stem).with_suffix(".png") if os.path.exists(im_path): im_shape = cv2.imread(str(im_path)).shape[:2] else: im_shape = (375, 1242) im_shape = np.array(im_shape, dtype=np.int32) im_bbox = [0, 0, im_shape[1], im_shape[0]] frustum = F.get_frustum(im_bbox, C) frustum = (Rinv @ (frustum - T).T).T frustum = kitti_utils.coord_camera_to_velodyne(frustum, calibs) frustum_normals = F.corner_to_surface_normal(frustum[None, ...]) indices = points_in_convex_polygon_3d_jit(sample.data[:, :3], frustum_normals) sample.data = sample.data[indices.reshape([-1])] return sample @manager.TRANSFORMS.add_component class RemoveCameraInvisiblePointsKITTIV2(TransformABC): """ Remove camera invisible points for KITTI dataset, unlike `RemoveCameraInvisiblePointsKITTI` which projects image plane to a frustum, this version projects poinst into image plane and remove the points outside the image boundary. """ def __init__(self): self.V2C = None self.R0 = None def __call__(self, sample: Sample): calibs = sample.calibs self.R0 = calibs[4] self.V2C = calibs[5] self.P2 = calibs[2] im_path = (Path(sample.path).parents[1] / "image_2" / Path( sample.path).stem).with_suffix(".png") if os.path.exists(im_path): im_shape = cv2.imread(str(im_path)).shape[:2] else: im_shape = (375, 1242) im_shape = np.array(im_shape, dtype=np.int32) pts = sample.data[:, 0:3] # lidar to rect pts_lidar_hom = self.cart_to_hom(pts) pts_rect = np.dot(pts_lidar_hom, np.dot(self.V2C.T, self.R0.T)) # rect to img pts_img, pts_rect_depth = self.rect_to_img(pts_rect) val_flag_1 = np.logical_and(pts_img[:, 0] >= 0, pts_img[:, 0] < im_shape[1]) val_flag_2 = np.logical_and(pts_img[:, 1] >= 0, pts_img[:, 1] < im_shape[0]) val_flag_merge = np.logical_and(val_flag_1, val_flag_2) pts_valid_flag = np.logical_and(val_flag_merge, pts_rect_depth >= 0) sample.data = sample.data[pts_valid_flag] return sample def cart_to_hom(self, pts): pts_hom = np.hstack((pts, np.ones((pts.shape[0], 1), dtype=np.float32))) return pts_hom def rect_to_img(self, pts_rect): pts_rect_hom = self.cart_to_hom(pts_rect) pts_2d_hom = np.dot(pts_rect_hom, self.P2.T) pts_img = (pts_2d_hom[:, 0:2].T / pts_rect_hom[:, 2]).T # (N, 2) pts_rect_depth = pts_2d_hom[:, 2] - self.P2.T[ 3, 2] # depth in rect camera coord return pts_img, pts_rect_depth @manager.TRANSFORMS.add_component class LoadSemanticKITTIRange(TransformABC): """ Load SemanticKITTI range image. Please refer to <https://github.com/PRBonn/semantic-kitti-api/blob/master/auxiliary/laserscan.py>. Args: project_label (bool, optional): Whether project label to range view or not. """ def __init__(self, project_label=True): self.project_label = project_label self.proj_H = 64 self.proj_W = 1024 self.upper_inclination = 3. / 180. * np.pi self.lower_inclination = -25. / 180. * np.pi self.fov = self.upper_inclination - self.lower_inclination self.remap_lut = SemanticKITTIDataset.build_remap_lut() def _remap_semantic_labels(self, sem_label): """ Remap semantic labels to cross entropy format. Please refer to <https://github.com/PRBonn/semantic-kitti-api/blob/master/remap_semantic_labels.py>. """ return self.remap_lut[sem_label] def __call__(self, sample: Sample) -> Sample: raw_scan = np.fromfile(sample.path, dtype=np.float32).reshape((-1, 4)) points = raw_scan[:, 0:3] remissions = raw_scan[:, 3] # get depth of all points (L-2 norm of [x, y, z]) depth = np.linalg.norm(points, ord=2, axis=1) # get angles of all points scan_x = points[:, 0] scan_y = points[:, 1] scan_z = points[:, 2] yaw = -np.arctan2(scan_y, scan_x) pitch = np.arcsin(scan_z / depth) # get projections in image coords proj_x = 0.5 * (yaw / np.pi + 1.0) # in [0.0, 1.0] proj_y = 1.0 - ( pitch + abs(self.lower_inclination)) / self.fov # in [0.0, 1.0] # scale to image size using angular resolution proj_x *= self.proj_W # in [0.0, W] proj_y *= self.proj_H # in [0.0, H] # round and clamp for use as index proj_x = np.floor(proj_x) proj_x = np.minimum(self.proj_W - 1, proj_x) proj_x = np.maximum(0, proj_x).astype(np.int32) # in [0,W-1] proj_x_copy = np.copy( proj_x ) # save a copy in original order, for each point, where it is in the range image proj_y = np.floor(proj_y) proj_y = np.minimum(self.proj_H - 1, proj_y) proj_y = np.maximum(0, proj_y).astype(np.int32) # in [0,H-1] proj_y_copy = np.copy( proj_y ) # save a copy in original order, for each point, where it is in the range image # unproj_range_copy = np.copy(depth) # copy of depth in original order # order in decreasing depth indices = np.arange(depth.shape[0]) order = np.argsort(depth)[::-1] depth = depth[order] indices = indices[order] points = points[order] remission = remissions[order] proj_y = proj_y[order] proj_x = proj_x[order] # projected range image - [H,W] range (-1 is no data) proj_range = np.full((self.proj_H, self.proj_W), -1, dtype=np.float32) # projected point cloud xyz - [H,W,3] xyz coord (-1 is no data) proj_xyz = np.full((self.proj_H, self.proj_W, 3), -1, dtype=np.float32) # projected remission - [H,W] intensity (-1 is no data) proj_remission = np.full((self.proj_H, self.proj_W), -1, dtype=np.float32) # projected index (for each pixel, what I am in the pointcloud) # [H,W] index (-1 is no data) proj_idx = np.full((self.proj_H, self.proj_W), -1, dtype=np.int32) proj_range[proj_y, proj_x] = depth proj_xyz[proj_y, proj_x] = points proj_remission[proj_y, proj_x] = remission proj_idx[proj_y, proj_x] = indices proj_mask = proj_idx > 0 # mask containing for each pixel, if it contains a point or not sample.data = np.concatenate([ proj_range[None, ...], proj_xyz.transpose([2, 0, 1]), proj_remission[None, ...] ]) sample.meta["proj_mask"] = proj_mask.astype(np.float32) sample.meta["proj_x"] = proj_x_copy sample.meta["proj_y"] = proj_y_copy if sample.labels is not None: # load labels raw_label = np.fromfile( sample.labels, dtype=np.uint32).reshape((-1)) # only fill in attribute if the right size if raw_label.shape[0] == points.shape[0]: sem_label = raw_label & 0xFFFF # semantic label in lower half sem_label = self._remap_semantic_labels(sem_label) # inst_label = raw_label >> 16 # instance id in upper half else:
logger.error("Point cloud shape: {}".format(points.shape))
8
2023-11-08 07:08:03+00:00
12k
camlsys/fl-project-template
project/main.py
[ { "identifier": "get_client_generator", "path": "project/client/client.py", "snippet": "def get_client_generator(\n working_dir: Path,\n net_generator: NetGen,\n dataloader_gen: ClientDataloaderGen,\n train: TrainFunc,\n test: TestFunc,\n) -> ClientGen:\n \"\"\"Return a function which ...
import json import logging import os import subprocess import sys import flwr as fl import hydra import wandb from pathlib import Path from typing import cast from flwr.common.logger import log from hydra.core.hydra_config import HydraConfig from hydra.utils import instantiate from omegaconf import DictConfig, OmegaConf from project.client.client import get_client_generator from project.dispatch.dispatch import dispatch_config, dispatch_data, dispatch_train from project.fed.server.deterministic_client_manager import DeterministicClientManager from project.fed.server.wandb_history import WandbHistory from project.fed.server.wandb_server import WandbServer from project.fed.utils.utils import ( get_initial_parameters, get_save_parameters_to_file, get_weighted_avg_metrics_agg_fn, test_client, ) from project.types.common import ClientGen, FedEvalFN from project.utils.utils import ( FileSystemManager, RayContextManager, seed_everything, wandb_init, )
7,628
"""Create and connect the building blocks for your experiments; start the simulation. It includes processing the dataset, instantiate strategy, specifying how the global model will be evaluated, etc. In the end, this script saves the results. """ # Only import from the project root # Never do a relative import nor one that assumes a given folder structure # Make debugging easier when using Hydra + Ray os.environ["HYDRA_FULL_ERROR"] = "1" os.environ["OC_CAUSE"] = "1" @hydra.main( config_path="conf", config_name="base", version_base=None, ) def main(cfg: DictConfig) -> None: """Run the baseline. Parameters ---------- cfg : DictConfig An omegaconf object that stores the hydra config. """ # Print parsed config log(logging.INFO, OmegaConf.to_yaml(cfg)) wandb_config = OmegaConf.to_container( cfg, resolve=True, throw_on_missing=True, ) # Obtain the output dir from hydra original_hydra_dir = Path( hydra.utils.to_absolute_path( HydraConfig.get().runtime.output_dir, ), ) output_directory = original_hydra_dir # Reuse an output directory for checkpointing if cfg.reuse_output_dir is not None: output_directory = Path(cfg.reuse_output_dir) # The directory to save data to results_dir = output_directory / "results" results_dir.mkdir(parents=True, exist_ok=True) # Where to save files to and from if cfg.working_dir is not None: # Pre-defined directory working_dir = Path(cfg.working_dir) else: # Default directory working_dir = output_directory / "working" working_dir.mkdir(parents=True, exist_ok=True) # Wandb context manager # controlls if wandb is initialised or not # if not it returns a dummy run
"""Create and connect the building blocks for your experiments; start the simulation. It includes processing the dataset, instantiate strategy, specifying how the global model will be evaluated, etc. In the end, this script saves the results. """ # Only import from the project root # Never do a relative import nor one that assumes a given folder structure # Make debugging easier when using Hydra + Ray os.environ["HYDRA_FULL_ERROR"] = "1" os.environ["OC_CAUSE"] = "1" @hydra.main( config_path="conf", config_name="base", version_base=None, ) def main(cfg: DictConfig) -> None: """Run the baseline. Parameters ---------- cfg : DictConfig An omegaconf object that stores the hydra config. """ # Print parsed config log(logging.INFO, OmegaConf.to_yaml(cfg)) wandb_config = OmegaConf.to_container( cfg, resolve=True, throw_on_missing=True, ) # Obtain the output dir from hydra original_hydra_dir = Path( hydra.utils.to_absolute_path( HydraConfig.get().runtime.output_dir, ), ) output_directory = original_hydra_dir # Reuse an output directory for checkpointing if cfg.reuse_output_dir is not None: output_directory = Path(cfg.reuse_output_dir) # The directory to save data to results_dir = output_directory / "results" results_dir.mkdir(parents=True, exist_ok=True) # Where to save files to and from if cfg.working_dir is not None: # Pre-defined directory working_dir = Path(cfg.working_dir) else: # Default directory working_dir = output_directory / "working" working_dir.mkdir(parents=True, exist_ok=True) # Wandb context manager # controlls if wandb is initialised or not # if not it returns a dummy run
with wandb_init(
15
2023-11-08 15:31:44+00:00
12k
silicx/GoldFromOres
DatasetCondensation/main.py
[ { "identifier": "get_loops", "path": "DatasetCondensation/utils.py", "snippet": "def get_loops(ipc):\r\n # Get the two hyper-parameters of outer-loop and inner-loop.\r\n # The following values are empirically good.\r\n if ipc == 1:\r\n outer_loop, inner_loop = 1, 1\r\n elif ipc == 10:...
import os import time import copy import argparse import numpy as np import torch import torch.nn as nn import pdb from torchvision.utils import save_image from .utils import get_loops, get_dataset, get_network, get_eval_pool, evaluate_synset, get_daparam, match_loss, get_time, TensorDataset, epoch, DiffAugment, ParamDiffAug from drop_utils import drop_samples
7,780
parser.add_argument('--method', type=str, default='DC', help='DC/DSA') parser.add_argument('--dataset', type=str, default='CIFAR10', help='dataset') parser.add_argument('--model', type=str, default='ConvNet', help='model') parser.add_argument('--ipc', type=int, default=1, help='image(s) per class') parser.add_argument('--eval_mode', type=str, default='S', help='eval_mode') # S: the same to training model, M: multi architectures, W: net width, D: net depth, A: activation function, P: pooling layer, N: normalization layer, parser.add_argument('--num_exp', type=int, default=5, help='the number of experiments') parser.add_argument('--num_eval', type=int, default=20, help='the number of evaluating randomly initialized models') parser.add_argument('--epoch_eval_train', type=int, default=300, help='epochs to train a model with synthetic data') parser.add_argument('--Iteration', type=int, default=1000, help='training iterations') parser.add_argument('--lr_img', type=float, default=0.1, help='learning rate for updating synthetic images') parser.add_argument('--lr_net', type=float, default=0.01, help='learning rate for updating network parameters') parser.add_argument('--batch_real', type=int, default=256, help='batch size for real data') parser.add_argument('--batch_train', type=int, default=256, help='batch size for training networks') parser.add_argument('--init', type=str, default='noise', help='noise/real: initialize synthetic images from random noise or randomly sampled real images.') parser.add_argument('--dsa_strategy', type=str, default='None', help='differentiable Siamese augmentation strategy') parser.add_argument('--data_path', type=str, default='data', help='dataset path') parser.add_argument('--save_path', type=str, default='result', help='path to save results') parser.add_argument('--dis_metric', type=str, default='ours', help='distance metric') parser.add_argument('--drop_criterion', type=str, default='LossConverge_large', help='Criterion for data dropping') parser.add_argument('--drop_ratio', type=float, default=0.0, help='The ratio to drop (for each class)') args = parser.parse_args() args.outer_loop, args.inner_loop = get_loops(args.ipc) args.device = 'cuda' if torch.cuda.is_available() else 'cpu' args.dsa_param = ParamDiffAug() args.dsa = True if args.method == 'DSA' else False if not os.path.exists(args.data_path): os.mkdir(args.data_path) if not os.path.exists(args.save_path): os.mkdir(args.save_path) eval_it_pool = np.arange(0, args.Iteration+1, 500).tolist() if args.eval_mode == 'S' or args.eval_mode == 'SS' else [args.Iteration] # The list of iterations when we evaluate models and record results. print('eval_it_pool: ', eval_it_pool) channel, im_size, num_classes, class_names, mean, std, dst_train, dst_test, testloader = get_dataset(args.dataset, args.data_path) model_eval_pool = get_eval_pool(args.eval_mode, args.model, args.model) accs_all_exps = dict() # record performances of all experiments for key in model_eval_pool: accs_all_exps[key] = [] data_save = [] for exp in range(args.num_exp): print('\n================== Exp %d ==================\n '%exp) print('Hyper-parameters: \n', args.__dict__) print('Evaluation model pool: ', model_eval_pool) ''' organize the real dataset ''' images_all = [] labels_all = [] indices_class = [[] for c in range(num_classes)] images_all = [torch.unsqueeze(dst_train[i][0], dim=0) for i in range(len(dst_train))] labels_all = [dst_train[i][1] for i in range(len(dst_train))] for i, lab in enumerate(labels_all): indices_class[lab].append(i) images_all = torch.cat(images_all, dim=0).to(args.device) labels_all = torch.tensor(labels_all, dtype=torch.long, device=args.device) images_all, labels_all, indices_class = drop_samples( images_all, labels_all, indices_class, args.dataset, args.drop_criterion, drop_ratio=args.drop_ratio) for c in range(num_classes): print('class c = %d: %d real images'%(c, len(indices_class[c]))) def get_images(c, n): # get random n images from class c idx_shuffle = np.random.permutation(indices_class[c])[:n] return images_all[idx_shuffle] for ch in range(channel): print('real images channel %d, mean = %.4f, std = %.4f'%(ch, torch.mean(images_all[:, ch]), torch.std(images_all[:, ch]))) ''' initialize the synthetic data ''' image_syn = torch.randn(size=(num_classes*args.ipc, channel, im_size[0], im_size[1]), dtype=torch.float, requires_grad=True, device=args.device) label_syn = torch.tensor([np.ones(args.ipc)*i for i in range(num_classes)], dtype=torch.long, requires_grad=False, device=args.device).view(-1) # [0,0,0, 1,1,1, ..., 9,9,9] if args.init == 'real': print('initialize synthetic data from random real images') for c in range(num_classes): image_syn.data[c*args.ipc:(c+1)*args.ipc] = get_images(c, args.ipc).detach().data else: print('initialize synthetic data from random noise') ''' training ''' optimizer_img = torch.optim.SGD([image_syn, ], lr=args.lr_img, momentum=0.5) # optimizer_img for synthetic data optimizer_img.zero_grad() criterion = nn.CrossEntropyLoss().to(args.device) print('%s training begins'%get_time()) for it in range(args.Iteration+1): ''' Evaluate synthetic data ''' if it in eval_it_pool: for model_eval in model_eval_pool: print('-------------------------\nEvaluation\nmodel_train = %s, model_eval = %s, iteration = %d'%(args.model, model_eval, it)) if args.dsa: args.epoch_eval_train = 1000 args.dc_aug_param = None print('DSA augmentation strategy: \n', args.dsa_strategy) print('DSA augmentation parameters: \n', args.dsa_param.__dict__) else: args.dc_aug_param = get_daparam(args.dataset, args.model, model_eval, args.ipc) # This augmentation parameter set is only for DC method. It will be muted when args.dsa is True. print('DC augmentation parameters: \n', args.dc_aug_param) if args.dsa or args.dc_aug_param['strategy'] != 'none': args.epoch_eval_train = 1000 # Training with data augmentation needs more epochs. else: args.epoch_eval_train = 300 accs = [] for it_eval in range(args.num_eval):
def main(): parser = argparse.ArgumentParser(description='Parameter Processing') parser.add_argument('--method', type=str, default='DC', help='DC/DSA') parser.add_argument('--dataset', type=str, default='CIFAR10', help='dataset') parser.add_argument('--model', type=str, default='ConvNet', help='model') parser.add_argument('--ipc', type=int, default=1, help='image(s) per class') parser.add_argument('--eval_mode', type=str, default='S', help='eval_mode') # S: the same to training model, M: multi architectures, W: net width, D: net depth, A: activation function, P: pooling layer, N: normalization layer, parser.add_argument('--num_exp', type=int, default=5, help='the number of experiments') parser.add_argument('--num_eval', type=int, default=20, help='the number of evaluating randomly initialized models') parser.add_argument('--epoch_eval_train', type=int, default=300, help='epochs to train a model with synthetic data') parser.add_argument('--Iteration', type=int, default=1000, help='training iterations') parser.add_argument('--lr_img', type=float, default=0.1, help='learning rate for updating synthetic images') parser.add_argument('--lr_net', type=float, default=0.01, help='learning rate for updating network parameters') parser.add_argument('--batch_real', type=int, default=256, help='batch size for real data') parser.add_argument('--batch_train', type=int, default=256, help='batch size for training networks') parser.add_argument('--init', type=str, default='noise', help='noise/real: initialize synthetic images from random noise or randomly sampled real images.') parser.add_argument('--dsa_strategy', type=str, default='None', help='differentiable Siamese augmentation strategy') parser.add_argument('--data_path', type=str, default='data', help='dataset path') parser.add_argument('--save_path', type=str, default='result', help='path to save results') parser.add_argument('--dis_metric', type=str, default='ours', help='distance metric') parser.add_argument('--drop_criterion', type=str, default='LossConverge_large', help='Criterion for data dropping') parser.add_argument('--drop_ratio', type=float, default=0.0, help='The ratio to drop (for each class)') args = parser.parse_args() args.outer_loop, args.inner_loop = get_loops(args.ipc) args.device = 'cuda' if torch.cuda.is_available() else 'cpu' args.dsa_param = ParamDiffAug() args.dsa = True if args.method == 'DSA' else False if not os.path.exists(args.data_path): os.mkdir(args.data_path) if not os.path.exists(args.save_path): os.mkdir(args.save_path) eval_it_pool = np.arange(0, args.Iteration+1, 500).tolist() if args.eval_mode == 'S' or args.eval_mode == 'SS' else [args.Iteration] # The list of iterations when we evaluate models and record results. print('eval_it_pool: ', eval_it_pool) channel, im_size, num_classes, class_names, mean, std, dst_train, dst_test, testloader = get_dataset(args.dataset, args.data_path) model_eval_pool = get_eval_pool(args.eval_mode, args.model, args.model) accs_all_exps = dict() # record performances of all experiments for key in model_eval_pool: accs_all_exps[key] = [] data_save = [] for exp in range(args.num_exp): print('\n================== Exp %d ==================\n '%exp) print('Hyper-parameters: \n', args.__dict__) print('Evaluation model pool: ', model_eval_pool) ''' organize the real dataset ''' images_all = [] labels_all = [] indices_class = [[] for c in range(num_classes)] images_all = [torch.unsqueeze(dst_train[i][0], dim=0) for i in range(len(dst_train))] labels_all = [dst_train[i][1] for i in range(len(dst_train))] for i, lab in enumerate(labels_all): indices_class[lab].append(i) images_all = torch.cat(images_all, dim=0).to(args.device) labels_all = torch.tensor(labels_all, dtype=torch.long, device=args.device) images_all, labels_all, indices_class = drop_samples( images_all, labels_all, indices_class, args.dataset, args.drop_criterion, drop_ratio=args.drop_ratio) for c in range(num_classes): print('class c = %d: %d real images'%(c, len(indices_class[c]))) def get_images(c, n): # get random n images from class c idx_shuffle = np.random.permutation(indices_class[c])[:n] return images_all[idx_shuffle] for ch in range(channel): print('real images channel %d, mean = %.4f, std = %.4f'%(ch, torch.mean(images_all[:, ch]), torch.std(images_all[:, ch]))) ''' initialize the synthetic data ''' image_syn = torch.randn(size=(num_classes*args.ipc, channel, im_size[0], im_size[1]), dtype=torch.float, requires_grad=True, device=args.device) label_syn = torch.tensor([np.ones(args.ipc)*i for i in range(num_classes)], dtype=torch.long, requires_grad=False, device=args.device).view(-1) # [0,0,0, 1,1,1, ..., 9,9,9] if args.init == 'real': print('initialize synthetic data from random real images') for c in range(num_classes): image_syn.data[c*args.ipc:(c+1)*args.ipc] = get_images(c, args.ipc).detach().data else: print('initialize synthetic data from random noise') ''' training ''' optimizer_img = torch.optim.SGD([image_syn, ], lr=args.lr_img, momentum=0.5) # optimizer_img for synthetic data optimizer_img.zero_grad() criterion = nn.CrossEntropyLoss().to(args.device) print('%s training begins'%get_time()) for it in range(args.Iteration+1): ''' Evaluate synthetic data ''' if it in eval_it_pool: for model_eval in model_eval_pool: print('-------------------------\nEvaluation\nmodel_train = %s, model_eval = %s, iteration = %d'%(args.model, model_eval, it)) if args.dsa: args.epoch_eval_train = 1000 args.dc_aug_param = None print('DSA augmentation strategy: \n', args.dsa_strategy) print('DSA augmentation parameters: \n', args.dsa_param.__dict__) else: args.dc_aug_param = get_daparam(args.dataset, args.model, model_eval, args.ipc) # This augmentation parameter set is only for DC method. It will be muted when args.dsa is True. print('DC augmentation parameters: \n', args.dc_aug_param) if args.dsa or args.dc_aug_param['strategy'] != 'none': args.epoch_eval_train = 1000 # Training with data augmentation needs more epochs. else: args.epoch_eval_train = 300 accs = [] for it_eval in range(args.num_eval):
net_eval = get_network(model_eval, channel, num_classes, im_size).to(args.device) # get a random model
2
2023-11-03 09:34:15+00:00
12k
gchada/ROAM
real/rail_walker_interface/environment/joystick_real.py
[ { "identifier": "WalkerEnvironment", "path": "real/rail_walker_interface/environment/env.py", "snippet": "class WalkerEnvironment:\n @property\n def robot(self) -> BaseWalker:\n pass" }, { "identifier": "JoystickEnvironment", "path": "real/rail_walker_interface/environment/env.p...
import gym import gym.spaces import numpy as np import copy from .env import WalkerEnvironment, JoystickEnvironment from ..robot import BaseWalker, BaseWalkerWithFootContact from ..joystick_policy import JoystickPolicy from functools import cached_property from typing import Optional, Any from collections import OrderedDict
7,487
ret_dict["robot/foot_forces"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_forces_normalized"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_forces_normalized_masked"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_contacts"] = gym.spaces.Box( # should use MultiBinary but flatten() does not support having multibinary / box spaces in a Dict low=0, high=1, shape=(4,), dtype=np.float32 ) return gym.spaces.Dict(ret_dict) def extract_observation(self) -> dict[str,Any]: roll, pitch, yaw = self.env.robot.get_roll_pitch_yaw() dr, dp, dy = self.env.robot.get_3d_angular_velocity() imu = np.array([roll, pitch, dr, dp], dtype=np.float32) ret_dict = { "robot/joints_pos": self.env.robot.get_joint_qpos(), "robot/joints_vel": self.env.robot.get_joint_qvel(), "robot/imu": imu, "robot/sensors_gyro": self.env.robot.get_3d_angular_velocity(), "robot/sensors_framequat": self.env.robot.get_framequat_wijk(), "robot/torques": self.env.robot.get_joint_torques(), "robot/sensors_local_velocimeter": self.env.robot.get_3d_local_velocity(), "robot/sensors_local_velocimeter_x": self.env.robot.get_3d_local_velocity()[0:1], "robot/sensors_accelerometer": self.env.robot.get_3d_acceleration_local(), } if isinstance(self.env.robot.unwrapped(), BaseWalkerWithFootContact): ret_dict["robot/foot_forces"] = self.env.robot.get_foot_force() ret_dict["robot/foot_contacts"] = self.env.robot.get_foot_contact() if hasattr(self.env.robot, "foot_contact_no_contact_threshold") and hasattr(self.env.robot, "foot_contact_has_contact_threshold"): ret_dict["robot/foot_forces_normalized"] = (ret_dict["robot/foot_forces"] - self.env.robot.foot_contact_no_contact_threshold) / (self.env.robot.foot_contact_has_contact_threshold - self.env.robot.foot_contact_no_contact_threshold) else: ret_dict["robot/foot_forces_normalized"] = ret_dict["robot/foot_forces"] masked_foot_forces = ret_dict["robot/foot_forces_normalized"].copy() masked_foot_forces[-1] = 0.0 ret_dict["robot/foot_forces_normalized_masked"] = masked_foot_forces return ret_dict class JoystickEnvImpl(gym.Env[dict[str,Any],np.ndarray], WalkerEnvironment, JoystickEnvironment): metadata = { "render_modes": [] } def __init__( self, joystick_policy : JoystickPolicy ): gym.Env.__init__(self) WalkerEnvironment.__init__(self) JoystickEnvironment.__init__(self) # ====================== Store Parameters ====================== self._joystick_policy = joystick_policy self.obs_extractor = JoystickEnvObservationExtractor(self) self.random_state = np.random.RandomState() @property def action_space(self) -> gym.spaces.Box: return gym.spaces.Box( low=self.robot.action_qpos_mins, high=self.robot.action_qpos_maxs, dtype=np.float32 ) @property def observation_space(self) -> gym.spaces.Dict: robot_space = self.obs_extractor.observation_spec real_obs_space = {} for key, space in robot_space.items(): if key.startswith("robot/") and key[len("robot/"):] in self.joystick_policy.enabled_observables: real_obs_space[key] = space if self.joystick_policy.target_observable is not None: real_obs_space["target_obs"] = self.joystick_policy.target_observable.get_observation_spec() if not self.joystick_policy.target_yaw_provider.is_target_velocity_fixed(): real_obs_space["target_vel"] = gym.spaces.Box( low = 0.0, high = np.inf, shape=(1,) ) target_custom_data_spec = self.joystick_policy.target_yaw_provider.get_target_custom_data_observable_spec() if self.joystick_policy.enable_target_custom_obs and target_custom_data_spec is not None: real_obs_space["target_custom"] = target_custom_data_spec # Enforce order real_obs_space = OrderedDict(sorted(real_obs_space.items(), key=lambda t: t[0])) obs_space = gym.spaces.Dict(real_obs_space) return obs_space @property def joystick_policy(self) -> JoystickPolicy: return self._joystick_policy def set_joystick_policy(self, joystick_policy: JoystickPolicy): self._joystick_policy = joystick_policy @property def is_resetter_policy(self) -> bool: return False @property
class JoystickEnvObservationExtractor: def __init__(self, env : "JoystickEnvImpl"): self.env = env @cached_property def observation_spec(self) -> gym.spaces.Dict: ret_dict = { "robot/joints_pos": gym.spaces.Box( low=self.env.robot.joint_qpos_mins, high=self.env.robot.joint_qpos_maxs, shape=(self.env.robot.joint_nums,), dtype=np.float32 ), "robot/joints_vel": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(self.env.robot.joint_nums,), dtype=np.float32 ), "robot/imu": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), ), "robot/sensors_gyro": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(3,), dtype=np.float32 ), "robot/sensors_framequat": gym.spaces.Box( low=-1.0, high=1.0, shape=(4,), dtype=np.float32 ), "robot/torques": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(self.env.robot.joint_nums,), dtype=np.float32 ), "robot/sensors_local_velocimeter": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(3,), dtype=np.float32 ), "robot/sensors_local_velocimeter_x": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(1,), dtype=np.float32 ), "robot/sensors_accelerometer": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(3,), dtype=np.float32 ), } if isinstance(self.env.robot.unwrapped(), BaseWalkerWithFootContact): ret_dict["robot/foot_forces"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_forces_normalized"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_forces_normalized_masked"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_contacts"] = gym.spaces.Box( # should use MultiBinary but flatten() does not support having multibinary / box spaces in a Dict low=0, high=1, shape=(4,), dtype=np.float32 ) return gym.spaces.Dict(ret_dict) def extract_observation(self) -> dict[str,Any]: roll, pitch, yaw = self.env.robot.get_roll_pitch_yaw() dr, dp, dy = self.env.robot.get_3d_angular_velocity() imu = np.array([roll, pitch, dr, dp], dtype=np.float32) ret_dict = { "robot/joints_pos": self.env.robot.get_joint_qpos(), "robot/joints_vel": self.env.robot.get_joint_qvel(), "robot/imu": imu, "robot/sensors_gyro": self.env.robot.get_3d_angular_velocity(), "robot/sensors_framequat": self.env.robot.get_framequat_wijk(), "robot/torques": self.env.robot.get_joint_torques(), "robot/sensors_local_velocimeter": self.env.robot.get_3d_local_velocity(), "robot/sensors_local_velocimeter_x": self.env.robot.get_3d_local_velocity()[0:1], "robot/sensors_accelerometer": self.env.robot.get_3d_acceleration_local(), } if isinstance(self.env.robot.unwrapped(), BaseWalkerWithFootContact): ret_dict["robot/foot_forces"] = self.env.robot.get_foot_force() ret_dict["robot/foot_contacts"] = self.env.robot.get_foot_contact() if hasattr(self.env.robot, "foot_contact_no_contact_threshold") and hasattr(self.env.robot, "foot_contact_has_contact_threshold"): ret_dict["robot/foot_forces_normalized"] = (ret_dict["robot/foot_forces"] - self.env.robot.foot_contact_no_contact_threshold) / (self.env.robot.foot_contact_has_contact_threshold - self.env.robot.foot_contact_no_contact_threshold) else: ret_dict["robot/foot_forces_normalized"] = ret_dict["robot/foot_forces"] masked_foot_forces = ret_dict["robot/foot_forces_normalized"].copy() masked_foot_forces[-1] = 0.0 ret_dict["robot/foot_forces_normalized_masked"] = masked_foot_forces return ret_dict class JoystickEnvImpl(gym.Env[dict[str,Any],np.ndarray], WalkerEnvironment, JoystickEnvironment): metadata = { "render_modes": [] } def __init__( self, joystick_policy : JoystickPolicy ): gym.Env.__init__(self) WalkerEnvironment.__init__(self) JoystickEnvironment.__init__(self) # ====================== Store Parameters ====================== self._joystick_policy = joystick_policy self.obs_extractor = JoystickEnvObservationExtractor(self) self.random_state = np.random.RandomState() @property def action_space(self) -> gym.spaces.Box: return gym.spaces.Box( low=self.robot.action_qpos_mins, high=self.robot.action_qpos_maxs, dtype=np.float32 ) @property def observation_space(self) -> gym.spaces.Dict: robot_space = self.obs_extractor.observation_spec real_obs_space = {} for key, space in robot_space.items(): if key.startswith("robot/") and key[len("robot/"):] in self.joystick_policy.enabled_observables: real_obs_space[key] = space if self.joystick_policy.target_observable is not None: real_obs_space["target_obs"] = self.joystick_policy.target_observable.get_observation_spec() if not self.joystick_policy.target_yaw_provider.is_target_velocity_fixed(): real_obs_space["target_vel"] = gym.spaces.Box( low = 0.0, high = np.inf, shape=(1,) ) target_custom_data_spec = self.joystick_policy.target_yaw_provider.get_target_custom_data_observable_spec() if self.joystick_policy.enable_target_custom_obs and target_custom_data_spec is not None: real_obs_space["target_custom"] = target_custom_data_spec # Enforce order real_obs_space = OrderedDict(sorted(real_obs_space.items(), key=lambda t: t[0])) obs_space = gym.spaces.Dict(real_obs_space) return obs_space @property def joystick_policy(self) -> JoystickPolicy: return self._joystick_policy def set_joystick_policy(self, joystick_policy: JoystickPolicy): self._joystick_policy = joystick_policy @property def is_resetter_policy(self) -> bool: return False @property
def robot(self) -> BaseWalker:
2
2023-11-02 23:21:38+00:00
12k
UMass-Foundation-Model/genome
engine/viper/base_models/xvlm/xvlm.py
[ { "identifier": "VisionTransformer", "path": "engine/viper/base_models/xvlm/vit.py", "snippet": "class VisionTransformer(nn.Module):\n \"\"\" Vision Transformer\n A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` -\n https://arxiv.org/abs/2010...
import os import torch import torch.nn as nn import torch.nn.functional as F import torch.distributed as dist import json from functools import partial from engine.viper.base_models.xvlm.vit import VisionTransformer, interpolate_pos_embed from engine.viper.base_models.xvlm.swin_transformer import SwinTransformer, interpolate_relative_pos_embed from engine.viper.base_models.xvlm.xbert import BertConfig, BertForMaskedLM, BertModel
8,016
# Multi-Grained Vision Language Pre-Training: Aligning Texts with Visual Concepts (https://arxiv.org/abs/2111.08276) # Github: https://github.com/zengyan-97/X-VLM # Copyright (c) 2022, ByteDance Inc. # All rights reserved. def read_json(rpath): with open(rpath, 'r') as f: return json.load(f) class AllGather(torch.autograd.Function): """An autograd function that performs allgather on a tensor.""" @staticmethod def forward(ctx, tensor, rank, world_size): output = [torch.empty_like(tensor) for _ in range(world_size)] dist.all_gather(output, tensor) ctx.rank = rank ctx.batch_size = tensor.shape[0] return torch.cat(output, 0) @staticmethod def backward(ctx, grad_output): return ( grad_output[ctx.batch_size * ctx.rank: ctx.batch_size * (ctx.rank + 1)], None, None ) allgather = AllGather.apply def build_vision_encoder(vision_config, load_params=False): """ Args: load_params: False when building fine-tuning models """ vision_width = vision_config['vision_width']
# Multi-Grained Vision Language Pre-Training: Aligning Texts with Visual Concepts (https://arxiv.org/abs/2111.08276) # Github: https://github.com/zengyan-97/X-VLM # Copyright (c) 2022, ByteDance Inc. # All rights reserved. def read_json(rpath): with open(rpath, 'r') as f: return json.load(f) class AllGather(torch.autograd.Function): """An autograd function that performs allgather on a tensor.""" @staticmethod def forward(ctx, tensor, rank, world_size): output = [torch.empty_like(tensor) for _ in range(world_size)] dist.all_gather(output, tensor) ctx.rank = rank ctx.batch_size = tensor.shape[0] return torch.cat(output, 0) @staticmethod def backward(ctx, grad_output): return ( grad_output[ctx.batch_size * ctx.rank: ctx.batch_size * (ctx.rank + 1)], None, None ) allgather = AllGather.apply def build_vision_encoder(vision_config, load_params=False): """ Args: load_params: False when building fine-tuning models """ vision_width = vision_config['vision_width']
vision_encoder = SwinTransformer(img_size=vision_config['image_res'],
2
2023-11-01 16:39:33+00:00
12k
ml4bio/RhoFold
rhofold/model/structure_module.py
[ { "identifier": "Linear", "path": "rhofold/model/primitives.py", "snippet": "class Linear(nn.Linear):\n \"\"\"\n A Linear layer with built-in nonstandard initializations. Called just\n like torch.nn.Linear.\n\n Implements the initializers in 1.11.4, plus some additional ones found\n in th...
import math import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Sequence from rhofold.model.primitives import Linear, LayerNorm from rhofold.utils.rigid_utils import Rigid from rhofold.utils.tensor_utils import ( dict_multimap, permute_final_dims, flatten_final_dims, ) from einops import rearrange from rhofold.utils.alphabet import RNAAlphabet from rhofold.utils.converter import RNAConverter
9,729
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class RefineNet(nn.Module): """""" def __init__(self, dim = 64, is_pos_emb = True, n_layer = 4, enable = True, **kwargs): """Constructor function.""" super().__init__() self.is_pos_emb = is_pos_emb self.alphabet = RNAAlphabet.from_architecture('RNA') self.embed_tokens = nn.Embedding(len(self.alphabet), dim) self.enable = enable if self.is_pos_emb: self.embed_positions = PosEmbedding(4096, dim, self.alphabet.padding_idx) self.refine_layer0 = ResEGNN(corrections=n_layer, dims_in=dim) self.refine_layer1 = ResEGNN(corrections=n_layer, dims_in=dim) self.refine_layer2 = ResEGNN(corrections=n_layer, dims_in=dim) self.refine_layer3 = ResEGNN(corrections=n_layer, dims_in=dim) def forward(self, tokens, cords): """Perform the forward pass. Args: Returns: """ if not self.enable: return cords tokens = tokens[:, 0, :] tokens = tokens.unsqueeze(-1).repeat(1, 1, 23) b, l, n = tokens.shape cords = cords.reshape([b, l, n, 3]) fea = self.embed_tokens(tokens) b, l, n, _ = fea.shape if self.is_pos_emb: fea += self.embed_positions(tokens.reshape(b * l, n)).view(fea.size()) out = self.refine_layer0(fea.reshape([ b * l, n, -1]), cords.reshape([ b * l, n, -1]), is_fea = True) fea, cords = out[-1] fea = fea.reshape([b, l, n, -1]).transpose(1,2) cords = cords.reshape([b, l, n, -1]).transpose(1,2) out = self.refine_layer1(fea.reshape([ b * n, l, -1]), cords.reshape([ b * n, l, -1]), is_fea = True) fea, cords = out[-1] fea = fea.reshape([b, n, l, -1]).transpose(1,2) cords = cords.reshape([b, n, l, -1]).transpose(1,2) out = self.refine_layer2(fea.reshape([ b * l, n, -1]), cords.reshape([ b * l, n, -1]), is_fea = True) fea, cords = out[-1] fea = fea.reshape([b, l, n, -1]).transpose(1,2) cords = cords.reshape([b, l, n, -1]).transpose(1,2) out = self.refine_layer3(fea.reshape([ b * n, l, -1]), cords.reshape([ b * n, l, -1]), is_fea = True) fea, cords = out[-1] cords = cords.reshape([b, n, l, -1]).transpose(1,2) cords = cords.reshape([b, l * n, 3]) return cords class Swish_(torch.nn.Module): def forward(self, x): return x * x.sigmoid() SiLU = torch.nn.SiLU if hasattr(torch.nn, 'SiLU') else Swish_ class CoorsNorm(torch.nn.Module): def __init__(self, eps=1e-8): super().__init__() self.eps = eps
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class RefineNet(nn.Module): """""" def __init__(self, dim = 64, is_pos_emb = True, n_layer = 4, enable = True, **kwargs): """Constructor function.""" super().__init__() self.is_pos_emb = is_pos_emb self.alphabet = RNAAlphabet.from_architecture('RNA') self.embed_tokens = nn.Embedding(len(self.alphabet), dim) self.enable = enable if self.is_pos_emb: self.embed_positions = PosEmbedding(4096, dim, self.alphabet.padding_idx) self.refine_layer0 = ResEGNN(corrections=n_layer, dims_in=dim) self.refine_layer1 = ResEGNN(corrections=n_layer, dims_in=dim) self.refine_layer2 = ResEGNN(corrections=n_layer, dims_in=dim) self.refine_layer3 = ResEGNN(corrections=n_layer, dims_in=dim) def forward(self, tokens, cords): """Perform the forward pass. Args: Returns: """ if not self.enable: return cords tokens = tokens[:, 0, :] tokens = tokens.unsqueeze(-1).repeat(1, 1, 23) b, l, n = tokens.shape cords = cords.reshape([b, l, n, 3]) fea = self.embed_tokens(tokens) b, l, n, _ = fea.shape if self.is_pos_emb: fea += self.embed_positions(tokens.reshape(b * l, n)).view(fea.size()) out = self.refine_layer0(fea.reshape([ b * l, n, -1]), cords.reshape([ b * l, n, -1]), is_fea = True) fea, cords = out[-1] fea = fea.reshape([b, l, n, -1]).transpose(1,2) cords = cords.reshape([b, l, n, -1]).transpose(1,2) out = self.refine_layer1(fea.reshape([ b * n, l, -1]), cords.reshape([ b * n, l, -1]), is_fea = True) fea, cords = out[-1] fea = fea.reshape([b, n, l, -1]).transpose(1,2) cords = cords.reshape([b, n, l, -1]).transpose(1,2) out = self.refine_layer2(fea.reshape([ b * l, n, -1]), cords.reshape([ b * l, n, -1]), is_fea = True) fea, cords = out[-1] fea = fea.reshape([b, l, n, -1]).transpose(1,2) cords = cords.reshape([b, l, n, -1]).transpose(1,2) out = self.refine_layer3(fea.reshape([ b * n, l, -1]), cords.reshape([ b * n, l, -1]), is_fea = True) fea, cords = out[-1] cords = cords.reshape([b, n, l, -1]).transpose(1,2) cords = cords.reshape([b, l * n, 3]) return cords class Swish_(torch.nn.Module): def forward(self, x): return x * x.sigmoid() SiLU = torch.nn.SiLU if hasattr(torch.nn, 'SiLU') else Swish_ class CoorsNorm(torch.nn.Module): def __init__(self, eps=1e-8): super().__init__() self.eps = eps
self.fn = torch.nn.LayerNorm(1)
1
2023-11-01 10:29:08+00:00
12k
ziqi-zhang/TAOISM
python/tensor_loader.py
[ { "identifier": "str_hash", "path": "python/utils/basic_utils.py", "snippet": "def str_hash(s):\n return int(int(hashlib.sha224(s.encode('utf-8')).hexdigest(), 16) % ((1 << 62) - 1))" }, { "identifier": "EnclaveInterface", "path": "python/enclave_interfaces.py", "snippet": "class Encl...
from types import MethodType from pdb import set_trace as st from python.utils.basic_utils import str_hash from python.enclave_interfaces import EnclaveInterface, GlobalTensor from python.global_config import SecretConfig import torch
7,239
self.sid = -1 self.tensor_name_list = [] self.encryption_tensor_name_list = {} self.RandomVarName = None self.ShareVarName = None self.ShareTuple = None def init(self, start_enclave=True): if start_enclave: print("Initializing sid: %d" % self.sid) self.init_enclave() self.generate_tensor_name_list() # if hasattr(self, "LayerName") and self.LayerName == "Layer1.0.main.relu2": # st() self.init_enclave_tensors() self.init_cpu_tensor() self.init_encryption_tensor() def generate_tensor_name_list(self, force=False): return def link_tensors(self): pass def init_enclave_tensors(self): self.generate_tensor_name_list() for TensorName, shape, SeedList in self.tensor_name_list: if shape is None: raise ValueError("The shape is None. Please setup the shape before init_enclave_tensor") # print(f"TensorLoader init {TensorName}, {shape}") self.init_enclave_tensor(TensorName, shape) if SeedList is None: continue for seed in SeedList: self.set_seed(TensorName, seed) def set_cpu(self, name, t): # print("---", name, self.get_tag(name)) GlobalTensor.set_cpu(self.get_tag(name), t) def set_gpu(self, name, t): GlobalTensor.set_gpu(self.get_tag(name), t) def set_encryption(self, name, t): GlobalTensor.set_encryption(self.get_tag(name), t) def get_cpu(self, name): return GlobalTensor.get_cpu(self.get_tag(name)) def get_gpu(self, name): return GlobalTensor.get_gpu(self.get_tag(name)) def get_encryption(self, name): return GlobalTensor.get_encryption(self.get_tag(name)) def generate_cpu_tensor(self, name, shape): self.set_cpu(name, torch.zeros(shape).type(SecretConfig.dtypeForCpuOp)) # self.CpuTensors[name] = torch.zeros(shape).type(SecretConfig.dtypeForCpuOp) def transfer_cpu_to_gpu(self, name): self.set_gpu(name, self.get_cpu(name).cuda(non_blocking=True).type(SecretConfig.dtypeForCudaMm)) # self.GpuTensors[name] = self.CpuTensors[name].cuda(non_blocking=True).type(SecretConfig.dtypeForCudaMm) def transfer_gpu_to_cpu(self, name): cpu_tensor = self.get_cpu(name) gpu_tensor = self.get_gpu(name) cpu_tensor.copy_(gpu_tensor.type(SecretConfig.dtypeForCpuOp)) def transfer_enclave_to_cpu(self, name): self.from_enclave(name, self.get_cpu(name)) def transfer_cpu_to_enclave(self, name): self.set_tensor(name, self.get_cpu(name)) def init_cpu_tensor(self): self.generate_tensor_name_list() for TensorName, shape, _ in self.tensor_name_list: self.generate_cpu_tensor(TensorName, shape) def init_encryption_tensor(self): self.generate_tensor_name_list() for name, shape in self.encryption_tensor_name_list: GlobalTensor.init_encrypted_tensor(self.get_tag(name), shape) # self.EncrtyptedTensors[name] = self.CreateEncryptTorch(shape) def set_tensor_cpu_enclave(self, name, tensor): # GlobalTensor.SetNamedTensor(self.GetTag(tag), tensor) self.set_cpu(name, tensor) self.set_tensor(name, tensor) # print("Set cpu enclave: ", tensor[0,:10]) def set_tensor_cpu_gpu_enclave(self, name, tensor): # GlobalTensor.SetNamedTensor(self.GetTag(tag), tensor) self.set_cpu(name, tensor) self.set_tensor(name, tensor) self.set_gpu(name, tensor) # print("Set cpu enclave: ", tensor[0,:10]) def from_enclave(self, name, tensor): self.get_tensor(name, tensor) # def generate_enclave_tensor(self, name): # if name in self.RandomVarName: # return self.async_get_random(name, self.get_cpu(name)) # elif name in self.ShareVarName: # original, seed = self.ShareTuple[name] # return self.async_get_share(original, self.get_cpu(name), seed) # else: # raise Exception("Doesnt how to generate this tensor") def tensor_loader_factory(sid, tensor_loader_name): GlobalTensor.init() tensor_loader = TensorLoader() tensor_loader.Name = tensor_loader_name
class TensorLoader(EnclaveInterface): def __init__(self): super().__init__() self.sid = -1 self.tensor_name_list = [] self.encryption_tensor_name_list = {} self.RandomVarName = None self.ShareVarName = None self.ShareTuple = None def init(self, start_enclave=True): if start_enclave: print("Initializing sid: %d" % self.sid) self.init_enclave() self.generate_tensor_name_list() # if hasattr(self, "LayerName") and self.LayerName == "Layer1.0.main.relu2": # st() self.init_enclave_tensors() self.init_cpu_tensor() self.init_encryption_tensor() def generate_tensor_name_list(self, force=False): return def link_tensors(self): pass def init_enclave_tensors(self): self.generate_tensor_name_list() for TensorName, shape, SeedList in self.tensor_name_list: if shape is None: raise ValueError("The shape is None. Please setup the shape before init_enclave_tensor") # print(f"TensorLoader init {TensorName}, {shape}") self.init_enclave_tensor(TensorName, shape) if SeedList is None: continue for seed in SeedList: self.set_seed(TensorName, seed) def set_cpu(self, name, t): # print("---", name, self.get_tag(name)) GlobalTensor.set_cpu(self.get_tag(name), t) def set_gpu(self, name, t): GlobalTensor.set_gpu(self.get_tag(name), t) def set_encryption(self, name, t): GlobalTensor.set_encryption(self.get_tag(name), t) def get_cpu(self, name): return GlobalTensor.get_cpu(self.get_tag(name)) def get_gpu(self, name): return GlobalTensor.get_gpu(self.get_tag(name)) def get_encryption(self, name): return GlobalTensor.get_encryption(self.get_tag(name)) def generate_cpu_tensor(self, name, shape): self.set_cpu(name, torch.zeros(shape).type(SecretConfig.dtypeForCpuOp)) # self.CpuTensors[name] = torch.zeros(shape).type(SecretConfig.dtypeForCpuOp) def transfer_cpu_to_gpu(self, name): self.set_gpu(name, self.get_cpu(name).cuda(non_blocking=True).type(SecretConfig.dtypeForCudaMm)) # self.GpuTensors[name] = self.CpuTensors[name].cuda(non_blocking=True).type(SecretConfig.dtypeForCudaMm) def transfer_gpu_to_cpu(self, name): cpu_tensor = self.get_cpu(name) gpu_tensor = self.get_gpu(name) cpu_tensor.copy_(gpu_tensor.type(SecretConfig.dtypeForCpuOp)) def transfer_enclave_to_cpu(self, name): self.from_enclave(name, self.get_cpu(name)) def transfer_cpu_to_enclave(self, name): self.set_tensor(name, self.get_cpu(name)) def init_cpu_tensor(self): self.generate_tensor_name_list() for TensorName, shape, _ in self.tensor_name_list: self.generate_cpu_tensor(TensorName, shape) def init_encryption_tensor(self): self.generate_tensor_name_list() for name, shape in self.encryption_tensor_name_list: GlobalTensor.init_encrypted_tensor(self.get_tag(name), shape) # self.EncrtyptedTensors[name] = self.CreateEncryptTorch(shape) def set_tensor_cpu_enclave(self, name, tensor): # GlobalTensor.SetNamedTensor(self.GetTag(tag), tensor) self.set_cpu(name, tensor) self.set_tensor(name, tensor) # print("Set cpu enclave: ", tensor[0,:10]) def set_tensor_cpu_gpu_enclave(self, name, tensor): # GlobalTensor.SetNamedTensor(self.GetTag(tag), tensor) self.set_cpu(name, tensor) self.set_tensor(name, tensor) self.set_gpu(name, tensor) # print("Set cpu enclave: ", tensor[0,:10]) def from_enclave(self, name, tensor): self.get_tensor(name, tensor) # def generate_enclave_tensor(self, name): # if name in self.RandomVarName: # return self.async_get_random(name, self.get_cpu(name)) # elif name in self.ShareVarName: # original, seed = self.ShareTuple[name] # return self.async_get_share(original, self.get_cpu(name), seed) # else: # raise Exception("Doesnt how to generate this tensor") def tensor_loader_factory(sid, tensor_loader_name): GlobalTensor.init() tensor_loader = TensorLoader() tensor_loader.Name = tensor_loader_name
tensor_loader.LayerId = str_hash(tensor_loader.Name)
0
2023-11-01 10:37:37+00:00
12k
NVlabs/M2T2
m2t2/m2t2.py
[ { "identifier": "ActionDecoder", "path": "m2t2/action_decoder.py", "snippet": "class ActionDecoder(torch.nn.Module):\n def __init__(\n self, mask_dim, use_embed, embed_dim, max_num_pred, num_params,\n hidden_dim, num_layers, activation, offset_bins\n ):\n super(ActionDecoder, ...
import torch import torch.nn as nn from m2t2.action_decoder import ActionDecoder, infer_placements from m2t2.contact_decoder import ContactDecoder from m2t2.criterion import SetCriterion, GraspCriterion, PlaceCriterion from m2t2.matcher import HungarianMatcher from m2t2.pointnet2 import PointNet2MSG, PointNet2MSGCls
9,379
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # # Author: Wentao Yuan ''' Top-level M2T2 network. ''' class M2T2(nn.Module): def __init__( self, backbone: nn.Module, transformer: nn.Module, object_encoder: nn.Module = None, grasp_mlp: nn.Module = None, set_criterion: nn.Module = None, grasp_criterion: nn.Module = None, place_criterion: nn.Module = None ): super(M2T2, self).__init__() self.backbone = backbone self.object_encoder = object_encoder self.transformer = transformer self.grasp_mlp = grasp_mlp self.set_criterion = set_criterion self.grasp_criterion = grasp_criterion self.place_criterion = place_criterion @classmethod def from_config(cls, cfg): args = {} args['backbone'] = PointNet2MSG.from_config(cfg.scene_encoder) channels = args['backbone'].out_channels obj_channels = None if cfg.contact_decoder.num_place_queries > 0:
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # # Author: Wentao Yuan ''' Top-level M2T2 network. ''' class M2T2(nn.Module): def __init__( self, backbone: nn.Module, transformer: nn.Module, object_encoder: nn.Module = None, grasp_mlp: nn.Module = None, set_criterion: nn.Module = None, grasp_criterion: nn.Module = None, place_criterion: nn.Module = None ): super(M2T2, self).__init__() self.backbone = backbone self.object_encoder = object_encoder self.transformer = transformer self.grasp_mlp = grasp_mlp self.set_criterion = set_criterion self.grasp_criterion = grasp_criterion self.place_criterion = place_criterion @classmethod def from_config(cls, cfg): args = {} args['backbone'] = PointNet2MSG.from_config(cfg.scene_encoder) channels = args['backbone'].out_channels obj_channels = None if cfg.contact_decoder.num_place_queries > 0:
args['object_encoder'] = PointNet2MSGCls.from_config(
8
2023-11-03 22:32:05+00:00
12k
Codra-Ingenierie-Informatique/DataLab
cdl/core/computation/signal.py
[ { "identifier": "fit", "path": "cdl/algorithms/fit.py", "snippet": "class FitModel(abc.ABC):\nclass GaussianModel(FitModel):\nclass LorentzianModel(FitModel):\nclass VoigtModel(FitModel):\n def func(cls, x, amp, sigma, x0, y0):\n def get_amp_from_amplitude(\n cls, amplitude, sigma\n ): ...
import guidata.dataset as gds import numpy as np import scipy.integrate as spt import scipy.ndimage as spi import scipy.optimize as spo import scipy.signal as sps from cdl.algorithms import fit from cdl.algorithms.signal import ( derivative, interpolate, moving_average, normalize, peak_indexes, xpeak, xy_fft, xy_ifft, ) from cdl.config import _ from cdl.core.computation.base import ( ClipParam, FFTParam, GaussianParam, MovingAverageParam, MovingMedianParam, ThresholdParam, ) from cdl.core.model.signal import SignalObj
10,723
return dst def compute_division(src1: SignalObj, src2: SignalObj) -> SignalObj: """Compute division between two signals Args: src1 (SignalObj): source signal 1 src2 (SignalObj): source signal 2 Returns: SignalObj: result signal object """ dst = dst_n1n(src1, src2, "division") x1, y1 = src1.get_data() _x2, y2 = src2.get_data() dst.set_xydata(x1, y1 / np.array(y2, dtype=y1.dtype)) return dst # -------- compute_11 functions -------------------------------------------------------- # Functions with 1 input image and 1 output image # -------------------------------------------------------------------------------------- def extract_multiple_roi(src: SignalObj, group: gds.DataSetGroup) -> SignalObj: """Extract multiple regions of interest from data Args: src (SignalObj): source signal group (gds.DataSetGroup): group of parameters Returns: SignalObj: signal with multiple regions of interest """ suffix = None if len(group.datasets) == 1: p = group.datasets[0] suffix = f"indexes={p.col1:d}:{p.col2:d}" dst = dst_11(src, "extract_multiple_roi", suffix) x, y = src.get_data() xout, yout = np.ones_like(x) * np.nan, np.ones_like(y) * np.nan for p in group.datasets: slice0 = slice(p.col1, p.col2 + 1) xout[slice0], yout[slice0] = x[slice0], y[slice0] nans = np.isnan(xout) | np.isnan(yout) dst.set_xydata(xout[~nans], yout[~nans]) # TODO: [P2] Instead of removing geometric shapes, apply roi extract dst.remove_all_shapes() return dst def extract_single_roi(src: SignalObj, p: gds.DataSet) -> SignalObj: """Extract single region of interest from data Args: src (SignalObj): source signal p (gds.DataSet): parameters Returns: SignalObj: signal with single region of interest """ dst = dst_11(src, "extract_single_roi", f"indexes={p.col1:d}:{p.col2:d}") x, y = src.get_data() dst.set_xydata(x[p.col1 : p.col2 + 1], y[p.col1 : p.col2 + 1]) # TODO: [P2] Instead of removing geometric shapes, apply roi extract dst.remove_all_shapes() return dst def compute_swap_axes(src: SignalObj) -> SignalObj: """Swap axes Args: src (SignalObj): source signal Returns: SignalObj: result signal object """ dst = dst_11(src, "swap_axes") x, y = src.get_data() dst.set_xydata(y, x) return dst def compute_abs(src: SignalObj) -> SignalObj: """Compute absolute value Args: src (SignalObj): source signal Returns: SignalObj: result signal object """ dst = dst_11(src, "abs") x, y = src.get_data() dst.set_xydata(x, np.abs(y)) return dst def compute_re(src: SignalObj) -> SignalObj: """Compute real part Args: src (SignalObj): source signal Returns: SignalObj: result signal object """ dst = dst_11(src, "re") x, y = src.get_data() dst.set_xydata(x, np.real(y)) return dst def compute_im(src: SignalObj) -> SignalObj: """Compute imaginary part Args: src (SignalObj): source signal Returns: SignalObj: result signal object """ dst = dst_11(src, "im") x, y = src.get_data() dst.set_xydata(x, np.imag(y)) return dst class DataTypeSParam(gds.DataSet): """Convert signal data type parameters""" dtype_str = gds.ChoiceItem(
# -*- coding: utf-8 -*- # # Licensed under the terms of the BSD 3-Clause # (see cdl/LICENSE for details) """ .. Signal computation objects (see parent package :mod:`cdl.core.computation`) """ # pylint: disable=invalid-name # Allows short reference names like x, y, ... # Note: # ---- # All dataset classes must also be imported in the cdl.core.computation.param module. from __future__ import annotations VALID_DTYPES_STRLIST = SignalObj.get_valid_dtypenames() def dst_11(src: SignalObj, name: str, suffix: str | None = None) -> SignalObj: """Create result signal object for compute_11 function Args: src (SignalObj): source signal name (str): name of the function Returns: SignalObj: result signal object """ dst = src.copy(title=f"{name}({src.short_id})") if suffix is not None: dst.title += "|" + suffix return dst def dst_n1n(src1: SignalObj, src2: SignalObj, name: str, suffix: str | None = None): """Create result signal object for compute_n1n function Args: src1 (SignalObj): source signal 1 src2 (SignalObj): source signal 2 name (str): name of the function Returns: SignalObj: result signal object """ dst = src1.copy(title=f"{name}({src1.short_id}, {src2.short_id})") if suffix is not None: dst.title += "|" + suffix return dst # -------- compute_n1 functions -------------------------------------------------------- # Functions with N input signals and 1 output signal # -------------------------------------------------------------------------------------- # Those functions are perfoming a computation on N input signals and return a single # output signal. If we were only executing these functions locally, we would not need # to define them here, but since we are using the multiprocessing module, we need to # define them here so that they can be pickled and sent to the worker processes. # Also, we need to systematically return the output signal object, even if it is already # modified in place, because the multiprocessing module will not be able to retrieve # the modified object from the worker processes. def compute_add(dst: SignalObj, src: SignalObj) -> SignalObj: """Add signal to result signal Args: dst (SignalObj): destination signal src (SignalObj): source signal """ dst.y += np.array(src.y, dtype=dst.y.dtype) if dst.dy is not None: dst.dy = np.sqrt(dst.dy**2 + src.dy**2) return dst def compute_product(dst: SignalObj, src: SignalObj) -> SignalObj: """Multiply signal to result signal Args: dst (SignalObj): destination signal src (SignalObj): source signal """ dst.y *= np.array(src.y, dtype=dst.y.dtype) if dst.dy is not None: dst.dy = dst.y * np.sqrt((dst.dy / dst.y) ** 2 + (src.dy / src.y) ** 2) return dst # -------- compute_n1n functions ------------------------------------------------------- # Functions with N input images + 1 input image and N output images # -------------------------------------------------------------------------------------- def compute_difference(src1: SignalObj, src2: SignalObj) -> SignalObj: """Compute difference between two signals Args: src1 (SignalObj): source signal 1 src2 (SignalObj): source signal 2 Returns: SignalObj: result signal object """ dst = dst_n1n(src1, src2, "difference") dst.y = src1.y - src2.y if dst.dy is not None: dst.dy = np.sqrt(src1.dy**2 + src2.dy**2) return dst def compute_quadratic_difference(src1: SignalObj, src2: SignalObj) -> SignalObj: """Compute quadratic difference between two signals Args: src1 (SignalObj): source signal 1 src2 (SignalObj): source signal 2 Returns: SignalObj: result signal object """ dst = dst_n1n(src1, src2, "quadratic_difference") x1, y1 = src1.get_data() _x2, y2 = src2.get_data() dst.set_xydata(x1, (y1 - np.array(y2, dtype=y1.dtype)) / np.sqrt(2.0)) if np.issubdtype(dst.data.dtype, np.unsignedinteger): dst.data[src1.data < src2.data] = 0 if dst.dy is not None: dst.dy = np.sqrt(src1.dy**2 + src2.dy**2) return dst def compute_division(src1: SignalObj, src2: SignalObj) -> SignalObj: """Compute division between two signals Args: src1 (SignalObj): source signal 1 src2 (SignalObj): source signal 2 Returns: SignalObj: result signal object """ dst = dst_n1n(src1, src2, "division") x1, y1 = src1.get_data() _x2, y2 = src2.get_data() dst.set_xydata(x1, y1 / np.array(y2, dtype=y1.dtype)) return dst # -------- compute_11 functions -------------------------------------------------------- # Functions with 1 input image and 1 output image # -------------------------------------------------------------------------------------- def extract_multiple_roi(src: SignalObj, group: gds.DataSetGroup) -> SignalObj: """Extract multiple regions of interest from data Args: src (SignalObj): source signal group (gds.DataSetGroup): group of parameters Returns: SignalObj: signal with multiple regions of interest """ suffix = None if len(group.datasets) == 1: p = group.datasets[0] suffix = f"indexes={p.col1:d}:{p.col2:d}" dst = dst_11(src, "extract_multiple_roi", suffix) x, y = src.get_data() xout, yout = np.ones_like(x) * np.nan, np.ones_like(y) * np.nan for p in group.datasets: slice0 = slice(p.col1, p.col2 + 1) xout[slice0], yout[slice0] = x[slice0], y[slice0] nans = np.isnan(xout) | np.isnan(yout) dst.set_xydata(xout[~nans], yout[~nans]) # TODO: [P2] Instead of removing geometric shapes, apply roi extract dst.remove_all_shapes() return dst def extract_single_roi(src: SignalObj, p: gds.DataSet) -> SignalObj: """Extract single region of interest from data Args: src (SignalObj): source signal p (gds.DataSet): parameters Returns: SignalObj: signal with single region of interest """ dst = dst_11(src, "extract_single_roi", f"indexes={p.col1:d}:{p.col2:d}") x, y = src.get_data() dst.set_xydata(x[p.col1 : p.col2 + 1], y[p.col1 : p.col2 + 1]) # TODO: [P2] Instead of removing geometric shapes, apply roi extract dst.remove_all_shapes() return dst def compute_swap_axes(src: SignalObj) -> SignalObj: """Swap axes Args: src (SignalObj): source signal Returns: SignalObj: result signal object """ dst = dst_11(src, "swap_axes") x, y = src.get_data() dst.set_xydata(y, x) return dst def compute_abs(src: SignalObj) -> SignalObj: """Compute absolute value Args: src (SignalObj): source signal Returns: SignalObj: result signal object """ dst = dst_11(src, "abs") x, y = src.get_data() dst.set_xydata(x, np.abs(y)) return dst def compute_re(src: SignalObj) -> SignalObj: """Compute real part Args: src (SignalObj): source signal Returns: SignalObj: result signal object """ dst = dst_11(src, "re") x, y = src.get_data() dst.set_xydata(x, np.real(y)) return dst def compute_im(src: SignalObj) -> SignalObj: """Compute imaginary part Args: src (SignalObj): source signal Returns: SignalObj: result signal object """ dst = dst_11(src, "im") x, y = src.get_data() dst.set_xydata(x, np.imag(y)) return dst class DataTypeSParam(gds.DataSet): """Convert signal data type parameters""" dtype_str = gds.ChoiceItem(
_("Destination data type"),
9
2023-11-09 16:56:03+00:00
12k
choderalab/chiron
chiron/tests/test_pairs.py
[ { "identifier": "NeighborListNsqrd", "path": "chiron/neighbors.py", "snippet": "class NeighborListNsqrd(PairsBase):\n \"\"\"\n N^2 neighborlist implementation that returns the particle pair ids, displacement vectors, and distances.\n\n Parameters\n ----------\n space: Space\n Class...
import jax.numpy as jnp import pytest from chiron.neighbors import ( NeighborListNsqrd, PairList, OrthogonalPeriodicSpace, OrthogonalNonperiodicSpace, ) from chiron.states import SamplerState from openmm import unit
8,923
def test_orthogonal_periodic_displacement(): # test that the incorrect box shapes throw an exception with pytest.raises(ValueError): space = OrthogonalPeriodicSpace(jnp.array([10.0, 10.0, 10.0])) # test that incorrect units throw an exception with pytest.raises(ValueError): space = OrthogonalPeriodicSpace( unit.Quantity( jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]), unit.radians, ) ) space = OrthogonalPeriodicSpace( jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) ) # test that the box vectors are set correctly assert jnp.all( space.box_vectors == jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) ) # test that the box lengths for an orthogonal box are set correctly assert jnp.all(space._box_lengths == jnp.array([10.0, 10.0, 10.0])) # test calculation of the displacement_vector and distance between two points p1 = jnp.array([[0, 0, 0], [0, 0, 0]]) p2 = jnp.array([[1, 0, 0], [6, 0, 0]]) r_ij, distance = space.displacement(p1, p2) assert jnp.all(r_ij == jnp.array([[-1.0, 0.0, 0.0], [4.0, 0.0, 0.0]])) assert jnp.all(distance == jnp.array([1, 4])) # test that the periodic wrapping works as expected wrapped_x = space.wrap(jnp.array([11, 0, 0])) assert jnp.all(wrapped_x == jnp.array([1, 0, 0])) wrapped_x = space.wrap(jnp.array([-1, 0, 0])) assert jnp.all(wrapped_x == jnp.array([9, 0, 0])) wrapped_x = space.wrap(jnp.array([5, 0, 0])) assert jnp.all(wrapped_x == jnp.array([5, 0, 0])) wrapped_x = space.wrap(jnp.array([5, 12, -1])) assert jnp.all(wrapped_x == jnp.array([5, 2, 9])) # test the setter for the box vectors space.box_vectors = jnp.array( [[10.0, 0.0, 0.0], [0.0, 20.0, 0.0], [0.0, 0.0, 30.0]] ) assert jnp.all( space._box_vectors == jnp.array([[10.0, 0.0, 0.0], [0.0, 20.0, 0.0], [0.0, 0.0, 30.0]]) ) assert jnp.all(space._box_lengths == jnp.array([10.0, 20.0, 30.0])) def test_orthogonal_nonperiodic_displacement():
def test_orthogonal_periodic_displacement(): # test that the incorrect box shapes throw an exception with pytest.raises(ValueError): space = OrthogonalPeriodicSpace(jnp.array([10.0, 10.0, 10.0])) # test that incorrect units throw an exception with pytest.raises(ValueError): space = OrthogonalPeriodicSpace( unit.Quantity( jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]), unit.radians, ) ) space = OrthogonalPeriodicSpace( jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) ) # test that the box vectors are set correctly assert jnp.all( space.box_vectors == jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) ) # test that the box lengths for an orthogonal box are set correctly assert jnp.all(space._box_lengths == jnp.array([10.0, 10.0, 10.0])) # test calculation of the displacement_vector and distance between two points p1 = jnp.array([[0, 0, 0], [0, 0, 0]]) p2 = jnp.array([[1, 0, 0], [6, 0, 0]]) r_ij, distance = space.displacement(p1, p2) assert jnp.all(r_ij == jnp.array([[-1.0, 0.0, 0.0], [4.0, 0.0, 0.0]])) assert jnp.all(distance == jnp.array([1, 4])) # test that the periodic wrapping works as expected wrapped_x = space.wrap(jnp.array([11, 0, 0])) assert jnp.all(wrapped_x == jnp.array([1, 0, 0])) wrapped_x = space.wrap(jnp.array([-1, 0, 0])) assert jnp.all(wrapped_x == jnp.array([9, 0, 0])) wrapped_x = space.wrap(jnp.array([5, 0, 0])) assert jnp.all(wrapped_x == jnp.array([5, 0, 0])) wrapped_x = space.wrap(jnp.array([5, 12, -1])) assert jnp.all(wrapped_x == jnp.array([5, 2, 9])) # test the setter for the box vectors space.box_vectors = jnp.array( [[10.0, 0.0, 0.0], [0.0, 20.0, 0.0], [0.0, 0.0, 30.0]] ) assert jnp.all( space._box_vectors == jnp.array([[10.0, 0.0, 0.0], [0.0, 20.0, 0.0], [0.0, 0.0, 30.0]]) ) assert jnp.all(space._box_lengths == jnp.array([10.0, 20.0, 30.0])) def test_orthogonal_nonperiodic_displacement():
space = OrthogonalNonperiodicSpace(
3
2023-11-07 18:17:43+00:00
12k
Rishit-dagli/Astroformer
pytorch-image-models/timm/models/vision_transformer.py
[ { "identifier": "build_model_with_cfg", "path": "pytorch-image-models/timm/models/_builder.py", "snippet": "def build_model_with_cfg(\n model_cls: Callable,\n variant: str,\n pretrained: bool,\n pretrained_cfg: Optional[Dict] = None,\n pretrained_cfg_overlay: Optional[...
import logging import math import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint import numpy as np import re import re from collections import OrderedDict from functools import partial from typing import Callable, List, Optional, Sequence, Tuple, Type, Union from torch.jit import Final from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD, \ OPENAI_CLIP_MEAN, OPENAI_CLIP_STD from timm.layers import PatchEmbed, Mlp, DropPath, AttentionPoolLatent, RmsNorm, PatchDropout, SwiGLUPacked, \ trunc_normal_, lecun_normal_, resample_patch_embed, resample_abs_pos_embed, use_fused_attn, \ get_act_layer, get_norm_layer, LayerType from ._builder import build_model_with_cfg from ._manipulate import named_apply, checkpoint_seq, adapt_input_conv from ._registry import generate_default_cfgs, register_model, register_model_deprecations from timm.layers import get_act_layer
8,679
'vit_base_patch16_224.mae': _cfg( url='https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_base.pth', hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_large_patch16_224.mae': _cfg( url='https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_large.pth', hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_huge_patch14_224.mae': _cfg( url='https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_huge.pth', hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_huge_patch14_gap_224.in1k_ijepa': _cfg( url='https://dl.fbaipublicfiles.com/ijepa/IN1K-vit.h.14-300e.pth.tar', # hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_huge_patch14_gap_224.in22k_ijepa': _cfg( url='https://dl.fbaipublicfiles.com/ijepa/IN22K-vit.h.14-900e.pth.tar', # hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_huge_patch16_gap_448.in1k_ijepa': _cfg( url='https://dl.fbaipublicfiles.com/ijepa/IN1K-vit.h.16-448px-300e.pth.tar', # hf_hub_id='timm/', license='cc-by-nc-4.0', input_size=(3, 448, 448), crop_pct=1.0, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_giant_patch16_gap_224.in22k_ijepa': _cfg( url='https://dl.fbaipublicfiles.com/ijepa/IN22K-vit.g.16-600e.pth.tar', # hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_base_patch16_siglip_224.webli': _cfg( hf_hub_id='timm/ViT-B-16-SigLIP', hf_hub_filename='open_clip_pytorch_model.bin', num_classes=0), 'vit_base_patch16_siglip_256.webli': _cfg( hf_hub_id='timm/ViT-B-16-SigLIP-256', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 256, 256), num_classes=0), 'vit_base_patch16_siglip_384.webli': _cfg( hf_hub_id='timm/ViT-B-16-SigLIP-384', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 384, 384), num_classes=0), 'vit_base_patch16_siglip_512.webli': _cfg( hf_hub_id='timm/ViT-B-16-SigLIP-512', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 512, 512), num_classes=0), 'vit_large_patch16_siglip_256.webli': _cfg( hf_hub_id='timm/ViT-L-16-SigLIP-256', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 256, 256), num_classes=0), 'vit_large_patch16_siglip_384.webli': _cfg( hf_hub_id='timm/ViT-L-16-SigLIP-384', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 384, 384), num_classes=0), 'vit_so400m_patch14_siglip_224.webli': _cfg( hf_hub_id='timm/ViT-SO400M-14-SigLIP', hf_hub_filename='open_clip_pytorch_model.bin', num_classes=0), 'vit_so400m_patch14_siglip_384.webli': _cfg( hf_hub_id='timm/ViT-SO400M-14-SigLIP-384', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 384, 384), num_classes=0), 'vit_medium_patch16_reg4_256': _cfg( input_size=(3, 256, 256)), 'vit_medium_patch16_reg4_gap_256': _cfg( input_size=(3, 256, 256)), 'vit_base_patch16_reg8_gap_256': _cfg(input_size=(3, 256, 256)), } _quick_gelu_cfgs = [ 'vit_large_patch14_clip_224.dfn2b', 'vit_huge_patch14_clip_224.dfn5b', 'vit_huge_patch14_clip_378.dfn5b', 'vit_base_patch32_clip_224.metaclip_2pt5b', 'vit_base_patch16_clip_224.metaclip_2pt5b', 'vit_large_patch14_clip_224.metaclip_2pt5b', 'vit_huge_patch14_clip_224.metaclip_2pt5b', 'vit_base_patch32_clip_224.openai', 'vit_base_patch16_clip_224.openai', 'vit_large_patch14_clip_224.openai', 'vit_large_patch14_clip_336.openai', ] default_cfgs.update({ n.replace('_clip_', '_clip_quickgelu_'): default_cfgs[n] for n in _quick_gelu_cfgs }) default_cfgs = generate_default_cfgs(default_cfgs) def _create_vision_transformer(variant, pretrained=False, **kwargs): if kwargs.get('features_only', None): raise RuntimeError('features_only not implemented for Vision Transformer models.') if 'flexi' in variant: # FIXME Google FlexiViT pretrained models have a strong preference for bilinear patch / embed # interpolation, other pretrained models resize better w/ anti-aliased bicubic interpolation. _filter_fn = partial(checkpoint_filter_fn, interpolation='bilinear', antialias=False) else: _filter_fn = checkpoint_filter_fn # FIXME attn pool (currently only in siglip) params removed if pool disabled, is there a better soln? strict = True if 'siglip' in variant and kwargs.get('global_pool', None) != 'map': strict = False
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in: 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 `How to train your ViT? Data, Augmentation, and Regularization in Vision Transformers` - https://arxiv.org/abs/2106.10270 `FlexiViT: One Model for All Patch Sizes` - https://arxiv.org/abs/2212.08013 The official jax code is released and available at * https://github.com/google-research/vision_transformer * https://github.com/google-research/big_vision Acknowledgments: * The paper authors for releasing code and weights, thanks! * I fixed my class token impl based on Phil Wang's https://github.com/lucidrains/vit-pytorch * Simple transformer style inspired by Andrej Karpathy's https://github.com/karpathy/minGPT * Bert reference code checks against Huggingface Transformers and Tensorflow Bert Hacked together by / Copyright 2020, Ross Wightman """ __all__ = ['VisionTransformer'] # model_registry will add each entrypoint fn to this _logger = logging.getLogger(__name__) class Attention(nn.Module): fused_attn: Final[bool] def __init__( self, dim, num_heads=8, qkv_bias=False, qk_norm=False, attn_drop=0., proj_drop=0., norm_layer=nn.LayerNorm, ): super().__init__() assert dim % num_heads == 0, 'dim should be divisible by num_heads' self.num_heads = num_heads self.head_dim = dim // num_heads self.scale = self.head_dim ** -0.5 self.fused_attn = use_fused_attn() self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) q, k = self.q_norm(q), self.k_norm(k) if self.fused_attn: x = F.scaled_dot_product_attention( q, k, v, dropout_p=self.attn_drop.p if self.training else 0., ) else: q = q * self.scale attn = q @ k.transpose(-2, -1) attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = attn @ v x = x.transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class LayerScale(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): return x.mul_(self.gamma) if self.inplace else x * self.gamma class Block(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_norm=False, proj_drop=0., attn_drop=0., init_values=None, drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, mlp_layer=Mlp, ): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_norm=qk_norm, attn_drop=attn_drop, proj_drop=proj_drop, norm_layer=norm_layer, ) self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) self.mlp = mlp_layer( in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, drop=proj_drop, ) self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity() def forward(self, x): x = x + self.drop_path1(self.ls1(self.attn(self.norm1(x)))) x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x)))) return x class ResPostBlock(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_norm=False, proj_drop=0., attn_drop=0., init_values=None, drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, mlp_layer=Mlp, ): super().__init__() self.init_values = init_values self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_norm=qk_norm, attn_drop=attn_drop, proj_drop=proj_drop, norm_layer=norm_layer, ) self.norm1 = norm_layer(dim) self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.mlp = mlp_layer( in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, drop=proj_drop, ) self.norm2 = norm_layer(dim) self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.init_weights() def init_weights(self): # NOTE this init overrides that base model init with specific changes for the block type if self.init_values is not None: nn.init.constant_(self.norm1.weight, self.init_values) nn.init.constant_(self.norm2.weight, self.init_values) def forward(self, x): x = x + self.drop_path1(self.norm1(self.attn(x))) x = x + self.drop_path2(self.norm2(self.mlp(x))) return x class ParallelScalingBlock(nn.Module): """ Parallel ViT block (MLP & Attention in parallel) Based on: 'Scaling Vision Transformers to 22 Billion Parameters` - https://arxiv.org/abs/2302.05442 """ fused_attn: Final[bool] def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_norm=False, proj_drop=0., attn_drop=0., init_values=None, drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, mlp_layer=None, # NOTE: not used ): super().__init__() assert dim % num_heads == 0, 'dim should be divisible by num_heads' self.num_heads = num_heads self.head_dim = dim // num_heads self.scale = self.head_dim ** -0.5 self.fused_attn = use_fused_attn() mlp_hidden_dim = int(mlp_ratio * dim) in_proj_out_dim = mlp_hidden_dim + 3 * dim self.in_norm = norm_layer(dim) self.in_proj = nn.Linear(dim, in_proj_out_dim, bias=qkv_bias) self.in_split = [mlp_hidden_dim] + [dim] * 3 if qkv_bias: self.register_buffer('qkv_bias', None) self.register_parameter('mlp_bias', None) else: self.register_buffer('qkv_bias', torch.zeros(3 * dim), persistent=False) self.mlp_bias = nn.Parameter(torch.zeros(mlp_hidden_dim)) self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() self.attn_drop = nn.Dropout(attn_drop) self.attn_out_proj = nn.Linear(dim, dim) self.mlp_drop = nn.Dropout(proj_drop) self.mlp_act = act_layer() self.mlp_out_proj = nn.Linear(mlp_hidden_dim, dim) self.ls = LayerScale(dim, init_values=init_values) if init_values is not None else nn.Identity() self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() def forward(self, x): B, N, C = x.shape # Combined MLP fc1 & qkv projections y = self.in_norm(x) if self.mlp_bias is not None: # Concat constant zero-bias for qkv w/ trainable mlp_bias. # Appears faster than adding to x_mlp separately y = F.linear(y, self.in_proj.weight, torch.cat((self.qkv_bias, self.mlp_bias))) else: y = self.in_proj(y) x_mlp, q, k, v = torch.split(y, self.in_split, dim=-1) # Dot product attention w/ qk norm q = self.q_norm(q.view(B, N, self.num_heads, self.head_dim)).transpose(1, 2) k = self.k_norm(k.view(B, N, self.num_heads, self.head_dim)).transpose(1, 2) v = v.view(B, N, self.num_heads, self.head_dim).transpose(1, 2) if self.fused_attn: x_attn = F.scaled_dot_product_attention( q, k, v, dropout_p=self.attn_drop.p if self.training else 0., ) else: q = q * self.scale attn = q @ k.transpose(-2, -1) attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x_attn = attn @ v x_attn = x_attn.transpose(1, 2).reshape(B, N, C) x_attn = self.attn_out_proj(x_attn) # MLP activation, dropout, fc2 x_mlp = self.mlp_act(x_mlp) x_mlp = self.mlp_drop(x_mlp) x_mlp = self.mlp_out_proj(x_mlp) # Add residual w/ drop path & layer scale applied y = self.drop_path(self.ls(x_attn + x_mlp)) x = x + y return x class ParallelThingsBlock(nn.Module): """ Parallel ViT block (N parallel attention followed by N parallel MLP) Based on: `Three things everyone should know about Vision Transformers` - https://arxiv.org/abs/2203.09795 """ def __init__( self, dim, num_heads, num_parallel=2, mlp_ratio=4., qkv_bias=False, qk_norm=False, init_values=None, proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, mlp_layer=Mlp, ): super().__init__() self.num_parallel = num_parallel self.attns = nn.ModuleList() self.ffns = nn.ModuleList() for _ in range(num_parallel): self.attns.append(nn.Sequential(OrderedDict([ ('norm', norm_layer(dim)), ('attn', Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_norm=qk_norm, attn_drop=attn_drop, proj_drop=proj_drop, norm_layer=norm_layer, )), ('ls', LayerScale(dim, init_values=init_values) if init_values else nn.Identity()), ('drop_path', DropPath(drop_path) if drop_path > 0. else nn.Identity()) ]))) self.ffns.append(nn.Sequential(OrderedDict([ ('norm', norm_layer(dim)), ('mlp', mlp_layer( dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, drop=proj_drop, )), ('ls', LayerScale(dim, init_values=init_values) if init_values else nn.Identity()), ('drop_path', DropPath(drop_path) if drop_path > 0. else nn.Identity()) ]))) def _forward_jit(self, x): x = x + torch.stack([attn(x) for attn in self.attns]).sum(dim=0) x = x + torch.stack([ffn(x) for ffn in self.ffns]).sum(dim=0) return x @torch.jit.ignore def _forward(self, x): x = x + sum(attn(x) for attn in self.attns) x = x + sum(ffn(x) for ffn in self.ffns) return x def forward(self, x): if torch.jit.is_scripting() or torch.jit.is_tracing(): return self._forward_jit(x) else: return self._forward(x) class VisionTransformer(nn.Module): """ Vision Transformer A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` - https://arxiv.org/abs/2010.11929 """ dynamic_img_size: Final[bool] def __init__( self, img_size: Union[int, Tuple[int, int]] = 224, patch_size: Union[int, Tuple[int, int]] = 16, in_chans: int = 3, num_classes: int = 1000, global_pool: str = 'token', embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4., qkv_bias: bool = True, qk_norm: bool = False, init_values: Optional[float] = None, class_token: bool = True, no_embed_class: bool = False, reg_tokens: int = 0, pre_norm: bool = False, fc_norm: Optional[bool] = None, dynamic_img_size: bool = False, dynamic_img_pad: bool = False, drop_rate: float = 0., pos_drop_rate: float = 0., patch_drop_rate: float = 0., proj_drop_rate: float = 0., attn_drop_rate: float = 0., drop_path_rate: float = 0., weight_init: str = '', embed_layer: Callable = PatchEmbed, norm_layer: Optional[LayerType] = None, act_layer: Optional[LayerType] = None, block_fn: Type[nn.Module] = Block, mlp_layer: Type[nn.Module] = Mlp, ): """ Args: img_size: Input image size. patch_size: Patch size. in_chans: Number of image input channels. num_classes: Mumber of classes for classification head. global_pool: Type of global pooling for final sequence (default: 'token'). embed_dim: Transformer embedding dimension. depth: Depth of transformer. num_heads: Number of attention heads. mlp_ratio: Ratio of mlp hidden dim to embedding dim. qkv_bias: Enable bias for qkv projections if True. init_values: Layer-scale init values (layer-scale enabled if not None). class_token: Use class token. no_embed_class: Don't include position embeddings for class (or reg) tokens. reg_tokens: Number of register tokens. fc_norm: Pre head norm after pool (instead of before), if None, enabled when global_pool == 'avg'. drop_rate: Head dropout rate. pos_drop_rate: Position embedding dropout rate. attn_drop_rate: Attention dropout rate. drop_path_rate: Stochastic depth rate. weight_init: Weight initialization scheme. embed_layer: Patch embedding layer. norm_layer: Normalization layer. act_layer: MLP activation layer. block_fn: Transformer block layer. """ super().__init__() assert global_pool in ('', 'avg', 'token', 'map') assert class_token or global_pool != 'token' use_fc_norm = global_pool == 'avg' if fc_norm is None else fc_norm norm_layer = get_norm_layer(norm_layer) or partial(nn.LayerNorm, eps=1e-6) act_layer = get_act_layer(act_layer) or nn.GELU self.num_classes = num_classes self.global_pool = global_pool self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models self.num_prefix_tokens = 1 if class_token else 0 self.num_prefix_tokens += reg_tokens self.num_reg_tokens = reg_tokens self.has_class_token = class_token self.no_embed_class = no_embed_class # don't embed prefix positions (includes reg) self.dynamic_img_size = dynamic_img_size self.grad_checkpointing = False embed_args = {} if dynamic_img_size: # flatten deferred until after pos embed embed_args.update(dict(strict_img_size=False, output_fmt='NHWC')) self.patch_embed = embed_layer( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, bias=not pre_norm, # disable bias if pre-norm is used (e.g. CLIP) dynamic_img_pad=dynamic_img_pad, **embed_args, ) num_patches = self.patch_embed.num_patches self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if class_token else None self.reg_token = nn.Parameter(torch.zeros(1, reg_tokens, embed_dim)) if reg_tokens else None embed_len = num_patches if no_embed_class else num_patches + self.num_prefix_tokens self.pos_embed = nn.Parameter(torch.randn(1, embed_len, embed_dim) * .02) self.pos_drop = nn.Dropout(p=pos_drop_rate) if patch_drop_rate > 0: self.patch_drop = PatchDropout( patch_drop_rate, num_prefix_tokens=self.num_prefix_tokens, ) else: self.patch_drop = nn.Identity() self.norm_pre = norm_layer(embed_dim) if pre_norm else nn.Identity() dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule self.blocks = nn.Sequential(*[ block_fn( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_norm=qk_norm, init_values=init_values, proj_drop=proj_drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer, mlp_layer=mlp_layer, ) for i in range(depth)]) self.norm = norm_layer(embed_dim) if not use_fc_norm else nn.Identity() # Classifier Head if global_pool == 'map': self.attn_pool = AttentionPoolLatent( self.embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, norm_layer=norm_layer, ) else: self.attn_pool = None self.fc_norm = norm_layer(embed_dim) if use_fc_norm else nn.Identity() self.head_drop = nn.Dropout(drop_rate) self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() if weight_init != 'skip': self.init_weights(weight_init) def init_weights(self, mode=''): assert mode in ('jax', 'jax_nlhb', 'moco', '') head_bias = -math.log(self.num_classes) if 'nlhb' in mode else 0. trunc_normal_(self.pos_embed, std=.02) if self.cls_token is not None: nn.init.normal_(self.cls_token, std=1e-6) named_apply(get_init_weights_vit(mode, head_bias), self) def _init_weights(self, m): # this fn left here for compat with downstream users init_weights_vit_timm(m) @torch.jit.ignore() def load_pretrained(self, checkpoint_path, prefix=''): _load_weights(self, checkpoint_path, prefix) @torch.jit.ignore def no_weight_decay(self): return {'pos_embed', 'cls_token', 'dist_token'} @torch.jit.ignore def group_matcher(self, coarse=False): return dict( stem=r'^cls_token|pos_embed|patch_embed', # stem and embed blocks=[(r'^blocks\.(\d+)', None), (r'^norm', (99999,))] ) @torch.jit.ignore def set_grad_checkpointing(self, enable=True): self.grad_checkpointing = enable @torch.jit.ignore def get_classifier(self): return self.head def reset_classifier(self, num_classes: int, global_pool=None): self.num_classes = num_classes if global_pool is not None: assert global_pool in ('', 'avg', 'token', 'map') if global_pool == 'map' and self.attn_pool is None: assert False, "Cannot currently add attention pooling in reset_classifier()." elif global_pool != 'map ' and self.attn_pool is not None: self.attn_pool = None # remove attention pooling self.global_pool = global_pool self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() def _pos_embed(self, x): if self.dynamic_img_size: B, H, W, C = x.shape pos_embed = resample_abs_pos_embed( self.pos_embed, (H, W), num_prefix_tokens=0 if self.no_embed_class else self.num_prefix_tokens, ) x = x.view(B, -1, C) else: pos_embed = self.pos_embed to_cat = [] if self.cls_token is not None: to_cat.append(self.cls_token.expand(x.shape[0], -1, -1)) if self.reg_token is not None: to_cat.append(self.reg_token.expand(x.shape[0], -1, -1)) if self.no_embed_class: # deit-3, updated JAX (big vision) # position embedding does not overlap with class token, add then concat x = x + pos_embed if to_cat: x = torch.cat(to_cat + [x], dim=1) else: # original timm, JAX, and deit vit impl # pos_embed has entry for class token, concat then add if to_cat: x = torch.cat(to_cat + [x], dim=1) x = x + pos_embed return self.pos_drop(x) def _intermediate_layers( self, x: torch.Tensor, n: Union[int, Sequence] = 1, ): outputs, num_blocks = [], len(self.blocks) take_indices = set(range(num_blocks - n, num_blocks) if isinstance(n, int) else n) # forward pass x = self.patch_embed(x) x = self._pos_embed(x) x = self.patch_drop(x) x = self.norm_pre(x) for i, blk in enumerate(self.blocks): x = blk(x) if i in take_indices: outputs.append(x) return outputs def get_intermediate_layers( self, x: torch.Tensor, n: Union[int, Sequence] = 1, reshape: bool = False, return_prefix_tokens: bool = False, norm: bool = False, ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]: """ Intermediate layer accessor (NOTE: This is a WIP experiment). Inspired by DINO / DINOv2 interface """ # take last n blocks if n is an int, if in is a sequence, select by matching indices outputs = self._intermediate_layers(x, n) if norm: outputs = [self.norm(out) for out in outputs] prefix_tokens = [out[:, 0:self.num_prefix_tokens] for out in outputs] outputs = [out[:, self.num_prefix_tokens:] for out in outputs] if reshape: grid_size = self.patch_embed.grid_size outputs = [ out.reshape(x.shape[0], grid_size[0], grid_size[1], -1).permute(0, 3, 1, 2).contiguous() for out in outputs ] if return_prefix_tokens: return tuple(zip(outputs, prefix_tokens)) return tuple(outputs) def forward_features(self, x): x = self.patch_embed(x) x = self._pos_embed(x) x = self.patch_drop(x) x = self.norm_pre(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) x = self.norm(x) return x def forward_head(self, x, pre_logits: bool = False): if self.attn_pool is not None: x = self.attn_pool(x) elif self.global_pool == 'avg': x = x[:, self.num_prefix_tokens:].mean(dim=1) elif self.global_pool: x = x[:, 0] # class token x = self.fc_norm(x) x = self.head_drop(x) return x if pre_logits else self.head(x) def forward(self, x): x = self.forward_features(x) x = self.forward_head(x) return x def init_weights_vit_timm(module: nn.Module, name: str = ''): """ ViT weight initialization, original timm impl (for reproducibility) """ if isinstance(module, nn.Linear): trunc_normal_(module.weight, std=.02) if module.bias is not None: nn.init.zeros_(module.bias) elif hasattr(module, 'init_weights'): module.init_weights() def init_weights_vit_jax(module: nn.Module, name: str = '', head_bias: float = 0.): """ ViT weight initialization, matching JAX (Flax) impl """ if isinstance(module, nn.Linear): if name.startswith('head'): nn.init.zeros_(module.weight) nn.init.constant_(module.bias, head_bias) else: nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.normal_(module.bias, std=1e-6) if 'mlp' in name else nn.init.zeros_(module.bias) elif isinstance(module, nn.Conv2d): lecun_normal_(module.weight) if module.bias is not None: nn.init.zeros_(module.bias) elif hasattr(module, 'init_weights'): module.init_weights() def init_weights_vit_moco(module: nn.Module, name: str = ''): """ ViT weight initialization, matching moco-v3 impl minus fixed PatchEmbed """ if isinstance(module, nn.Linear): if 'qkv' in name: # treat the weights of Q, K, V separately val = math.sqrt(6. / float(module.weight.shape[0] // 3 + module.weight.shape[1])) nn.init.uniform_(module.weight, -val, val) else: nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.zeros_(module.bias) elif hasattr(module, 'init_weights'): module.init_weights() def get_init_weights_vit(mode='jax', head_bias: float = 0.): if 'jax' in mode: return partial(init_weights_vit_jax, head_bias=head_bias) elif 'moco' in mode: return init_weights_vit_moco else: return init_weights_vit_timm def resize_pos_embed( posemb, posemb_new, num_prefix_tokens=1, gs_new=(), interpolation='bicubic', antialias=False, ): """ Rescale the grid of position embeddings when loading from state_dict. *DEPRECATED* This function is being deprecated in favour of resample_abs_pos_embed Adapted from: https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224 """ ntok_new = posemb_new.shape[1] if num_prefix_tokens: posemb_prefix, posemb_grid = posemb[:, :num_prefix_tokens], posemb[0, num_prefix_tokens:] ntok_new -= num_prefix_tokens else: posemb_prefix, posemb_grid = posemb[:, :0], posemb[0] gs_old = int(math.sqrt(len(posemb_grid))) if not len(gs_new): # backwards compatibility gs_new = [int(math.sqrt(ntok_new))] * 2 assert len(gs_new) >= 2 _logger.info(f'Resized position embedding: {posemb.shape} ({[gs_old, gs_old]}) to {posemb_new.shape} ({gs_new}).') posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2) posemb_grid = F.interpolate(posemb_grid, size=gs_new, mode=interpolation, antialias=antialias, align_corners=False) posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_new[0] * gs_new[1], -1) posemb = torch.cat([posemb_prefix, posemb_grid], dim=1) return posemb @torch.no_grad() def _load_weights(model: VisionTransformer, checkpoint_path: str, prefix: str = ''): """ Load weights from .npz checkpoints for official Google Brain Flax implementation """ def _n2p(w, t=True): if w.ndim == 4 and w.shape[0] == w.shape[1] == w.shape[2] == 1: w = w.flatten() if t: if w.ndim == 4: w = w.transpose([3, 2, 0, 1]) elif w.ndim == 3: w = w.transpose([2, 0, 1]) elif w.ndim == 2: w = w.transpose([1, 0]) return torch.from_numpy(w) w = np.load(checkpoint_path) interpolation = 'bilinear' antialias = False big_vision = False if not prefix: if 'opt/target/embedding/kernel' in w: prefix = 'opt/target/' elif 'params/embedding/kernel' in w: prefix = 'params/' big_vision = True elif 'params/img/embedding/kernel' in w: prefix = 'params/img/' big_vision = True if hasattr(model.patch_embed, 'backbone'): # hybrid backbone = model.patch_embed.backbone stem_only = not hasattr(backbone, 'stem') stem = backbone if stem_only else backbone.stem stem.conv.weight.copy_(adapt_input_conv(stem.conv.weight.shape[1], _n2p(w[f'{prefix}conv_root/kernel']))) stem.norm.weight.copy_(_n2p(w[f'{prefix}gn_root/scale'])) stem.norm.bias.copy_(_n2p(w[f'{prefix}gn_root/bias'])) if not stem_only: for i, stage in enumerate(backbone.stages): for j, block in enumerate(stage.blocks): bp = f'{prefix}block{i + 1}/unit{j + 1}/' for r in range(3): getattr(block, f'conv{r + 1}').weight.copy_(_n2p(w[f'{bp}conv{r + 1}/kernel'])) getattr(block, f'norm{r + 1}').weight.copy_(_n2p(w[f'{bp}gn{r + 1}/scale'])) getattr(block, f'norm{r + 1}').bias.copy_(_n2p(w[f'{bp}gn{r + 1}/bias'])) if block.downsample is not None: block.downsample.conv.weight.copy_(_n2p(w[f'{bp}conv_proj/kernel'])) block.downsample.norm.weight.copy_(_n2p(w[f'{bp}gn_proj/scale'])) block.downsample.norm.bias.copy_(_n2p(w[f'{bp}gn_proj/bias'])) embed_conv_w = _n2p(w[f'{prefix}embedding/kernel']) else: embed_conv_w = adapt_input_conv( model.patch_embed.proj.weight.shape[1], _n2p(w[f'{prefix}embedding/kernel'])) if embed_conv_w.shape[-2:] != model.patch_embed.proj.weight.shape[-2:]: embed_conv_w = resample_patch_embed( embed_conv_w, model.patch_embed.proj.weight.shape[-2:], interpolation=interpolation, antialias=antialias, verbose=True, ) model.patch_embed.proj.weight.copy_(embed_conv_w) model.patch_embed.proj.bias.copy_(_n2p(w[f'{prefix}embedding/bias'])) if model.cls_token is not None: model.cls_token.copy_(_n2p(w[f'{prefix}cls'], t=False)) if big_vision: pos_embed_w = _n2p(w[f'{prefix}pos_embedding'], t=False) else: pos_embed_w = _n2p(w[f'{prefix}Transformer/posembed_input/pos_embedding'], t=False) if pos_embed_w.shape != model.pos_embed.shape: old_shape = pos_embed_w.shape num_prefix_tokens = 0 if getattr(model, 'no_embed_class', False) else getattr(model, 'num_prefix_tokens', 1) pos_embed_w = resample_abs_pos_embed( # resize pos embedding when different size from pretrained weights pos_embed_w, new_size=model.patch_embed.grid_size, num_prefix_tokens=num_prefix_tokens, interpolation=interpolation, antialias=antialias, verbose=True, ) model.pos_embed.copy_(pos_embed_w) model.norm.weight.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/scale'])) model.norm.bias.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/bias'])) if (isinstance(model.head, nn.Linear) and f'{prefix}head/bias' in w and model.head.bias.shape[0] == w[f'{prefix}head/bias'].shape[-1]): model.head.weight.copy_(_n2p(w[f'{prefix}head/kernel'])) model.head.bias.copy_(_n2p(w[f'{prefix}head/bias'])) # NOTE representation layer has been removed, not used in latest 21k/1k pretrained weights # if isinstance(getattr(model.pre_logits, 'fc', None), nn.Linear) and f'{prefix}pre_logits/bias' in w: # model.pre_logits.fc.weight.copy_(_n2p(w[f'{prefix}pre_logits/kernel'])) # model.pre_logits.fc.bias.copy_(_n2p(w[f'{prefix}pre_logits/bias'])) if model.attn_pool is not None: block_prefix = f'{prefix}MAPHead_0/' mha_prefix = block_prefix + f'MultiHeadDotProductAttention_0/' model.attn_pool.latent.copy_(_n2p(w[f'{block_prefix}probe'], t=False)) model.attn_pool.kv.weight.copy_(torch.cat([ _n2p(w[f'{mha_prefix}{n}/kernel'], t=False).flatten(1).T for n in ('key', 'value')])) model.attn_pool.kv.bias.copy_(torch.cat([ _n2p(w[f'{mha_prefix}{n}/bias'], t=False).reshape(-1) for n in ('key', 'value')])) model.attn_pool.q.weight.copy_(_n2p(w[f'{mha_prefix}query/kernel'], t=False).flatten(1).T) model.attn_pool.q.bias.copy_(_n2p(w[f'{mha_prefix}query/bias'], t=False).reshape(-1)) model.attn_pool.proj.weight.copy_(_n2p(w[f'{mha_prefix}out/kernel']).flatten(1)) model.attn_pool.proj.bias.copy_(_n2p(w[f'{mha_prefix}out/bias'])) model.attn_pool.norm.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/scale'])) model.attn_pool.norm.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/bias'])) for r in range(2): getattr(model.attn_pool.mlp, f'fc{r + 1}').weight.copy_(_n2p(w[f'{block_prefix}MlpBlock_0/Dense_{r}/kernel'])) getattr(model.attn_pool.mlp, f'fc{r + 1}').bias.copy_(_n2p(w[f'{block_prefix}MlpBlock_0/Dense_{r}/bias'])) mha_sub, b_sub, ln1_sub = (0, 0, 1) if big_vision else (1, 3, 2) for i, block in enumerate(model.blocks.children()): block_prefix = f'{prefix}Transformer/encoderblock_{i}/' mha_prefix = block_prefix + f'MultiHeadDotProductAttention_{mha_sub}/' block.norm1.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/scale'])) block.norm1.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/bias'])) block.attn.qkv.weight.copy_(torch.cat([ _n2p(w[f'{mha_prefix}{n}/kernel'], t=False).flatten(1).T for n in ('query', 'key', 'value')])) block.attn.qkv.bias.copy_(torch.cat([ _n2p(w[f'{mha_prefix}{n}/bias'], t=False).reshape(-1) for n in ('query', 'key', 'value')])) block.attn.proj.weight.copy_(_n2p(w[f'{mha_prefix}out/kernel']).flatten(1)) block.attn.proj.bias.copy_(_n2p(w[f'{mha_prefix}out/bias'])) block.norm2.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_{ln1_sub}/scale'])) block.norm2.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_{ln1_sub}/bias'])) for r in range(2): getattr(block.mlp, f'fc{r + 1}').weight.copy_(_n2p(w[f'{block_prefix}MlpBlock_{b_sub}/Dense_{r}/kernel'])) getattr(block.mlp, f'fc{r + 1}').bias.copy_(_n2p(w[f'{block_prefix}MlpBlock_{b_sub}/Dense_{r}/bias'])) def _convert_openai_clip(state_dict, model, prefix='visual.'): out_dict = {} swaps = [ ('conv1', 'patch_embed.proj'), ('positional_embedding', 'pos_embed'), ('transformer.resblocks.', 'blocks.'), ('ln_pre', 'norm_pre'), ('ln_post', 'norm'), ('ln_', 'norm'), ('in_proj_', 'qkv.'), ('out_proj', 'proj'), ('mlp.c_fc', 'mlp.fc1'), ('mlp.c_proj', 'mlp.fc2'), ] for k, v in state_dict.items(): if not k.startswith(prefix): continue k = k.replace(prefix, '') for sp in swaps: k = k.replace(sp[0], sp[1]) if k == 'proj': k = 'head.weight' v = v.transpose(0, 1) out_dict['head.bias'] = torch.zeros(v.shape[0]) elif k == 'class_embedding': k = 'cls_token' v = v.unsqueeze(0).unsqueeze(1) elif k == 'pos_embed': v = v.unsqueeze(0) if v.shape[1] != model.pos_embed.shape[1]: # To resize pos embedding when using model at different size from pretrained weights v = resize_pos_embed( v, model.pos_embed, 0 if getattr(model, 'no_embed_class') else getattr(model, 'num_prefix_tokens', 1), model.patch_embed.grid_size ) out_dict[k] = v return out_dict def _convert_dinov2(state_dict, model): out_dict = {} state_dict.pop("mask_token", None) if 'register_tokens' in state_dict: # convert dinov2 w/ registers to no_embed_class timm model (neither cls or reg tokens overlap pos embed) out_dict['reg_token'] = state_dict.pop('register_tokens') out_dict['cls_token'] = state_dict.pop('cls_token') + state_dict['pos_embed'][:, 0] out_dict['pos_embed'] = state_dict.pop('pos_embed')[:, 1:] for k, v in state_dict.items(): if re.match(r"blocks\.(\d+)\.mlp\.w12\.(?:weight|bias)", k): out_dict[k.replace("w12", "fc1")] = v continue elif re.match(r"blocks\.(\d+)\.mlp\.w3\.(?:weight|bias)", k): out_dict[k.replace("w3", "fc2")] = v continue out_dict[k] = v return out_dict def checkpoint_filter_fn( state_dict, model, adapt_layer_scale=False, interpolation='bicubic', antialias=True, ): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} state_dict = state_dict.get('model', state_dict) state_dict = state_dict.get('state_dict', state_dict) prefix = '' if 'visual.class_embedding' in state_dict: return _convert_openai_clip(state_dict, model) elif 'module.visual.class_embedding' in state_dict: return _convert_openai_clip(state_dict, model, prefix='module.visual.') if "mask_token" in state_dict: state_dict = _convert_dinov2(state_dict, model) if "encoder" in state_dict: state_dict = state_dict['encoder'] prefix = 'module.' if 'visual.trunk.pos_embed' in state_dict: # convert an OpenCLIP model with timm vision encoder # FIXME remap final nn.Linear if it exists outside of the timm .trunk (ie in visual.head.proj) prefix = 'visual.trunk.' if prefix: # filter on & remove prefix string from keys state_dict = {k[len(prefix):]: v for k, v in state_dict.items() if k.startswith(prefix)} for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k: O, I, H, W = model.patch_embed.proj.weight.shape if len(v.shape) < 4: # For old models that I trained prior to conv based patchification O, I, H, W = model.patch_embed.proj.weight.shape v = v.reshape(O, -1, H, W) if v.shape[-1] != W or v.shape[-2] != H: v = resample_patch_embed( v, (H, W), interpolation=interpolation, antialias=antialias, verbose=True, ) elif k == 'pos_embed' and v.shape[1] != model.pos_embed.shape[1]: # To resize pos embedding when using model at different size from pretrained weights num_prefix_tokens = 0 if getattr(model, 'no_embed_class', False) else getattr(model, 'num_prefix_tokens', 1) v = resample_abs_pos_embed( v, new_size=model.patch_embed.grid_size, num_prefix_tokens=num_prefix_tokens, interpolation=interpolation, antialias=antialias, verbose=True, ) elif adapt_layer_scale and 'gamma_' in k: # remap layer-scale gamma into sub-module (deit3 models) k = re.sub(r'gamma_([0-9])', r'ls\1.gamma', k) elif 'pre_logits' in k: # NOTE representation layer removed as not used in latest 21k/1k pretrained weights continue out_dict[k] = v return out_dict def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'crop_pct': .9, 'interpolation': 'bicubic', 'fixed_input_size': True, 'mean': IMAGENET_INCEPTION_MEAN, 'std': IMAGENET_INCEPTION_STD, 'first_conv': 'patch_embed.proj', 'classifier': 'head', **kwargs } default_cfgs = { # re-finetuned augreg 21k FT on in1k weights 'vit_base_patch16_224.augreg2_in21k_ft_in1k': _cfg( hf_hub_id='timm/'), 'vit_base_patch16_384.augreg2_in21k_ft_in1k': _cfg(), 'vit_base_patch8_224.augreg2_in21k_ft_in1k': _cfg( hf_hub_id='timm/'), # How to train your ViT (augreg) weights, pretrained on 21k FT on in1k 'vit_tiny_patch16_224.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz', hf_hub_id='timm/', custom_load=True), 'vit_tiny_patch16_384.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', hf_hub_id='timm/', custom_load=True, input_size=(3, 384, 384), crop_pct=1.0), 'vit_small_patch32_224.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz', hf_hub_id='timm/', custom_load=True), 'vit_small_patch32_384.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', hf_hub_id='timm/', custom_load=True, input_size=(3, 384, 384), crop_pct=1.0), 'vit_small_patch16_224.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz', hf_hub_id='timm/', custom_load=True), 'vit_small_patch16_384.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', hf_hub_id='timm/', custom_load=True, input_size=(3, 384, 384), crop_pct=1.0), 'vit_base_patch32_224.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_32-i21k-300ep-lr_0.001-aug_medium1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz', hf_hub_id='timm/', custom_load=True), 'vit_base_patch32_384.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_32-i21k-300ep-lr_0.001-aug_light1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', hf_hub_id='timm/', custom_load=True, input_size=(3, 384, 384), crop_pct=1.0), 'vit_base_patch16_224.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.01-res_224.npz', hf_hub_id='timm/', custom_load=True), 'vit_base_patch16_384.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.01-res_384.npz', hf_hub_id='timm/', custom_load=True, input_size=(3, 384, 384), crop_pct=1.0), 'vit_base_patch8_224.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_8-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.01-res_224.npz', hf_hub_id='timm/', custom_load=True), 'vit_large_patch16_224.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_224.npz', hf_hub_id='timm/', custom_load=True), 'vit_large_patch16_384.augreg_in21k_ft_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_384.npz', hf_hub_id='timm/', custom_load=True, input_size=(3, 384, 384), crop_pct=1.0), # patch models (weights from official Google JAX impl) pretrained on in21k FT on in1k 'vit_base_patch16_224.orig_in21k_ft_in1k': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p16_224-80ecf9dd.pth', hf_hub_id='timm/'), 'vit_base_patch16_384.orig_in21k_ft_in1k': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p16_384-83fb41ba.pth', hf_hub_id='timm/', input_size=(3, 384, 384), crop_pct=1.0), 'vit_large_patch32_384.orig_in21k_ft_in1k': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p32_384-9b920ba8.pth', hf_hub_id='timm/', input_size=(3, 384, 384), crop_pct=1.0), # How to train your ViT (augreg) weights trained on in1k only 'vit_small_patch16_224.augreg_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_16-i1k-300ep-lr_0.001-aug_medium2-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.01-res_224.npz', hf_hub_id='timm/', custom_load=True), 'vit_small_patch16_384.augreg_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_16-i1k-300ep-lr_0.001-aug_medium2-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.01-res_384.npz', hf_hub_id='timm/', custom_load=True, input_size=(3, 384, 384), crop_pct=1.0), 'vit_base_patch32_224.augreg_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_32-i1k-300ep-lr_0.001-aug_medium2-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_224.npz', hf_hub_id='timm/', custom_load=True), 'vit_base_patch32_384.augreg_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_32-i1k-300ep-lr_0.001-aug_medium2-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_384.npz', hf_hub_id='timm/', custom_load=True, input_size=(3, 384, 384), crop_pct=1.0), 'vit_base_patch16_224.augreg_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_16-i1k-300ep-lr_0.001-aug_strong2-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_224.npz', hf_hub_id='timm/', custom_load=True), 'vit_base_patch16_384.augreg_in1k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_16-i1k-300ep-lr_0.001-aug_strong2-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_384.npz', hf_hub_id='timm/', custom_load=True, input_size=(3, 384, 384), crop_pct=1.0), 'vit_large_patch14_224.untrained': _cfg(url=''), 'vit_huge_patch14_224.untrained': _cfg(url=''), 'vit_giant_patch14_224.untrained': _cfg(url=''), 'vit_gigantic_patch14_224.untrained': _cfg(url=''), # patch models, imagenet21k (weights from official Google JAX impl) 'vit_large_patch32_224.orig_in21k': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_patch32_224_in21k-9046d2e7.pth', hf_hub_id='timm/', num_classes=21843), 'vit_huge_patch14_224.orig_in21k': _cfg( url='https://storage.googleapis.com/vit_models/imagenet21k/ViT-H_14.npz', hf_hub_id='timm/', custom_load=True, num_classes=21843), # How to train your ViT (augreg) weights, pretrained on in21k 'vit_tiny_patch16_224.augreg_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0.npz', hf_hub_id='timm/', custom_load=True, num_classes=21843), 'vit_small_patch32_224.augreg_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0.npz', hf_hub_id='timm/', custom_load=True, num_classes=21843), 'vit_small_patch16_224.augreg_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0.npz', hf_hub_id='timm/', custom_load=True, num_classes=21843), 'vit_base_patch32_224.augreg_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_32-i21k-300ep-lr_0.001-aug_medium1-wd_0.03-do_0.0-sd_0.0.npz', hf_hub_id='timm/', custom_load=True, num_classes=21843), 'vit_base_patch16_224.augreg_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0.npz', hf_hub_id='timm/', custom_load=True, num_classes=21843), 'vit_base_patch8_224.augreg_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_8-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0.npz', hf_hub_id='timm/', custom_load=True, num_classes=21843), 'vit_large_patch16_224.augreg_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1.npz', hf_hub_id='timm/', custom_load=True, num_classes=21843), # SAM trained models (https://arxiv.org/abs/2106.01548) 'vit_base_patch32_224.sam_in1k': _cfg( url='https://storage.googleapis.com/vit_models/sam/ViT-B_32.npz', custom_load=True, hf_hub_id='timm/'), 'vit_base_patch16_224.sam_in1k': _cfg( url='https://storage.googleapis.com/vit_models/sam/ViT-B_16.npz', custom_load=True, hf_hub_id='timm/'), # DINO pretrained - https://arxiv.org/abs/2104.14294 (no classifier head, for fine-tune only) 'vit_small_patch16_224.dino': _cfg( url='https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth', hf_hub_id='timm/', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_small_patch8_224.dino': _cfg( url='https://dl.fbaipublicfiles.com/dino/dino_deitsmall8_pretrain/dino_deitsmall8_pretrain.pth', hf_hub_id='timm/', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_base_patch16_224.dino': _cfg( url='https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth', hf_hub_id='timm/', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_base_patch8_224.dino': _cfg( url='https://dl.fbaipublicfiles.com/dino/dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth', hf_hub_id='timm/', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), # DINOv2 pretrained - https://arxiv.org/abs/2304.07193 (no classifier head, for fine-tune/features only) 'vit_small_patch14_dinov2.lvd142m': _cfg( url='https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_pretrain.pth', hf_hub_id='timm/', license='apache-2.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0, input_size=(3, 518, 518), crop_pct=1.0), 'vit_base_patch14_dinov2.lvd142m': _cfg( url='https://dl.fbaipublicfiles.com/dinov2/dinov2_vitb14/dinov2_vitb14_pretrain.pth', hf_hub_id='timm/', license='apache-2.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0, input_size=(3, 518, 518), crop_pct=1.0), 'vit_large_patch14_dinov2.lvd142m': _cfg( url='https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_pretrain.pth', hf_hub_id='timm/', license='apache-2.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0, input_size=(3, 518, 518), crop_pct=1.0), 'vit_giant_patch14_dinov2.lvd142m': _cfg( url='https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_pretrain.pth', hf_hub_id='timm/', license='apache-2.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0, input_size=(3, 518, 518), crop_pct=1.0), # DINOv2 pretrained w/ registers - https://arxiv.org/abs/2309.16588 (no classifier head, for fine-tune/features only) 'vit_small_patch14_reg4_dinov2.lvd142m': _cfg( url='https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_reg4_pretrain.pth', hf_hub_id='timm/', license='apache-2.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0, input_size=(3, 518, 518), crop_pct=1.0), 'vit_base_patch14_reg4_dinov2.lvd142m': _cfg( url='https://dl.fbaipublicfiles.com/dinov2/dinov2_vitb14/dinov2_vitb14_reg4_pretrain.pth', hf_hub_id='timm/', license='apache-2.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0, input_size=(3, 518, 518), crop_pct=1.0), 'vit_large_patch14_reg4_dinov2.lvd142m': _cfg( url='https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_reg4_pretrain.pth', hf_hub_id='timm/', license='apache-2.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0, input_size=(3, 518, 518), crop_pct=1.0), 'vit_giant_patch14_reg4_dinov2.lvd142m': _cfg( url='https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_reg4_pretrain.pth', hf_hub_id='timm/', license='apache-2.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0, input_size=(3, 518, 518), crop_pct=1.0), # ViT ImageNet-21K-P pretraining by MILL 'vit_base_patch16_224_miil.in21k': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/vit_base_patch16_224_in21k_miil-887286df.pth', hf_hub_id='timm/', mean=(0., 0., 0.), std=(1., 1., 1.), crop_pct=0.875, interpolation='bilinear', num_classes=11221), 'vit_base_patch16_224_miil.in21k_ft_in1k': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tresnet/vit_base_patch16_224_1k_miil_84_4-2deb18e3.pth', hf_hub_id='timm/', mean=(0., 0., 0.), std=(1., 1., 1.), crop_pct=0.875, interpolation='bilinear'), # Custom timm variants 'vit_base_patch16_rpn_224.sw_in1k': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-tpu-weights/vit_base_patch16_rpn_224-sw-3b07e89d.pth', hf_hub_id='timm/'), 'vit_medium_patch16_gap_240.sw_in12k': _cfg( hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95, num_classes=11821), 'vit_medium_patch16_gap_256.sw_in12k_ft_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 256, 256), crop_pct=0.95), 'vit_medium_patch16_gap_384.sw_in12k_ft_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 384, 384), crop_pct=0.95, crop_mode='squash'), 'vit_base_patch16_gap_224': _cfg(), # CLIP pretrained image tower and related fine-tuned weights 'vit_base_patch32_clip_224.laion2b_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD), 'vit_base_patch32_clip_384.laion2b_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, input_size=(3, 384, 384)), 'vit_base_patch32_clip_448.laion2b_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, input_size=(3, 448, 448)), 'vit_base_patch16_clip_224.laion2b_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=0.95), 'vit_base_patch16_clip_384.laion2b_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, input_size=(3, 384, 384), crop_mode='squash'), 'vit_large_patch14_clip_224.laion2b_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD, crop_pct=1.0), 'vit_large_patch14_clip_336.laion2b_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD, crop_pct=1.0, input_size=(3, 336, 336), crop_mode='squash'), 'vit_huge_patch14_clip_224.laion2b_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0), 'vit_huge_patch14_clip_336.laion2b_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, input_size=(3, 336, 336), crop_mode='squash'), 'vit_base_patch32_clip_224.openai_ft_in12k_in1k': _cfg( # hf_hub_id='timm/vit_base_patch32_clip_224.openai_ft_in12k_in1k', # FIXME weight exists, need to push mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD), 'vit_base_patch32_clip_384.openai_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=0.95, input_size=(3, 384, 384), crop_mode='squash'), 'vit_base_patch16_clip_224.openai_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=0.95), 'vit_base_patch16_clip_384.openai_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=0.95, input_size=(3, 384, 384), crop_mode='squash'), 'vit_large_patch14_clip_224.openai_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0), 'vit_large_patch14_clip_336.openai_ft_in12k_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, input_size=(3, 336, 336), crop_mode='squash'), 'vit_base_patch32_clip_224.laion2b_ft_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD), 'vit_base_patch16_clip_224.laion2b_ft_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0), 'vit_base_patch16_clip_384.laion2b_ft_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, input_size=(3, 384, 384), crop_mode='squash'), 'vit_large_patch14_clip_224.laion2b_ft_in1k': _cfg( hf_hub_id='timm/', mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD, crop_pct=1.0), 'vit_large_patch14_clip_336.laion2b_ft_in1k': _cfg( hf_hub_id='timm/', mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD, crop_pct=1.0, input_size=(3, 336, 336), crop_mode='squash'), 'vit_huge_patch14_clip_224.laion2b_ft_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0), 'vit_huge_patch14_clip_336.laion2b_ft_in1k': _cfg( hf_hub_id='', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, input_size=(3, 336, 336), crop_mode='squash'), 'vit_base_patch32_clip_224.openai_ft_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD), 'vit_base_patch16_clip_224.openai_ft_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD), 'vit_base_patch16_clip_384.openai_ft_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, input_size=(3, 384, 384), crop_mode='squash'), 'vit_large_patch14_clip_224.openai_ft_in1k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0), 'vit_base_patch32_clip_224.laion2b_ft_in12k': _cfg( #hf_hub_id='timm/vit_base_patch32_clip_224.laion2b_ft_in12k', # FIXME weight exists, need to push mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, num_classes=11821), 'vit_base_patch16_clip_224.laion2b_ft_in12k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, num_classes=11821), 'vit_large_patch14_clip_224.laion2b_ft_in12k': _cfg( hf_hub_id='timm/', mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD, crop_pct=1.0, num_classes=11821), 'vit_huge_patch14_clip_224.laion2b_ft_in12k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=11821), 'vit_base_patch32_clip_224.openai_ft_in12k': _cfg( # hf_hub_id='timm/vit_base_patch32_clip_224.openai_ft_in12k', # FIXME weight exists, need to push mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, num_classes=11821), 'vit_base_patch16_clip_224.openai_ft_in12k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, num_classes=11821), 'vit_large_patch14_clip_224.openai_ft_in12k': _cfg( hf_hub_id='timm/', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=11821), 'vit_base_patch32_clip_224.laion2b': _cfg( hf_hub_id='laion/CLIP-ViT-B-32-laion2B-s34B-b79K', hf_hub_filename='open_clip_pytorch_model.bin', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, num_classes=512), 'vit_base_patch16_clip_224.laion2b': _cfg( hf_hub_id='laion/CLIP-ViT-B-16-laion2B-s34B-b88K', hf_hub_filename='open_clip_pytorch_model.bin', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=512), 'vit_large_patch14_clip_224.laion2b': _cfg( hf_hub_id='laion/CLIP-ViT-L-14-laion2B-s32B-b82K', hf_hub_filename='open_clip_pytorch_model.bin', mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD, crop_pct=1.0, num_classes=768), 'vit_huge_patch14_clip_224.laion2b': _cfg( hf_hub_id='laion/CLIP-ViT-H-14-laion2B-s32B-b79K', hf_hub_filename='open_clip_pytorch_model.bin', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=1024), 'vit_giant_patch14_clip_224.laion2b': _cfg( hf_hub_id='laion/CLIP-ViT-g-14-laion2B-s12B-b42K', hf_hub_filename='open_clip_pytorch_model.bin', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=1024), 'vit_gigantic_patch14_clip_224.laion2b': _cfg( hf_hub_id='laion/CLIP-ViT-bigG-14-laion2B-39B-b160k', hf_hub_filename='open_clip_pytorch_model.bin', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=1280), 'vit_base_patch32_clip_224.datacompxl': _cfg( hf_hub_id='laion/CLIP-ViT-B-32-DataComp.XL-s13B-b90K', hf_hub_filename='open_clip_pytorch_model.bin', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=512), 'vit_base_patch32_clip_256.datacompxl': _cfg( hf_hub_id='laion/CLIP-ViT-B-32-256x256-DataComp-s34B-b86K', hf_hub_filename='open_clip_pytorch_model.bin', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, input_size=(3, 256, 256), num_classes=512), 'vit_base_patch16_clip_224.datacompxl': _cfg( hf_hub_id='laion/CLIP-ViT-B-16-DataComp.XL-s13B-b90K', hf_hub_filename='open_clip_pytorch_model.bin', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=512), 'vit_large_patch14_clip_224.datacompxl': _cfg( hf_hub_id='laion/CLIP-ViT-L-14-DataComp.XL-s13B-b90K', hf_hub_filename='open_clip_pytorch_model.bin', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=768), 'vit_base_patch16_clip_224.dfn2b': _cfg( hf_hub_id='apple/DFN2B-CLIP-ViT-B-16', hf_hub_filename='open_clip_pytorch_model.bin', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=512), 'vit_large_patch14_clip_224.dfn2b': _cfg( hf_hub_id='apple/DFN2B-CLIP-ViT-L-14', hf_hub_filename='open_clip_pytorch_model.bin', notes=('natively QuickGELU, use quickgelu model variant for original results',), mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=768), 'vit_huge_patch14_clip_224.dfn5b': _cfg( hf_hub_id='apple/DFN5B-CLIP-ViT-H-14', hf_hub_filename='open_clip_pytorch_model.bin', notes=('natively QuickGELU, use quickgelu model variant for original results',), mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=1024), 'vit_huge_patch14_clip_378.dfn5b': _cfg( hf_hub_id='apple/DFN5B-CLIP-ViT-H-14-378', hf_hub_filename='open_clip_pytorch_model.bin', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, notes=('natively QuickGELU, use quickgelu model variant for original results',), crop_pct=1.0, input_size=(3, 378, 378), num_classes=1024), 'vit_base_patch32_clip_224.metaclip_2pt5b': _cfg( hf_hub_id='facebook/metaclip-b32-fullcc2.5b', hf_hub_filename='metaclip_b32_fullcc2.5b.bin', license='cc-by-nc-4.0', notes=('natively QuickGELU, use quickgelu model variant for original results',), mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=512), 'vit_base_patch16_clip_224.metaclip_2pt5b': _cfg( hf_hub_id='facebook/metaclip-b16-fullcc2.5b', hf_hub_filename='metaclip_b16_fullcc2.5b.bin', license='cc-by-nc-4.0', notes=('natively QuickGELU, use quickgelu model variant for original results',), mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=512), 'vit_large_patch14_clip_224.metaclip_2pt5b': _cfg( hf_hub_id='facebook/metaclip-l14-fullcc2.5b', hf_hub_filename='metaclip_l14_fullcc2.5b.bin', license='cc-by-nc-4.0', notes=('natively QuickGELU, use quickgelu model variant for original results',), mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=768), 'vit_huge_patch14_clip_224.metaclip_2pt5b': _cfg( hf_hub_id='facebook/metaclip-h14-fullcc2.5b', hf_hub_filename='metaclip_h14_fullcc2.5b.bin', license='cc-by-nc-4.0', notes=('natively QuickGELU, use quickgelu model variant for original results',), mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=1024), 'vit_base_patch32_clip_224.openai': _cfg( hf_hub_id='timm/', notes=('natively QuickGELU, use quickgelu model variant for original results',), mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, num_classes=512), 'vit_base_patch16_clip_224.openai': _cfg( hf_hub_id='timm/', notes=('natively QuickGELU, use quickgelu model variant for original results',), mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, num_classes=512), 'vit_large_patch14_clip_224.openai': _cfg( hf_hub_id='timm/', notes=('natively QuickGELU, use quickgelu model variant for original results',), mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, num_classes=768), 'vit_large_patch14_clip_336.openai': _cfg( hf_hub_id='timm/', hf_hub_filename='open_clip_pytorch_model.bin', notes=('natively QuickGELU, use quickgelu model variant for original results',), mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, crop_pct=1.0, input_size=(3, 336, 336), num_classes=768), # experimental (may be removed) 'vit_base_patch32_plus_256.untrained': _cfg(url='', input_size=(3, 256, 256), crop_pct=0.95), 'vit_base_patch16_plus_240.untrained': _cfg(url='', input_size=(3, 240, 240), crop_pct=0.95), 'vit_small_patch16_36x1_224.untrained': _cfg(url=''), 'vit_small_patch16_18x2_224.untrained': _cfg(url=''), 'vit_base_patch16_18x2_224.untrained': _cfg(url=''), # EVA fine-tuned weights from MAE style MIM - EVA-CLIP target pretrain # https://github.com/baaivision/EVA/blob/7ecf2c0a370d97967e86d047d7af9188f78d2df3/eva/README.md#eva-l-learning-better-mim-representations-from-eva-clip 'eva_large_patch14_196.in22k_ft_in22k_in1k': _cfg( # hf_hub_id='BAAI/EVA', hf_hub_filename='eva_l_psz14_196px_21k_to_1k_ft_88p6.pt', hf_hub_id='timm/', license='mit', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, input_size=(3, 196, 196), crop_pct=1.0), 'eva_large_patch14_336.in22k_ft_in22k_in1k': _cfg( # hf_hub_id='BAAI/EVA', hf_hub_filename='eva_l_psz14_336px_21k_to_1k_ft_89p2.pt', hf_hub_id='timm/', license='mit', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, input_size=(3, 336, 336), crop_pct=1.0, crop_mode='squash'), 'eva_large_patch14_196.in22k_ft_in1k': _cfg( # hf_hub_id='BAAI/EVA', hf_hub_filename='eva_l_psz14_196px_1k_ft_88p0.pt', hf_hub_id='timm/', license='mit', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, input_size=(3, 196, 196), crop_pct=1.0), 'eva_large_patch14_336.in22k_ft_in1k': _cfg( # hf_hub_id='BAAI/EVA', hf_hub_filename='eva_l_psz14_336px_1k_ft_88p65.pt', hf_hub_id='timm/', license='mit', mean=OPENAI_CLIP_MEAN, std=OPENAI_CLIP_STD, input_size=(3, 336, 336), crop_pct=1.0, crop_mode='squash'), 'flexivit_small.1200ep_in1k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/flexivit_s_i1k.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95), 'flexivit_small.600ep_in1k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/flexivit_s_i1k_600ep.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95), 'flexivit_small.300ep_in1k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/flexivit_s_i1k_300ep.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95), 'flexivit_base.1200ep_in1k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/flexivit_b_i1k.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95), 'flexivit_base.600ep_in1k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/flexivit_b_i1k_600ep.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95), 'flexivit_base.300ep_in1k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/flexivit_b_i1k_300ep.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95), 'flexivit_base.1000ep_in21k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/flexivit_b_i21k_1000ep.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95, num_classes=21843), 'flexivit_base.300ep_in21k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/flexivit_b_i21k_300ep.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95, num_classes=21843), 'flexivit_large.1200ep_in1k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/flexivit_l_i1k.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95), 'flexivit_large.600ep_in1k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/flexivit_l_i1k_600ep.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95), 'flexivit_large.300ep_in1k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/flexivit_l_i1k_300ep.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95), 'flexivit_base.patch16_in21k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/vit_b16_i21k_300ep.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95, num_classes=21843), 'flexivit_base.patch30_in21k': _cfg( url='https://storage.googleapis.com/big_vision/flexivit/vit_b30_i21k_300ep.npz', custom_load=True, hf_hub_id='timm/', input_size=(3, 240, 240), crop_pct=0.95, num_classes=21843), 'vit_base_patch16_xp_224.untrained': _cfg(url=''), 'vit_large_patch14_xp_224.untrained': _cfg(url=''), 'vit_huge_patch14_xp_224.untrained': _cfg(url=''), 'vit_base_patch16_224.mae': _cfg( url='https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_base.pth', hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_large_patch16_224.mae': _cfg( url='https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_large.pth', hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_huge_patch14_224.mae': _cfg( url='https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_huge.pth', hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_huge_patch14_gap_224.in1k_ijepa': _cfg( url='https://dl.fbaipublicfiles.com/ijepa/IN1K-vit.h.14-300e.pth.tar', # hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_huge_patch14_gap_224.in22k_ijepa': _cfg( url='https://dl.fbaipublicfiles.com/ijepa/IN22K-vit.h.14-900e.pth.tar', # hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_huge_patch16_gap_448.in1k_ijepa': _cfg( url='https://dl.fbaipublicfiles.com/ijepa/IN1K-vit.h.16-448px-300e.pth.tar', # hf_hub_id='timm/', license='cc-by-nc-4.0', input_size=(3, 448, 448), crop_pct=1.0, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_giant_patch16_gap_224.in22k_ijepa': _cfg( url='https://dl.fbaipublicfiles.com/ijepa/IN22K-vit.g.16-600e.pth.tar', # hf_hub_id='timm/', license='cc-by-nc-4.0', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_classes=0), 'vit_base_patch16_siglip_224.webli': _cfg( hf_hub_id='timm/ViT-B-16-SigLIP', hf_hub_filename='open_clip_pytorch_model.bin', num_classes=0), 'vit_base_patch16_siglip_256.webli': _cfg( hf_hub_id='timm/ViT-B-16-SigLIP-256', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 256, 256), num_classes=0), 'vit_base_patch16_siglip_384.webli': _cfg( hf_hub_id='timm/ViT-B-16-SigLIP-384', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 384, 384), num_classes=0), 'vit_base_patch16_siglip_512.webli': _cfg( hf_hub_id='timm/ViT-B-16-SigLIP-512', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 512, 512), num_classes=0), 'vit_large_patch16_siglip_256.webli': _cfg( hf_hub_id='timm/ViT-L-16-SigLIP-256', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 256, 256), num_classes=0), 'vit_large_patch16_siglip_384.webli': _cfg( hf_hub_id='timm/ViT-L-16-SigLIP-384', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 384, 384), num_classes=0), 'vit_so400m_patch14_siglip_224.webli': _cfg( hf_hub_id='timm/ViT-SO400M-14-SigLIP', hf_hub_filename='open_clip_pytorch_model.bin', num_classes=0), 'vit_so400m_patch14_siglip_384.webli': _cfg( hf_hub_id='timm/ViT-SO400M-14-SigLIP-384', hf_hub_filename='open_clip_pytorch_model.bin', input_size=(3, 384, 384), num_classes=0), 'vit_medium_patch16_reg4_256': _cfg( input_size=(3, 256, 256)), 'vit_medium_patch16_reg4_gap_256': _cfg( input_size=(3, 256, 256)), 'vit_base_patch16_reg8_gap_256': _cfg(input_size=(3, 256, 256)), } _quick_gelu_cfgs = [ 'vit_large_patch14_clip_224.dfn2b', 'vit_huge_patch14_clip_224.dfn5b', 'vit_huge_patch14_clip_378.dfn5b', 'vit_base_patch32_clip_224.metaclip_2pt5b', 'vit_base_patch16_clip_224.metaclip_2pt5b', 'vit_large_patch14_clip_224.metaclip_2pt5b', 'vit_huge_patch14_clip_224.metaclip_2pt5b', 'vit_base_patch32_clip_224.openai', 'vit_base_patch16_clip_224.openai', 'vit_large_patch14_clip_224.openai', 'vit_large_patch14_clip_336.openai', ] default_cfgs.update({ n.replace('_clip_', '_clip_quickgelu_'): default_cfgs[n] for n in _quick_gelu_cfgs }) default_cfgs = generate_default_cfgs(default_cfgs) def _create_vision_transformer(variant, pretrained=False, **kwargs): if kwargs.get('features_only', None): raise RuntimeError('features_only not implemented for Vision Transformer models.') if 'flexi' in variant: # FIXME Google FlexiViT pretrained models have a strong preference for bilinear patch / embed # interpolation, other pretrained models resize better w/ anti-aliased bicubic interpolation. _filter_fn = partial(checkpoint_filter_fn, interpolation='bilinear', antialias=False) else: _filter_fn = checkpoint_filter_fn # FIXME attn pool (currently only in siglip) params removed if pool disabled, is there a better soln? strict = True if 'siglip' in variant and kwargs.get('global_pool', None) != 'map': strict = False
return build_model_with_cfg(
0
2023-11-05 01:25:14+00:00
12k
ilur98/DGQ
dgq/quant/quant_sequence.py
[ { "identifier": "prepare_hook", "path": "dgq/quant/smooth_hooker.py", "snippet": "def prepare_hook(layer, inps, qconfig, inps_kwargs): \n handles = []\n for mod in layer.modules():\n if isinstance(mod, nn.LayerNorm) or isinstance(mod, LlamaRMSNorm):\n if qconfig[\"meanact\"]:\n ...
import torch import torch.nn as nn from dgq.quant.smooth_hooker import prepare_hook from dgq.quant.smooth import mean_bias, smooth_module from dgq.quant.quant_linear import QuantLinear from dgq.quant.quantizer_helper import QuantizerHelper from dgq.quant.kvquanter import kvquant from dgq.utils.modelutils import find_layers, move_embed, get_blocks
7,985
__all__ = ["quant_sequential"] def set_quant_state(module, actq, wtq): for mod in module.modules(): if isinstance(mod, QuantLinear): mod.setquant(actq, wtq) @torch.no_grad() def PTQ(model, enc, qconfig, nsamples=128, seqlen=2048): dev = "cuda:0"
__all__ = ["quant_sequential"] def set_quant_state(module, actq, wtq): for mod in module.modules(): if isinstance(mod, QuantLinear): mod.setquant(actq, wtq) @torch.no_grad() def PTQ(model, enc, qconfig, nsamples=128, seqlen=2048): dev = "cuda:0"
layers = get_blocks(model)
8
2023-11-01 13:45:16+00:00
12k
noco-ai/elemental-golem
server.py
[ { "identifier": "install_skill", "path": "application/download.py", "snippet": "def install_skill(all_skills, install_skill_data, shared_models, server_id, channel):\n # Create a list to hold all the processes\n processes = []\n for skill in all_skills:\n if skill[\"routing_key\"] != ins...
import logging import argparse import time import os import json import hashlib import hvac from typing import Dict from application.download import install_skill from application.system_info import get_system_info, load_configs, load_enabled_skills from application.amqp import connect_to_amqp, become_consumer, bind_queue_to_exchange from application.amqp import create_exchange, create_queue, send_message_to_exchange from application.thread import start_worker_threads, stop_worker_thread, get_worker_threads, stop_all_threads, update_thread_configuration, stop_thread_generation
7,298
# create dead letter exchange and queue create_exchange(amqp_channel, 'deadletter') flx_queue = create_queue(channel=amqp_channel, queue_name='deadletters') bind_queue_to_exchange(amqp_channel, 'deadletters', 'deadletter') # create exchange and queue for this server create_exchange(amqp_channel, 'golem') create_exchange(amqp_channel, 'golem_broadcast', 'fanout') create_exchange(amqp_channel, 'arcane_bridge_broadcast', 'fanout') create_queue(channel=amqp_channel, queue_name=server_id, is_auto_delete=True, dlx="deadletter") bind_queue_to_exchange(amqp_channel, server_id, 'golem') bind_queue_to_exchange(amqp_channel, server_id, 'golem_broadcast') # start all the pipe threads create_exchange(amqp_channel, 'golem_skill') # define server call back for answering messages def server_callback(ch, method, properties, body): global all_skills, all_configs, all_models, all_repos, script_map, loaded_handlers if "command" not in properties.headers or "return_routing_key" not in properties.headers or "return_exchange" not in properties.headers: logger.info("command or return routing not found in header. command, return_route_key, and return_exchange are required headers") amqp_channel.basic_reject(delivery_tag=method.delivery_tag, requeue=False) return logger.info(f"incoming command {properties.headers['command']}") try: headers = {} command = properties.headers.get('command') return_key = properties.headers.get('return_routing_key') return_exchange = properties.headers.get('return_exchange') for key, value in properties.headers.items(): # Exclude return_exchange and return_routing_key if key not in ['return_exchange', 'return_routing_key', 'x-delay']: headers[key] = value if command == "system_info": installed_models, installed_repos, downloading_models = check_data_directories(all_models, all_repos) # get list of installed models system_info = get_system_info(server_id, args.gpu_type) system_info["server_id"] = server_id system_info["server_label"] = server_id.replace("_", "-") system_info["installed_models"] = installed_models system_info["downloading_models"] = downloading_models system_info["installed_repository"] = installed_repos system_info["handlers"] = loaded_handlers # protect secrets from the UI stripped_skills = [{k: v for k, v in skill.items() if k != "secrets"} for skill in all_skills] system_info["installed_skills"] = stripped_skills running_skills = [] system_info["status"] = "ONLINE" worker_threads = get_worker_threads() for thread in worker_threads: thread_status = thread["thread_status"].raw.decode().rstrip('\0') if thread_status != "ONLINE": system_info["status"] = "STARTING" running_skills.extend([{"device":thread["device"], "routing_key": thread["routing_key"], "ram": thread["ram"] * 1000000, "use_precision": thread["use_precision"], "thread_status": thread_status }]) system_info["running_skills"] = running_skills send_message_to_exchange(amqp_channel, return_exchange, return_key, json.dumps(system_info).encode(), headers) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) return elif command == "run_skill": skill_details = json.loads(body) add_skill(skill_details, server_id) run_map = {skill_details["routing_key"]: [skill_details]} start_worker_threads(all_skills, run_map, amqp_params, script_map, server_id) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) return elif command == "stop_skill": skill_details = json.loads(body) remove_skill(skill_details, server_id) stop_worker_thread(skill_details, amqp_channel) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) return elif command == "install_skill": skill_details = json.loads(body) install_skill(all_skills, skill_details, args.shared_models, server_id, amqp_channel) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) logger.info('skill installing 🚀') return elif command == "custom_skill": skill_details = json.loads(body) install_custom_skill(skill_details, server_id) all_skills, all_configs, all_models, all_repos, script_map, loaded_handlers = load_configs('modules', vault_client, args.vault_root, server_id) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) logger.info('custom skill installed 🚀') return elif command == "stop_generation": stop_details = json.loads(body) stop_thread_generation(stop_details) logger.info(stop_details) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) logger.info('generation stopped 🛑') return elif command == "update_configuration": details = json.loads(body) vault_data = update_thread_configuration(args.vault_root, vault_client, details["vault_path"]) for skill in all_skills: if "configuration_template" in skill and "vault_path" in skill["configuration_template"] and skill["configuration_template"]["vault_path"] == details["vault_path"]: current_config = skill["configuration"] merged_config = {**current_config, **vault_data} skill["configuration"] = merged_config amqp_channel.basic_ack(delivery_tag=method.delivery_tag) logger.info('configuration updated 🔧') return except Exception as e: logger.error("an error occurred:", e) amqp_channel.basic_reject(delivery_tag=method.delivery_tag, requeue=False) logger.info(f"command {properties.headers['command']} not found") amqp_channel.basic_reject(delivery_tag=method.delivery_tag, requeue=False)
pika_logger = logging.getLogger("pika") pika_logger.setLevel(logging.WARNING) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # local modules # checks what models are installed on the system def check_data_directories(all_models, all_repos): # make sure dirs are present os.makedirs("data/models", exist_ok=True) os.makedirs("data/loras", exist_ok=True) os.makedirs("data/repos", exist_ok=True) # list of installed models available_models = [] downloading_models = [] for model_data in all_models: model_name = model_data["path"] model_directory = f"data/models/{model_name}" lock_file_path = f'data/models/{model_data["lock_file"]}' if os.path.exists(lock_file_path): downloading_models.append(model_name) elif os.path.exists(model_directory): available_models.append(model_name) # list of insalled repors available_repos = [] for repo_name in all_repos: repo_directory = f"data/repos/{repo_name}" if os.path.exists(repo_directory): available_repos.append(repo_name) return available_models, available_repos, downloading_models def add_skill(new_skill: dict, server_id: str): # load existing skills enabled_skills = load_enabled_skills(server_id) # flatten the list of lists into a single list flattened_skills = [skill for sublist in enabled_skills.values() for skill in sublist] # expected keys expected_keys = {"routing_key": str, "device": str, "use_precision": str} # check if new_skill is valid if (set(new_skill.keys()) == set(expected_keys.keys()) and all(isinstance(new_skill[key], expected_keys[key]) for key in expected_keys)): # add new skill to the list flattened_skills.append(new_skill) # save back to file with open(f'data/{server_id}_skills.json', 'w') as f: json.dump(flattened_skills, f) else: logger.info(f"invalid skill data: {new_skill}") def remove_skill(skill_to_remove: dict, server_id: str): # load existing skills enabled_skills = load_enabled_skills(server_id) # flatten the list of lists into a single list flattened_skills = [skill for sublist in enabled_skills.values() for skill in sublist] # iterate over the skills to find the first match and remove it for i, skill in enumerate(flattened_skills): if skill == skill_to_remove: del flattened_skills[i] break # save back to file with open(f'data/{server_id}_skills.json', 'w') as f: json.dump(flattened_skills, f) def fatal_error(error): logger.error(error) time.sleep(3) os._exit(0) def install_custom_skill(skill_details, server_id): data = [] filename = f"data/{server_id}_custom.json" if os.path.exists(filename): with open(filename, 'r') as file: data = json.load(file) if not isinstance(data, list): raise TypeError("The file must contain a JSON array.") data.append(skill_details) with open(filename, 'w') as file: json.dump(data, file, indent=4) def connect_to_vault(vault_url, vault_token_file, vault_root, max_retries=10, sleep_time=8): for retry in range(max_retries): try: # Read the Vault token from file if os.path.isfile(args.vault_token_file): # Read the Vault token from file with open(vault_token_file, 'r') as file: vault_token = file.read().strip() logger.info(f"vault connecting to {vault_url}, vhost: {vault_root}") vault_client = hvac.Client(url=vault_url, token=vault_token, namespace=vault_root) vault_connected = vault_client.is_authenticated() if vault_connected: # give a bit of time for amqp to write its creds vault_data_resp = vault_client.read(path=f'{vault_root}/data/core/amqp') if vault_data_resp == None: raise ValueError('invalid response from vault server') vault_data = vault_data_resp['data']['data'] # Check if all required fields are present required_fields = ['host', 'username', 'password', 'vhost'] if not all(field in vault_data for field in required_fields): missing_fields = [field for field in required_fields if field not in vault_data] raise ValueError(missing_fields) logger.info('successfully connected to vault server') return vault_client, vault_data else: logger.info(f"waiting for token file creation") except Exception as e: print(e) pass time.sleep(sleep_time) logger.info(f"retrying connection to vault server. attempt {retry+1}/{max_retries}") # If connection is not successful after max_retries fatal_error('unable to connect to vault server after multiple attempts.') if __name__ == "__main__": logger.info("starting elemental golem") # Parse command-line arguments parser = argparse.ArgumentParser(description='Vault creds') parser.add_argument('--server-id', required=True, help='Unique server ID') parser.add_argument('--vault-host', required=True, help='Vault server host address') parser.add_argument('--vault-token-file', help='Path to the Vault token file', default='./vault-token') parser.add_argument('--vault-root', help='Root path in the Vault server', default='spellbook') parser.add_argument('--amqp-ip', help='Overrides what is stored in Vault for the amqp ip.') parser.add_argument('--shared-models', required=False, help='Show be set to true is the data/ folder is shared between golem instances or in a docker container.', default=False, type=bool) parser.add_argument('--gpu-type', help='The type of GPU the system has onboard', default='nvidia', choices=['nvidia', 'nogpu']) args = parser.parse_args() vault_client, vault_data = connect_to_vault(args.vault_host, args.vault_token_file, args.vault_root) # connect to amqp amqp_ip = args.amqp_ip if args.amqp_ip != None else vault_data['host'] amqp_params = { 'amqp_ip': amqp_ip, 'amqp_user': vault_data['username'], 'amqp_password': vault_data['password'], 'amqp_vhost': vault_data['vhost'] } server_name = args.server_id server_id = 'golem_' + hashlib.sha256(server_name.encode()).hexdigest()[:10] # load config files all_skills, all_configs, all_models, all_repos, script_map, loaded_handlers = load_configs('modules', vault_client, args.vault_root, server_id, args.gpu_type) # load enabled models json tp dict enabled_skills_dict = load_enabled_skills(server_id) # start threads start_worker_threads(all_skills, enabled_skills_dict, amqp_params, script_map, server_id) # connect to rabbit mq amqp_connected, amqp_connection, amqp_channel = connect_to_amqp(**amqp_params) if amqp_connected == False: fatal_error('unable to connect to amqp server') # create dead letter exchange and queue create_exchange(amqp_channel, 'deadletter') flx_queue = create_queue(channel=amqp_channel, queue_name='deadletters') bind_queue_to_exchange(amqp_channel, 'deadletters', 'deadletter') # create exchange and queue for this server create_exchange(amqp_channel, 'golem') create_exchange(amqp_channel, 'golem_broadcast', 'fanout') create_exchange(amqp_channel, 'arcane_bridge_broadcast', 'fanout') create_queue(channel=amqp_channel, queue_name=server_id, is_auto_delete=True, dlx="deadletter") bind_queue_to_exchange(amqp_channel, server_id, 'golem') bind_queue_to_exchange(amqp_channel, server_id, 'golem_broadcast') # start all the pipe threads create_exchange(amqp_channel, 'golem_skill') # define server call back for answering messages def server_callback(ch, method, properties, body): global all_skills, all_configs, all_models, all_repos, script_map, loaded_handlers if "command" not in properties.headers or "return_routing_key" not in properties.headers or "return_exchange" not in properties.headers: logger.info("command or return routing not found in header. command, return_route_key, and return_exchange are required headers") amqp_channel.basic_reject(delivery_tag=method.delivery_tag, requeue=False) return logger.info(f"incoming command {properties.headers['command']}") try: headers = {} command = properties.headers.get('command') return_key = properties.headers.get('return_routing_key') return_exchange = properties.headers.get('return_exchange') for key, value in properties.headers.items(): # Exclude return_exchange and return_routing_key if key not in ['return_exchange', 'return_routing_key', 'x-delay']: headers[key] = value if command == "system_info": installed_models, installed_repos, downloading_models = check_data_directories(all_models, all_repos) # get list of installed models system_info = get_system_info(server_id, args.gpu_type) system_info["server_id"] = server_id system_info["server_label"] = server_id.replace("_", "-") system_info["installed_models"] = installed_models system_info["downloading_models"] = downloading_models system_info["installed_repository"] = installed_repos system_info["handlers"] = loaded_handlers # protect secrets from the UI stripped_skills = [{k: v for k, v in skill.items() if k != "secrets"} for skill in all_skills] system_info["installed_skills"] = stripped_skills running_skills = [] system_info["status"] = "ONLINE" worker_threads = get_worker_threads() for thread in worker_threads: thread_status = thread["thread_status"].raw.decode().rstrip('\0') if thread_status != "ONLINE": system_info["status"] = "STARTING" running_skills.extend([{"device":thread["device"], "routing_key": thread["routing_key"], "ram": thread["ram"] * 1000000, "use_precision": thread["use_precision"], "thread_status": thread_status }]) system_info["running_skills"] = running_skills send_message_to_exchange(amqp_channel, return_exchange, return_key, json.dumps(system_info).encode(), headers) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) return elif command == "run_skill": skill_details = json.loads(body) add_skill(skill_details, server_id) run_map = {skill_details["routing_key"]: [skill_details]} start_worker_threads(all_skills, run_map, amqp_params, script_map, server_id) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) return elif command == "stop_skill": skill_details = json.loads(body) remove_skill(skill_details, server_id) stop_worker_thread(skill_details, amqp_channel) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) return elif command == "install_skill": skill_details = json.loads(body) install_skill(all_skills, skill_details, args.shared_models, server_id, amqp_channel) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) logger.info('skill installing 🚀') return elif command == "custom_skill": skill_details = json.loads(body) install_custom_skill(skill_details, server_id) all_skills, all_configs, all_models, all_repos, script_map, loaded_handlers = load_configs('modules', vault_client, args.vault_root, server_id) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) logger.info('custom skill installed 🚀') return elif command == "stop_generation": stop_details = json.loads(body) stop_thread_generation(stop_details) logger.info(stop_details) amqp_channel.basic_ack(delivery_tag=method.delivery_tag) logger.info('generation stopped 🛑') return elif command == "update_configuration": details = json.loads(body) vault_data = update_thread_configuration(args.vault_root, vault_client, details["vault_path"]) for skill in all_skills: if "configuration_template" in skill and "vault_path" in skill["configuration_template"] and skill["configuration_template"]["vault_path"] == details["vault_path"]: current_config = skill["configuration"] merged_config = {**current_config, **vault_data} skill["configuration"] = merged_config amqp_channel.basic_ack(delivery_tag=method.delivery_tag) logger.info('configuration updated 🔧') return except Exception as e: logger.error("an error occurred:", e) amqp_channel.basic_reject(delivery_tag=method.delivery_tag, requeue=False) logger.info(f"command {properties.headers['command']} not found") amqp_channel.basic_reject(delivery_tag=method.delivery_tag, requeue=False)
become_consumer(amqp_channel, server_id, server_callback)
5
2023-11-06 19:03:07+00:00
12k
m4rkw/monzo-utils
monzo_utils/lib/monzo_sync.py
[ { "identifier": "Config", "path": "monzo_utils/lib/config.py", "snippet": "class Config(metaclass=Singleton):\n\n def __init__(self, config=None, config_path=None):\n if config_path is None:\n homedir = pwd.getpwuid(os.getuid()).pw_dir\n config_path = f\"{homedir}/.monzo\...
import os import sys import time import json import yaml import re import datetime import pwd from pathlib import Path from monzo_utils.lib.config import Config from monzo_utils.lib.db import DB from monzo_utils.lib.log import Log from monzo_utils.lib.monzo_api import MonzoAPI from monzo_utils.model.provider import Provider from monzo_utils.model.account import Account from monzo_utils.model.merchant import Merchant from monzo_utils.model.merchant_address import MerchantAddress from monzo_utils.model.pot import Pot from monzo_utils.model.transaction import Transaction from monzo_utils.model.counterparty import Counterparty from monzo_utils.model.transaction_metadata import TransactionMetadata from monzo.exceptions import MonzoAuthenticationError, MonzoServerError, MonzoHTTPError, MonzoPermissionsError
8,183
continue if 'accounts' in Config().keys and account.account_id in Config().accounts: continue if 'Joint account between' in account.description: account_type = 'Joint Current Account' else: account_type = account.account_type() print(f" id: {account.account_id}") print(f" balance: £{account.balance.balance/100:.2f}") print(f"description: {account.description}") print(f" type: {account_type}") sys.stdout.write("\n") resp = self.prompt_continue('Sync this account? [y/N] ', True) if resp == 'n': continue account_name = self.prompt_input('name for this account') if 'accounts' not in Config().keys: Config().set('accounts', {}) Config().accounts[account.account_id] = { 'name': account_name } if account_type == 'Flex': Config().accounts[account.account_id]['credit_limit'] = self.prompt_input('credit limit', None, False, 'int') else: Config().accounts[account.account_id]['sortcode'] = self.prompt_input('sort code') Config().accounts[account.account_id]['account_no'] = self.prompt_input('account no') sys.stdout.write("\n") Config().save() def prompt_continue(self, prompt='Continue? [y/N] ', boolean=False): while 1: sys.stdout.write(prompt) sys.stdout.flush() resp = sys.stdin.readline().rstrip().lower() if resp == 'n': if boolean: return False print("\nStopping at user request.\n") sys.exit(0) if resp == 'y': break return True def prompt_input(self, prompt, default=None, none_allowed=False, validation=None): while 1: if default is None: sys.stdout.write(f"Enter {prompt}: ") else: sys.stdout.write(f"Enter {prompt} [{default}]: ") sys.stdout.flush() resp = sys.stdin.readline().rstrip() if len(resp) == 0: if default is None and none_allowed is False: continue resp = default if validation == 'int' and resp is not None: try: resp = int(resp) except: sys.stderr.write("\nerror: value must be an integer\n\n") sys.stderr.flush() continue return resp def test_db_access(self, db_config): try: db = DB(db_config) except Exception as e: Log().error(f"failed to initialise the database: {str(e)}") sys.exit(1) try: if db_config['driver'] == 'mysql': resp = db.query("show tables") else: resp = db.query("pragma table_info(`provider`)") except Exception as e: Log().error(f"Failed to connect to the database: {str(e)}") sys.exit(1) def get_or_create_merchant(self, mo_merchant): if 'metadata' in mo_merchant and 'website' in mo_merchant['metadata']: website = mo_merchant['metadata']['website'] else: website = None merchant_id = mo_merchant['id'] mo_merchant['merchant_id'] = mo_merchant['id'] mo_merchant.pop('id') mo_address = mo_merchant.pop('address')
#!/usr/bin/env python3 PROVIDER = 'Monzo' class MonzoSync: def __init__(self, no_init=False): homedir = pwd.getpwuid(os.getuid()).pw_dir self.monzo_dir = f"{homedir}/.monzo" if not os.path.exists(self.monzo_dir): os.mkdir(self.monzo_dir, 0o755) self.config_file = f"{self.monzo_dir}/config.yaml" self.token_file = f"{self.monzo_dir}/tokens" if no_init: return Config() self.api = MonzoAPI() self.db = DB() self.provider = self.get_provider() def setup(self): print("\n========================") print("Monzo Utils Setup Wizard") print("========================\n") print("Requirements:\n") print("1) You must have created an OAuth client here: https://developers.monzo.com/apps/new") print(" Note: confidentiality must be set to Confidential\n") print("2) The database (MySQL/MariaDB or SQLite3) must be created and ready (see README.md)\n") print("3) The machine we are running on must be reachable on a known port from the internet.") print(" The webserver must be configured with the CGI script to capture the oauth tokens.") print(" This is only required during setup for the initial oauth authentication flow.") print(" Once this is complete and the tokens are stored this can be removed.\n") self.prompt_continue() if os.path.exists(self.config_file): sys.stdout.write(f"\nWARNING! Config file already exists at: {self.config_file}\n\n") sys.stdout.write("If we continue this will be erased.\n\n") self.prompt_continue() sys.stdout.write("\n") sys.stdout.write("Which database do you want to use?\n\n") sys.stdout.write("1. MySQL/MariaDB (recommended)\n") sys.stdout.write("2. SQLite3\n\n") while 1: db_backend = self.prompt_input('DB choice') if db_backend in ['1','2']: break if db_backend == '1': mysql_host = self.prompt_input('MySQL host', '127.0.0.1') mysql_port = self.prompt_input('MySQL port', '3306', False, 'int') mysql_db = self.prompt_input('MySQL database', 'monzo') mysql_user = self.prompt_input('MySQL username', 'monzo') mysql_password = self.prompt_input('MySQL password', 'monzo') db = { 'driver': 'mysql', 'host': mysql_host, 'port': mysql_port, 'user': mysql_user, 'password': mysql_password, 'database': mysql_db } else: db = { 'driver': 'sqlite', 'path': f"{self.monzo_dir}/data.db" } self.test_db_access(db) sys.stdout.write("\n") client_id = self.prompt_input('Monzo Client ID') client_secret = self.prompt_input('Monzo Client Secret') redirect_url = self.prompt_input('Monzo Client redirect URL') sys.stdout.write("Enter the path where the CGI script will store the token file:\n") token_path = self.prompt_input('Token path', '/var/www/monzo/token') sys.stdout.write("\nIf the auth token expires or stops working the sync script can send\n") sys.stdout.write("an email to notify you. Enter this email below or leave blank if not required.\n") email = self.prompt_input('Email', None, True) Config({ 'oauth_token_file': token_path, 'db': db, 'client_id': client_id, 'client_secret': client_secret, 'redirect_url': redirect_url, 'email': email }) Config().save() self.__init__() self.scan_accounts() sys.stdout.write("Performing initial transaction sync ...\n\n") sys.stdout.flush() self.sync(days=89) sys.stdout.write("\nSetup complete!\n\n") def scan_accounts(self): sys.stdout.write("\nFinding accounts...\n\n") accounts = self.api.accounts() found_accounts = [] for account in accounts: if account.balance is None: continue if 'accounts' in Config().keys and account.account_id in Config().accounts: continue if 'Joint account between' in account.description: account_type = 'Joint Current Account' else: account_type = account.account_type() print(f" id: {account.account_id}") print(f" balance: £{account.balance.balance/100:.2f}") print(f"description: {account.description}") print(f" type: {account_type}") sys.stdout.write("\n") resp = self.prompt_continue('Sync this account? [y/N] ', True) if resp == 'n': continue account_name = self.prompt_input('name for this account') if 'accounts' not in Config().keys: Config().set('accounts', {}) Config().accounts[account.account_id] = { 'name': account_name } if account_type == 'Flex': Config().accounts[account.account_id]['credit_limit'] = self.prompt_input('credit limit', None, False, 'int') else: Config().accounts[account.account_id]['sortcode'] = self.prompt_input('sort code') Config().accounts[account.account_id]['account_no'] = self.prompt_input('account no') sys.stdout.write("\n") Config().save() def prompt_continue(self, prompt='Continue? [y/N] ', boolean=False): while 1: sys.stdout.write(prompt) sys.stdout.flush() resp = sys.stdin.readline().rstrip().lower() if resp == 'n': if boolean: return False print("\nStopping at user request.\n") sys.exit(0) if resp == 'y': break return True def prompt_input(self, prompt, default=None, none_allowed=False, validation=None): while 1: if default is None: sys.stdout.write(f"Enter {prompt}: ") else: sys.stdout.write(f"Enter {prompt} [{default}]: ") sys.stdout.flush() resp = sys.stdin.readline().rstrip() if len(resp) == 0: if default is None and none_allowed is False: continue resp = default if validation == 'int' and resp is not None: try: resp = int(resp) except: sys.stderr.write("\nerror: value must be an integer\n\n") sys.stderr.flush() continue return resp def test_db_access(self, db_config): try: db = DB(db_config) except Exception as e: Log().error(f"failed to initialise the database: {str(e)}") sys.exit(1) try: if db_config['driver'] == 'mysql': resp = db.query("show tables") else: resp = db.query("pragma table_info(`provider`)") except Exception as e: Log().error(f"Failed to connect to the database: {str(e)}") sys.exit(1) def get_or_create_merchant(self, mo_merchant): if 'metadata' in mo_merchant and 'website' in mo_merchant['metadata']: website = mo_merchant['metadata']['website'] else: website = None merchant_id = mo_merchant['id'] mo_merchant['merchant_id'] = mo_merchant['id'] mo_merchant.pop('id') mo_address = mo_merchant.pop('address')
merchant = Merchant().find_by_merchant_id(merchant_id)
6
2023-11-05 12:48:18+00:00
12k
WolfgangFahl/dcm
dcm/dcm_chart.py
[ { "identifier": "CompetenceElement", "path": "dcm/dcm_core.py", "snippet": "class CompetenceElement:\n \"\"\"\n A base class representing a generic competence element with common properties.\n\n Attributes:\n name (str): The name of the competence element.\n id (Optional[str]): An...
from dataclasses import dataclass from typing import List, Optional from dcm.dcm_core import ( CompetenceElement, CompetenceFacet, CompetenceTree, DynamicCompetenceMap, Learner, ) from dcm.svg import SVG, DonutSegment, SVGConfig
9,610
""" Created on 2024-01-12 @author: wf """ class DcmChart: """ a Dynamic competence map chart """ def __init__(self, dcm: DynamicCompetenceMap): """ Constructor """ self.dcm = dcm def generate_svg( self, filename: Optional[str] = None, learner: Optional[Learner] = None, config: Optional[SVGConfig] = None, ) -> str: """ Generate the SVG markup and optionally save it to a file. If a filename is given, the method will also save the SVG to that file. The SVG is generated based on internal state not shown here. Args: filename (str, optional): The path to the file where the SVG should be saved. Defaults to None. learner(Learner): the learner to show the achievements for config (SVGConfig, optional): The configuration for the SVG canvas and legend. Defaults to default values. Returns: str: The SVG markup. """ if config is None: config = SVGConfig() # Use default configuration if none provided svg_markup = self.generate_svg_markup( self.dcm.competence_tree, learner=learner, config=config ) if filename: self.save_svg_to_file(svg_markup, filename) return svg_markup def generate_donut_segment_for_element( self, svg: SVG, element: CompetenceElement, learner: Learner,
""" Created on 2024-01-12 @author: wf """ class DcmChart: """ a Dynamic competence map chart """ def __init__(self, dcm: DynamicCompetenceMap): """ Constructor """ self.dcm = dcm def generate_svg( self, filename: Optional[str] = None, learner: Optional[Learner] = None, config: Optional[SVGConfig] = None, ) -> str: """ Generate the SVG markup and optionally save it to a file. If a filename is given, the method will also save the SVG to that file. The SVG is generated based on internal state not shown here. Args: filename (str, optional): The path to the file where the SVG should be saved. Defaults to None. learner(Learner): the learner to show the achievements for config (SVGConfig, optional): The configuration for the SVG canvas and legend. Defaults to default values. Returns: str: The SVG markup. """ if config is None: config = SVGConfig() # Use default configuration if none provided svg_markup = self.generate_svg_markup( self.dcm.competence_tree, learner=learner, config=config ) if filename: self.save_svg_to_file(svg_markup, filename) return svg_markup def generate_donut_segment_for_element( self, svg: SVG, element: CompetenceElement, learner: Learner,
segment: DonutSegment,
6
2023-11-06 09:24:24+00:00
12k
fortelex/hiveline
hiveline/results/trace_plotter.py
[ { "identifier": "Place", "path": "hiveline/od/place.py", "snippet": "class Place():\n\n def __init__(self, place_name: str, year: str):\n '''\n Initialize the place object, load geographical shape and tiling\n Args:\n place_name (str): the place name (ex: 'Konstanz, Ge...
from hiveline.od.place import Place from hiveline.plotting.map import CityPlotter, get_line_traces_by_mode, add_line_traces from hiveline.results.journeys import Journeys from hiveline.results.modal_shares import decide, Params
8,279
def _prepare_traces(journeys: Journeys, only_use_selected=True): selection: list[str] | None = None if only_use_selected: selection = journeys.get_selection(lambda options: decide(options, Params())) print("Extracting traces...") return [trace for trace in journeys.iterate_traces(selection)] def plot_trace_animation(journeys: Journeys, only_use_selected=True, zoom_level=13, tall_city=False, fps=30, duration=30): raw_traces = _prepare_traces(journeys, only_use_selected=only_use_selected) print("Plotting traces...") total_frames = fps * duration num_to_plot = 0 num_step = int(len(raw_traces) / total_frames) plotter = CityPlotter(place, zoom=zoom_level) webdriver = plotter.setup_webdriver() traces = {} for i in range(total_frames): print(f"Frame {i} of {total_frames}") raw_to_add = raw_traces[num_to_plot:num_to_plot + num_step]
def _prepare_traces(journeys: Journeys, only_use_selected=True): selection: list[str] | None = None if only_use_selected: selection = journeys.get_selection(lambda options: decide(options, Params())) print("Extracting traces...") return [trace for trace in journeys.iterate_traces(selection)] def plot_trace_animation(journeys: Journeys, only_use_selected=True, zoom_level=13, tall_city=False, fps=30, duration=30): raw_traces = _prepare_traces(journeys, only_use_selected=only_use_selected) print("Plotting traces...") total_frames = fps * duration num_to_plot = 0 num_step = int(len(raw_traces) / total_frames) plotter = CityPlotter(place, zoom=zoom_level) webdriver = plotter.setup_webdriver() traces = {} for i in range(total_frames): print(f"Frame {i} of {total_frames}") raw_to_add = raw_traces[num_to_plot:num_to_plot + num_step]
traces_to_add = get_line_traces_by_mode(raw_to_add)
2
2023-11-07 15:34:04+00:00
12k
uhppoted/uhppoted-app-home-assistant
custom_components/uhppoted/config_flow.py
[ { "identifier": "DOMAIN", "path": "custom_components/uhppoted/const.py", "snippet": "DOMAIN = 'uhppoted'" }, { "identifier": "CONF_BIND_ADDR", "path": "custom_components/uhppoted/const.py", "snippet": "CONF_BIND_ADDR = 'bind_address'" }, { "identifier": "CONF_BROADCAST_ADDR", ...
import logging import re import uuid import voluptuous as vol from typing import Any from typing import Dict from typing import Optional from homeassistant.core import HomeAssistant from homeassistant.core import callback from homeassistant.config_entries import ConfigFlow from homeassistant.config_entries import OptionsFlow from homeassistant.config_entries import ConfigEntry from homeassistant.helpers import selector from homeassistant.helpers.selector import SelectSelector from homeassistant.helpers.selector import SelectSelectorConfig from homeassistant.helpers.selector import SelectSelectorMode from homeassistant.helpers import config_validation as cv from uhppoted import uhppote from .const import DOMAIN from .const import CONF_BIND_ADDR from .const import CONF_BROADCAST_ADDR from .const import CONF_LISTEN_ADDR from .const import CONF_DEBUG from .const import CONF_CONTROLLERS from .const import CONF_CONTROLLER_ID from .const import CONF_CONTROLLER_SERIAL_NUMBER from .const import CONF_CONTROLLER_ADDR from .const import CONF_CONTROLLER_TIMEZONE from .const import CONF_DOORS from .const import CONF_DOOR_ID from .const import CONF_DOOR_CONTROLLER from .const import CONF_DOOR_NUMBER from .const import CONF_CARDS from .const import CONF_CARD_UNIQUE_ID from .const import CONF_CARD_NUMBER from .const import CONF_CARD_NAME from .const import CONF_CARD_STARTDATE from .const import CONF_CARD_ENDDATE from .const import CONF_CARD_DOORS from .const import DEFAULT_CONTROLLER_ID from .const import DEFAULT_CONTROLLER_ADDR from .const import DEFAULT_CONTROLLER_TIMEZONE from .const import DEFAULT_DOOR1 from .const import DEFAULT_DOOR2 from .const import DEFAULT_DOOR3 from .const import DEFAULT_DOOR4 from .options_flow import UhppotedOptionsFlow from .config import validate_controller_id from .config import validate_door_id from .config import validate_door_duplicates from .config import validate_card_id from .config import validate_all_cards from .config import get_IPv4 from .config import get_all_controllers from .config import get_all_cards from .config import default_card_start_date from .config import default_card_end_date
8,113
v.append({ CONF_CONTROLLER_ID: name, CONF_CONTROLLER_SERIAL_NUMBER: serial_no, CONF_CONTROLLER_ADDR: address, CONF_CONTROLLER_TIMEZONE: timezone, }) self.options.update({CONF_CONTROLLERS: v}) controller['name'] = user_input[CONF_CONTROLLER_ID] controller['configured'] = True return await self.async_step_controller() defaults = { CONF_CONTROLLER_ID: DEFAULT_CONTROLLER_ID, CONF_CONTROLLER_ADDR: DEFAULT_CONTROLLER_ADDR, CONF_CONTROLLER_TIMEZONE: DEFAULT_CONTROLLER_TIMEZONE, } if user_input is not None: for k in [CONF_CONTROLLER_ID, CONF_CONTROLLER_ADDR, CONF_CONTROLLER_TIMEZONE]: if k in user_input: defaults[k] = user_input[k] schema = vol.Schema({ vol.Required(CONF_CONTROLLER_ID, default=defaults[CONF_CONTROLLER_ID]): str, vol.Optional(CONF_CONTROLLER_ADDR, default=defaults[CONF_CONTROLLER_ADDR]): str, vol.Optional(CONF_CONTROLLER_TIMEZONE, default=defaults[CONF_CONTROLLER_TIMEZONE]): str, }) return self.async_show_form(step_id="controller", data_schema=schema, errors=errors, description_placeholders={ "serial_no": controller['serial_no'], }) async def async_step_doors(self, user_input: Optional[Dict[str, Any]] = None): it = next((v for v in self.controllers if not v['doors']), None) if it == None: return await self.async_step_door() else: controller = it['controller'] errors: Dict[str, str] = {} if user_input is not None: if not errors: it['doors'] = { 'doors': [int(f'{v}') for v in user_input['doors']], 'configured': False, } return await self.async_step_doors() doors = [] if re.match('^[1234].*', f"{controller['serial_no']}"): doors.append(1) if re.match('^[234].*', f"{controller['serial_no']}"): doors.append(2) if re.match('^[34].*', f"{controller['serial_no']}"): doors.append(3) if re.match('^[4].*', f"{controller['serial_no']}"): doors.append(4) select = selector.SelectSelectorConfig(options=[{ 'label': f'Door {v}', 'value': f'{v}' } for v in doors], multiple=True, custom_value=False, mode=selector.SelectSelectorMode.LIST) # yapf: disable schema = vol.Schema({ vol.Required('doors', default=[f'{v}' for v in doors]): selector.SelectSelector(select), }) placeholders = { 'controller': f'{controller["name"]}', 'serial_no': f'{controller["serial_no"]}', } return self.async_show_form(step_id="doors", data_schema=schema, errors=errors, description_placeholders=placeholders) async def async_step_door(self, user_input: Optional[Dict[str, Any]] = None): def f(v): return len(v['doors']) > 0 and not v['configured'] it = next((v for v in self.controllers if f(v['doors'])), None) if it == None: return await self.async_step_cards() else: controller = it['controller']['name'] serial_no = it['controller']['serial_no'] doors = it['doors']['doors'] errors: Dict[str, str] = {} if user_input is not None: l = [user_input[f'door{v}_id'] for v in doors] for d in doors: try: k = f'door{d}_id' v = user_input[k] validate_door_id(v, self.options) validate_door_duplicates(v, l) except ValueError as err: errors[k] = f'{err}' if not errors: v = self.options[CONF_DOORS] for d in doors: v.append({ CONF_DOOR_ID: user_input[f'door{d}_id'], CONF_DOOR_CONTROLLER: controller,
_LOGGER = logging.getLogger(__name__) class UhppotedConfigFlow(ConfigFlow, domain=DOMAIN): @staticmethod @callback def async_get_options_flow(config_entry: ConfigEntry) -> UhppotedOptionsFlow: return UhppotedOptionsFlow(config_entry) async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None): defaults = self.hass.data[DOMAIN] if DOMAIN in self.hass.data else {} self.data = {} self.options = {} self.controllers = [] self.doors = [] self.configuration = {'cards': []} self.options.update(get_IPv4(defaults)) self.options.update({ CONF_CONTROLLERS: [], CONF_DOORS: [], }) return await self.async_step_IPv4() async def async_step_IPv4(self, user_input: Optional[Dict[str, Any]] = None): errors: Dict[str, str] = {} if user_input is not None: if not errors: self.options.update(user_input) return await self.async_step_controllers() bind = self.options[CONF_BIND_ADDR] broadcast = self.options[CONF_BROADCAST_ADDR] listen = self.options[CONF_LISTEN_ADDR] debug = self.options[CONF_DEBUG] schema = vol.Schema({ vol.Optional(CONF_BIND_ADDR, default=bind): str, vol.Optional(CONF_BROADCAST_ADDR, default=broadcast): str, vol.Optional(CONF_LISTEN_ADDR, default=listen): str, vol.Optional(CONF_DEBUG, default=debug): bool, }) return self.async_show_form(step_id="IPv4", data_schema=schema, errors=errors) async def async_step_controllers(self, user_input: Optional[Dict[str, Any]] = None): errors: Dict[str, str] = {} if user_input is not None: if not errors: for v in user_input[CONF_CONTROLLERS]: self.controllers.append({ 'controller': { 'name': '', 'serial_no': v, 'configured': False, }, 'doors': None, }) return await self.async_step_controller() controllers = get_all_controllers(self.options) if len(controllers) < 2: for v in controllers: self.controllers.append({ 'controller': { 'name': '', 'serial_no': v, 'configured': False, }, 'doors': None, }) return await self.async_step_controller() schema = vol.Schema({ vol.Required(CONF_CONTROLLERS, default=[f'{v}' for v in controllers]): SelectSelector( SelectSelectorConfig(options=[f'{v}' for v in controllers], multiple=True, custom_value=False, mode=SelectSelectorMode.LIST)), }) return self.async_show_form(step_id="controllers", data_schema=schema, errors=errors) async def async_step_controller(self, user_input: Optional[Dict[str, Any]] = None): it = next((v for v in self.controllers if not v['controller']['configured']), None) if it == None: return await self.async_step_doors() else: controller = it['controller'] errors: Dict[str, str] = {} if user_input is not None: name = user_input[CONF_CONTROLLER_ID] serial_no = controller['serial_no'] address = user_input[CONF_CONTROLLER_ADDR] timezone = user_input[CONF_CONTROLLER_TIMEZONE] try: validate_controller_id(serial_no, name, self.options) except ValueError as err: errors[CONF_CONTROLLER_ID] = f'{err}' if not errors: v = self.options[CONF_CONTROLLERS] v.append({ CONF_CONTROLLER_ID: name, CONF_CONTROLLER_SERIAL_NUMBER: serial_no, CONF_CONTROLLER_ADDR: address, CONF_CONTROLLER_TIMEZONE: timezone, }) self.options.update({CONF_CONTROLLERS: v}) controller['name'] = user_input[CONF_CONTROLLER_ID] controller['configured'] = True return await self.async_step_controller() defaults = { CONF_CONTROLLER_ID: DEFAULT_CONTROLLER_ID, CONF_CONTROLLER_ADDR: DEFAULT_CONTROLLER_ADDR, CONF_CONTROLLER_TIMEZONE: DEFAULT_CONTROLLER_TIMEZONE, } if user_input is not None: for k in [CONF_CONTROLLER_ID, CONF_CONTROLLER_ADDR, CONF_CONTROLLER_TIMEZONE]: if k in user_input: defaults[k] = user_input[k] schema = vol.Schema({ vol.Required(CONF_CONTROLLER_ID, default=defaults[CONF_CONTROLLER_ID]): str, vol.Optional(CONF_CONTROLLER_ADDR, default=defaults[CONF_CONTROLLER_ADDR]): str, vol.Optional(CONF_CONTROLLER_TIMEZONE, default=defaults[CONF_CONTROLLER_TIMEZONE]): str, }) return self.async_show_form(step_id="controller", data_schema=schema, errors=errors, description_placeholders={ "serial_no": controller['serial_no'], }) async def async_step_doors(self, user_input: Optional[Dict[str, Any]] = None): it = next((v for v in self.controllers if not v['doors']), None) if it == None: return await self.async_step_door() else: controller = it['controller'] errors: Dict[str, str] = {} if user_input is not None: if not errors: it['doors'] = { 'doors': [int(f'{v}') for v in user_input['doors']], 'configured': False, } return await self.async_step_doors() doors = [] if re.match('^[1234].*', f"{controller['serial_no']}"): doors.append(1) if re.match('^[234].*', f"{controller['serial_no']}"): doors.append(2) if re.match('^[34].*', f"{controller['serial_no']}"): doors.append(3) if re.match('^[4].*', f"{controller['serial_no']}"): doors.append(4) select = selector.SelectSelectorConfig(options=[{ 'label': f'Door {v}', 'value': f'{v}' } for v in doors], multiple=True, custom_value=False, mode=selector.SelectSelectorMode.LIST) # yapf: disable schema = vol.Schema({ vol.Required('doors', default=[f'{v}' for v in doors]): selector.SelectSelector(select), }) placeholders = { 'controller': f'{controller["name"]}', 'serial_no': f'{controller["serial_no"]}', } return self.async_show_form(step_id="doors", data_schema=schema, errors=errors, description_placeholders=placeholders) async def async_step_door(self, user_input: Optional[Dict[str, Any]] = None): def f(v): return len(v['doors']) > 0 and not v['configured'] it = next((v for v in self.controllers if f(v['doors'])), None) if it == None: return await self.async_step_cards() else: controller = it['controller']['name'] serial_no = it['controller']['serial_no'] doors = it['doors']['doors'] errors: Dict[str, str] = {} if user_input is not None: l = [user_input[f'door{v}_id'] for v in doors] for d in doors: try: k = f'door{d}_id' v = user_input[k] validate_door_id(v, self.options) validate_door_duplicates(v, l) except ValueError as err: errors[k] = f'{err}' if not errors: v = self.options[CONF_DOORS] for d in doors: v.append({ CONF_DOOR_ID: user_input[f'door{d}_id'], CONF_DOOR_CONTROLLER: controller,
CONF_DOOR_NUMBER: int(f'{d}'),
13
2023-11-06 18:46:49+00:00
12k
shadowpa0327/FLORA
main.py
[ { "identifier": "AverageMeter", "path": "my_meter.py", "snippet": "class AverageMeter:\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self._world_size = dist.get_world_size()\n self.reset()\n\n def reset(self):\n # local\n s...
import os import time import random import argparse import datetime import numpy as np import torch import torch.backends.cudnn as cudnn import torch.distributed as dist import wandb from collections import defaultdict from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy from timm.utils import accuracy from my_meter import AverageMeter from config import get_config from models import build_model from data import build_loader from lr_scheduler import build_scheduler from optimizer import build_optimizer from logger import create_logger from utils import load_checkpoint, load_pretrained, save_checkpoint,\ NativeScalerWithGradNormCount,\ auto_resume_helper, is_main_process,\ get_git_info, run_cmd from nas_utils import build_low_rank_search_space
7,863
"--opts", help="Modify config options by adding 'KEY VALUE' pairs. ", default=None, nargs='+', ) # easy config modification parser.add_argument('--batch-size', type=int, help="batch size for single GPU") parser.add_argument('--data-path', type=str, help='path to dataset') parser.add_argument('--pretrained', help='pretrained weight from checkpoint, could be imagenet22k pretrained weight') parser.add_argument('--resume', help='resume from checkpoint') parser.add_argument('--accumulation-steps', type=int, help="gradient accumulation steps") parser.add_argument('--use-checkpoint', action='store_true', help="whether to use gradient checkpointing to save memory") parser.add_argument('--disable_amp', action='store_true', help='Disable pytorch amp') parser.add_argument('--output', default='output', type=str, metavar='PATH', help='root of output folder, the full path is <output>/<model_name>/<tag> (default: output)') parser.add_argument('--tag', help='tag of experiment') parser.add_argument('--eval', action='store_true', help='Perform evaluation only') parser.add_argument('--throughput', action='store_true', help='Test throughput only') parser.add_argument('--use-sync-bn', action='store_true', default=False, help='sync bn') parser.add_argument('--use-wandb', action='store_true', default=False, help='use wandb to record log') # distributed training parser.add_argument("--local_rank", type=int, help='local rank for DistributedDataParallel') # NAS parser.add_argument("--lsss", action='store_true', help = 'train only the local supernet', default=False) parser.add_argument("--lsss-bid", type = int, help = "block id for the target transformer blocks", default = -1) args = parser.parse_args() config = get_config(args) return args, config def main(args, config): dataset_train, dataset_val, data_loader_train, data_loader_val, mixup_fn = build_loader( config) supernet_config = config.NAS.SEARCH_SPACE smallest_config = [] for ratios in supernet_config: smallest_config.append(ratios[0]) logger.info(f"Creating model:{config.MODEL.TYPE}/{config.MODEL.NAME}") model = build_model(config) model.cuda() if args.use_sync_bn: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) logger.info(str(model)) optimizer = build_optimizer(config, model) if 'classic' in config.MODEL.TYPE: model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[config.LOCAL_RANK], broadcast_buffers=False, find_unused_parameters = True) else: model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[config.LOCAL_RANK], broadcast_buffers=False, find_unused_parameters = False) loss_scaler = NativeScalerWithGradNormCount() model_without_ddp = model.module low_rank_search_space = build_low_rank_search_space(args, config) if config.NAS.ENABLE: if config.NAS.INIT_CONFIG is None: cfg = low_rank_search_space.get_smallest_config() else: cfg = config.NAS.INIT_CONFIG model_without_ddp.set_sample_config(cfg) if config.NAS.LSSS.ENABLE: logger.info(f"=> Now training the local supernet of block-{config.NAS.LSSS.BLOCK_ID}") else: logger.info(f"=> Srarting supernet training !") logger.info(f"") logger.info(f"=> Set init subnet config to be {cfg}") logger.info(str(model)) n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) logger.info(f"number of params: {n_parameters}") if hasattr(model_without_ddp, 'flops'): flops = model_without_ddp.flops() logger.info(f"number of GFLOPs: {flops / 1e9}") lr_scheduler = build_scheduler(config, optimizer, len( data_loader_train) // config.TRAIN.ACCUMULATION_STEPS) if config.DISTILL.ENABLED: # we disable MIXUP and CUTMIX when knowledge distillation assert len( config.DISTILL.TEACHER_LOGITS_PATH) > 0, "Please fill in DISTILL.TEACHER_LOGITS_PATH" criterion = torch.nn.CrossEntropyLoss(reduction='mean') else: if config.AUG.MIXUP > 0.: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif config.MODEL.LABEL_SMOOTHING > 0.: criterion = LabelSmoothingCrossEntropy( smoothing=config.MODEL.LABEL_SMOOTHING) else: criterion = torch.nn.CrossEntropyLoss() max_accuracy = 0.0 if config.TRAIN.AUTO_RESUME:
# -------------------------------------------------------- # Based on the code: TinyViT # (https://github.com/microsoft/Cream/tree/main/TinyViT) # Add Low Rank Supernet Training # -------------------------------------------------------- try: except ImportError: wandb = None NORM_ITER_LEN = 100 def parse_option(): parser = argparse.ArgumentParser( 'Swin Transformer training and evaluation script', add_help=False) parser.add_argument('--cfg', type=str, required=True, metavar="FILE", help='path to config file', ) parser.add_argument( "--opts", help="Modify config options by adding 'KEY VALUE' pairs. ", default=None, nargs='+', ) # easy config modification parser.add_argument('--batch-size', type=int, help="batch size for single GPU") parser.add_argument('--data-path', type=str, help='path to dataset') parser.add_argument('--pretrained', help='pretrained weight from checkpoint, could be imagenet22k pretrained weight') parser.add_argument('--resume', help='resume from checkpoint') parser.add_argument('--accumulation-steps', type=int, help="gradient accumulation steps") parser.add_argument('--use-checkpoint', action='store_true', help="whether to use gradient checkpointing to save memory") parser.add_argument('--disable_amp', action='store_true', help='Disable pytorch amp') parser.add_argument('--output', default='output', type=str, metavar='PATH', help='root of output folder, the full path is <output>/<model_name>/<tag> (default: output)') parser.add_argument('--tag', help='tag of experiment') parser.add_argument('--eval', action='store_true', help='Perform evaluation only') parser.add_argument('--throughput', action='store_true', help='Test throughput only') parser.add_argument('--use-sync-bn', action='store_true', default=False, help='sync bn') parser.add_argument('--use-wandb', action='store_true', default=False, help='use wandb to record log') # distributed training parser.add_argument("--local_rank", type=int, help='local rank for DistributedDataParallel') # NAS parser.add_argument("--lsss", action='store_true', help = 'train only the local supernet', default=False) parser.add_argument("--lsss-bid", type = int, help = "block id for the target transformer blocks", default = -1) args = parser.parse_args() config = get_config(args) return args, config def main(args, config): dataset_train, dataset_val, data_loader_train, data_loader_val, mixup_fn = build_loader( config) supernet_config = config.NAS.SEARCH_SPACE smallest_config = [] for ratios in supernet_config: smallest_config.append(ratios[0]) logger.info(f"Creating model:{config.MODEL.TYPE}/{config.MODEL.NAME}") model = build_model(config) model.cuda() if args.use_sync_bn: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) logger.info(str(model)) optimizer = build_optimizer(config, model) if 'classic' in config.MODEL.TYPE: model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[config.LOCAL_RANK], broadcast_buffers=False, find_unused_parameters = True) else: model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[config.LOCAL_RANK], broadcast_buffers=False, find_unused_parameters = False) loss_scaler = NativeScalerWithGradNormCount() model_without_ddp = model.module low_rank_search_space = build_low_rank_search_space(args, config) if config.NAS.ENABLE: if config.NAS.INIT_CONFIG is None: cfg = low_rank_search_space.get_smallest_config() else: cfg = config.NAS.INIT_CONFIG model_without_ddp.set_sample_config(cfg) if config.NAS.LSSS.ENABLE: logger.info(f"=> Now training the local supernet of block-{config.NAS.LSSS.BLOCK_ID}") else: logger.info(f"=> Srarting supernet training !") logger.info(f"") logger.info(f"=> Set init subnet config to be {cfg}") logger.info(str(model)) n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) logger.info(f"number of params: {n_parameters}") if hasattr(model_without_ddp, 'flops'): flops = model_without_ddp.flops() logger.info(f"number of GFLOPs: {flops / 1e9}") lr_scheduler = build_scheduler(config, optimizer, len( data_loader_train) // config.TRAIN.ACCUMULATION_STEPS) if config.DISTILL.ENABLED: # we disable MIXUP and CUTMIX when knowledge distillation assert len( config.DISTILL.TEACHER_LOGITS_PATH) > 0, "Please fill in DISTILL.TEACHER_LOGITS_PATH" criterion = torch.nn.CrossEntropyLoss(reduction='mean') else: if config.AUG.MIXUP > 0.: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif config.MODEL.LABEL_SMOOTHING > 0.: criterion = LabelSmoothingCrossEntropy( smoothing=config.MODEL.LABEL_SMOOTHING) else: criterion = torch.nn.CrossEntropyLoss() max_accuracy = 0.0 if config.TRAIN.AUTO_RESUME:
resume_file = auto_resume_helper(config.OUTPUT)
11
2023-11-03 09:54:45+00:00
12k
fw-ai/fireworks_poe_bot
fireworks_poe_bot/__main__.py
[ { "identifier": "FireworksPoeTextBot", "path": "fireworks_poe_bot/fw_poe_text_bot.py", "snippet": "class FireworksPoeTextBot(PoeBot):\n def __init__(\n self,\n model: str,\n api_key: str,\n environment: str,\n deployment: str,\n server_version: str,\n ...
from fireworks_poe_bot.fw_poe_text_bot import FireworksPoeTextBot from fireworks_poe_bot.fw_poe_image_bot import FireworksPoeImageBot from fireworks_poe_bot.fw_poe_qr_bot import FireworksPoeQRBot from fireworks_poe_bot.logging import UVICORN_LOGGING_CONFIG from fireworks_poe_bot.plugin import LoggingPlugin, register_logging_plugin, BOT_PLUGINS, log_info from dataclasses import dataclass from typing import Any, Dict from .fastapi_poe import make_app import argparse import uvicorn import logging import os import json
10,539
@dataclass class ServerArgs: host: str = "0.0.0.0" port: int = 80 config_file_path: str = "config.json" environment: str = "" deployment: str = "poe-omnibot" class PyLoggingPlugin(LoggingPlugin): def log_warn(self, payload: Dict[str, Any]): logging.warning(payload) def log_info(self, payload: Dict[str, Any]): logging.info(payload) def log_error(self, payload: Dict[str, Any]): logging.error(payload) def main(args=None): if args is None: parser = argparse.ArgumentParser( prog="fireworks_poe_bot", description=f""" Fireworks LLM Poe Server Bot Copyright (c) 2023 Fireworks.ai, Inc. and affiliates. """, ) # Server args. server_args = ServerArgs() server_group = parser.add_argument_group("server", "Server arguments") server_group.add_argument("--host", type=str, default=server_args.host) server_group.add_argument("-p", "--port", type=int, default=server_args.port) server_group.add_argument( "-c", "--config-file-path", type=str, default=server_args.config_file_path ) server_group.add_argument( "-e", "--environment", type=str, default=server_args.environment ) server_group.add_argument( "-d", "--deployment", type=str, default=server_args.deployment ) args = parser.parse_args() # Parse arguments. for k, v in vars(args).items(): for g in [server_args]: if hasattr(g, k): setattr(g, k, v) break else: assert k in ["print_supported_models"], f"Unknown argument {k}" # Register default logging plugin register_logging_plugin(PyLoggingPlugin()) # Load bots from config with open(args.config_file_path) as f: config = json.load(f) remaining_config_keys = set(config.keys()) bots = {} for plugin in BOT_PLUGINS: if plugin.config_key in config: remaining_config_keys.remove(plugin.config_key) for config_dict in config[plugin.config_key]: bot_config = plugin.BotConfigClass(**config_dict) model_fqn = bot_config.model_fqn ctor_dict = bot_config.dict() for k in list(ctor_dict.keys()): if k.startswith("SERVER_"): ctor_dict.pop(k) bots[model_fqn] = plugin.BotPluginClass( environment=args.environment, deployment=args.deployment, server_version="0.0.1", # FIXME: versioneer? **ctor_dict ) if len(remaining_config_keys) > 0: raise ValueError( f"Unknown config keys: {remaining_config_keys}, supported keys: {set([plugin.config_key for plugin in BOT_PLUGINS])}" ) log_info({'message': f"Loaded bots: {bots}"}) assert ( len(bots) > 0 ), "No bots specified, use --text-models or --image-models to specify models to serve"
@dataclass class ServerArgs: host: str = "0.0.0.0" port: int = 80 config_file_path: str = "config.json" environment: str = "" deployment: str = "poe-omnibot" class PyLoggingPlugin(LoggingPlugin): def log_warn(self, payload: Dict[str, Any]): logging.warning(payload) def log_info(self, payload: Dict[str, Any]): logging.info(payload) def log_error(self, payload: Dict[str, Any]): logging.error(payload) def main(args=None): if args is None: parser = argparse.ArgumentParser( prog="fireworks_poe_bot", description=f""" Fireworks LLM Poe Server Bot Copyright (c) 2023 Fireworks.ai, Inc. and affiliates. """, ) # Server args. server_args = ServerArgs() server_group = parser.add_argument_group("server", "Server arguments") server_group.add_argument("--host", type=str, default=server_args.host) server_group.add_argument("-p", "--port", type=int, default=server_args.port) server_group.add_argument( "-c", "--config-file-path", type=str, default=server_args.config_file_path ) server_group.add_argument( "-e", "--environment", type=str, default=server_args.environment ) server_group.add_argument( "-d", "--deployment", type=str, default=server_args.deployment ) args = parser.parse_args() # Parse arguments. for k, v in vars(args).items(): for g in [server_args]: if hasattr(g, k): setattr(g, k, v) break else: assert k in ["print_supported_models"], f"Unknown argument {k}" # Register default logging plugin register_logging_plugin(PyLoggingPlugin()) # Load bots from config with open(args.config_file_path) as f: config = json.load(f) remaining_config_keys = set(config.keys()) bots = {} for plugin in BOT_PLUGINS: if plugin.config_key in config: remaining_config_keys.remove(plugin.config_key) for config_dict in config[plugin.config_key]: bot_config = plugin.BotConfigClass(**config_dict) model_fqn = bot_config.model_fqn ctor_dict = bot_config.dict() for k in list(ctor_dict.keys()): if k.startswith("SERVER_"): ctor_dict.pop(k) bots[model_fqn] = plugin.BotPluginClass( environment=args.environment, deployment=args.deployment, server_version="0.0.1", # FIXME: versioneer? **ctor_dict ) if len(remaining_config_keys) > 0: raise ValueError( f"Unknown config keys: {remaining_config_keys}, supported keys: {set([plugin.config_key for plugin in BOT_PLUGINS])}" ) log_info({'message': f"Loaded bots: {bots}"}) assert ( len(bots) > 0 ), "No bots specified, use --text-models or --image-models to specify models to serve"
app = make_app(bots, allow_without_key=True)
8
2023-11-03 23:24:23+00:00
12k
Fsoft-AIC/LSDM
util/model_util.py
[ { "identifier": "SceneDiffusionModel", "path": "model/sdm.py", "snippet": "class SceneDiffusionModel(nn.Module):\n def __init__(self, seg_len=256, modality='text', clip_version='ViT-B/32', clip_dim=768, dropout=0.1, n_layer=6, n_head=8, f_vert=64, dim_ff=512,\n cat_emb=32, mesh_ds_dir...
from model.sdm import SceneDiffusionModel from diffusion import gaussian_diffusion as gd from diffusion.respace import SpacedDiffusion, space_timesteps from util.fixseed import fixseed from run.train_platforms import ClearmlPlatform, TensorboardPlatform, NoPlatform # required for the eval operation
7,854
diffusion = create_gaussian_diffusion(get_default_diffusion()) return model, diffusion def get_default_model_proxd(): return { 'seq_len': 256, 'modality': 'text', 'clip_version': 'ViT-B/32', 'clip_dim': 512, 'dropout': 0.1, 'n_layer': 6, 'n_head': 8, 'f_vert': 64, 'dim_ff': 512, 'd_hid': 256, 'mesh_ds_dir': "data/mesh_ds", 'posa_path': None, 'latent_dim': 128, 'pcd_dim': 3, 'cond_mask_prob': 1.0, 'device': 0, 'vert_dims': 655, 'obj_cat': 8, 'data_rep': 'rot6d', 'njoints': 251, } def get_default_model_humanise(): return { 'seq_len': 256, 'modality': 'text', 'clip_version': 'ViT-B/32', 'clip_dim': 512, 'dropout': 0.1, 'n_layer': 6, 'n_head': 8, 'f_vert': 64, 'dim_ff': 512, 'd_hid': 256, 'mesh_ds_dir': "data/mesh_ds", 'posa_path': None, 'latent_dim': 128, 'pcd_dim': 3, 'cond_mask_prob': 1.0, 'device': 0, 'vert_dims': 655, 'obj_cat': 8, 'data_rep': 'rot6d', 'njoints': 251, 'max_cats': 11, } def get_default_diffusion(): args = { "lambda_fc": 0.0, "lambda_rcxyz": 0.0, "lambda_vel": 0.0, "lambda_cat": 0.1, "noise_schedule": "cosine", "sigma_small": True, } return args def get_model_args(): return { "arch": "trans_enc", "batch_size": 64, "cond_mask_prob": 0.1, "cuda": True, "data_dir": "", "dataset": "humanml", "device": 0, "diffusion_steps": 1000, "emb_trans_dec": False, "eval_batch_size": 32, "eval_during_training": False, "eval_num_samples": 1000, "eval_rep_times": 3, "eval_split": "test", "lambda_fc": 0.0, "lambda_rcxyz": 0.0, "lambda_vel": 0.0, "lambda_cat": 0.05, "latent_dim": 512, "layers": 8, "log_interval": 1000, "lr": 0.0001, "lr_anneal_steps": 0, "noise_schedule": "cosine", "num_frames": 60, "num_steps": 600000, "overwrite": False, "resume_checkpoint": "", "save_dir": "save/my_humanml_trans_enc_512", "save_interval": 50000, "seed": 10, "sigma_small": True, "train_platform_type": "NoPlatform", "unconstrained": False, "weight_decay": 0.0 } def create_gaussian_diffusion(args): # default params predict_xstart = True # we always predict x_start (a.k.a. x0), that's our deal! steps = 1000 scale_beta = 1. # no scaling timestep_respacing = '' # can be used for ddim sampling, we don't use it. learn_sigma = False rescale_timesteps = False betas = gd.get_named_beta_schedule(args['noise_schedule'], steps, scale_beta) loss_type = gd.LossType.MSE if not timestep_respacing: timestep_respacing = [steps]
def load_model_wo_clip(model, state_dict): missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False) assert len(unexpected_keys) == 0 assert all([k.startswith('clip_model.') for k in missing_keys]) def create_model_and_diffusion(datatype): # model = SceneDiffusionModel(**get_model_args(args, data)) if datatype == "proxd": model = SceneDiffusionModel(**get_default_model_proxd()) else: model = SceneDiffusionModel(**get_default_model_humanise()) diffusion = create_gaussian_diffusion(get_default_diffusion()) return model, diffusion def get_default_model_proxd(): return { 'seq_len': 256, 'modality': 'text', 'clip_version': 'ViT-B/32', 'clip_dim': 512, 'dropout': 0.1, 'n_layer': 6, 'n_head': 8, 'f_vert': 64, 'dim_ff': 512, 'd_hid': 256, 'mesh_ds_dir': "data/mesh_ds", 'posa_path': None, 'latent_dim': 128, 'pcd_dim': 3, 'cond_mask_prob': 1.0, 'device': 0, 'vert_dims': 655, 'obj_cat': 8, 'data_rep': 'rot6d', 'njoints': 251, } def get_default_model_humanise(): return { 'seq_len': 256, 'modality': 'text', 'clip_version': 'ViT-B/32', 'clip_dim': 512, 'dropout': 0.1, 'n_layer': 6, 'n_head': 8, 'f_vert': 64, 'dim_ff': 512, 'd_hid': 256, 'mesh_ds_dir': "data/mesh_ds", 'posa_path': None, 'latent_dim': 128, 'pcd_dim': 3, 'cond_mask_prob': 1.0, 'device': 0, 'vert_dims': 655, 'obj_cat': 8, 'data_rep': 'rot6d', 'njoints': 251, 'max_cats': 11, } def get_default_diffusion(): args = { "lambda_fc": 0.0, "lambda_rcxyz": 0.0, "lambda_vel": 0.0, "lambda_cat": 0.1, "noise_schedule": "cosine", "sigma_small": True, } return args def get_model_args(): return { "arch": "trans_enc", "batch_size": 64, "cond_mask_prob": 0.1, "cuda": True, "data_dir": "", "dataset": "humanml", "device": 0, "diffusion_steps": 1000, "emb_trans_dec": False, "eval_batch_size": 32, "eval_during_training": False, "eval_num_samples": 1000, "eval_rep_times": 3, "eval_split": "test", "lambda_fc": 0.0, "lambda_rcxyz": 0.0, "lambda_vel": 0.0, "lambda_cat": 0.05, "latent_dim": 512, "layers": 8, "log_interval": 1000, "lr": 0.0001, "lr_anneal_steps": 0, "noise_schedule": "cosine", "num_frames": 60, "num_steps": 600000, "overwrite": False, "resume_checkpoint": "", "save_dir": "save/my_humanml_trans_enc_512", "save_interval": 50000, "seed": 10, "sigma_small": True, "train_platform_type": "NoPlatform", "unconstrained": False, "weight_decay": 0.0 } def create_gaussian_diffusion(args): # default params predict_xstart = True # we always predict x_start (a.k.a. x0), that's our deal! steps = 1000 scale_beta = 1. # no scaling timestep_respacing = '' # can be used for ddim sampling, we don't use it. learn_sigma = False rescale_timesteps = False betas = gd.get_named_beta_schedule(args['noise_schedule'], steps, scale_beta) loss_type = gd.LossType.MSE if not timestep_respacing: timestep_respacing = [steps]
return SpacedDiffusion(
2
2023-11-06 07:55:51+00:00
12k
Harvard-Ophthalmology-AI-Lab/FairSeg
SAMed/segment_anything/automatic_mask_generator.py
[ { "identifier": "Sam", "path": "SAMed/segment_anything/modeling/sam.py", "snippet": "class Sam(nn.Module):\n mask_threshold: float = 0.0\n image_format: str = \"RGB\"\n\n def __init__(\n self,\n image_encoder: ImageEncoderViT,\n prompt_encoder: PromptEncoder,\n mask_...
import numpy as np import torch import cv2 # type: ignore # noqa: F401 from torchvision.ops.boxes import batched_nms, box_area # type: ignore from typing import Any, Dict, List, Optional, Tuple from .modeling import Sam from .predictor import SamPredictor from .utils.amg import ( MaskData, area_from_rle, batch_iterator, batched_mask_to_box, box_xyxy_to_xywh, build_all_layer_point_grids, calculate_stability_score, coco_encode_rle, generate_crop_boxes, is_box_near_crop_edge, mask_to_rle_pytorch, remove_small_regions, rle_to_mask, uncrop_boxes_xyxy, uncrop_masks, uncrop_points, ) from pycocotools import mask as mask_utils # type: ignore # noqa: F401
10,171
Generates a grid of point prompts over the image, then filters low quality and duplicate masks. The default settings are chosen for SAM with a ViT-H backbone. Arguments: model (Sam): The SAM model to use for mask prediction. points_per_side (int or None): The number of points to be sampled along one side of the image. The total number of points is points_per_side**2. If None, 'point_grids' must provide explicit point sampling. points_per_batch (int): Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU memory. pred_iou_thresh (float): A filtering threshold in [0,1], using the model's predicted mask quality. stability_score_thresh (float): A filtering threshold in [0,1], using the stability of the mask under changes to the cutoff used to binarize the model's mask predictions. stability_score_offset (float): The amount to shift the cutoff when calculated the stability score. box_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks. crops_n_layers (int): If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops. crops_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks between different crops. crop_overlap_ratio (float): Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. crop_n_points_downscale_factor (int): The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n. point_grids (list(np.ndarray) or None): A list over explicit grids of points used for sampling, normalized to [0,1]. The nth grid in the list is used in the nth crop layer. Exclusive with points_per_side. min_mask_region_area (int): If >0, postprocessing will be applied to remove disconnected regions and holes in masks with area smaller than min_mask_region_area. Requires opencv. output_mode (str): The form masks are returned in. Can be 'binary_mask', 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. For large resolutions, 'binary_mask' may consume large amounts of memory. """ assert (points_per_side is None) != ( point_grids is None ), "Exactly one of points_per_side or point_grid must be provided." if points_per_side is not None: self.point_grids = build_all_layer_point_grids( points_per_side, crop_n_layers, crop_n_points_downscale_factor, ) elif point_grids is not None: self.point_grids = point_grids else: raise ValueError("Can't have both points_per_side and point_grid be None.") assert output_mode in [ "binary_mask", "uncompressed_rle", "coco_rle", ], f"Unknown output_mode {output_mode}." if output_mode == "coco_rle": if min_mask_region_area > 0: self.predictor = SamPredictor(model) self.points_per_batch = points_per_batch self.pred_iou_thresh = pred_iou_thresh self.stability_score_thresh = stability_score_thresh self.stability_score_offset = stability_score_offset self.box_nms_thresh = box_nms_thresh self.crop_n_layers = crop_n_layers self.crop_nms_thresh = crop_nms_thresh self.crop_overlap_ratio = crop_overlap_ratio self.crop_n_points_downscale_factor = crop_n_points_downscale_factor self.min_mask_region_area = min_mask_region_area self.output_mode = output_mode @torch.no_grad() def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: """ Generates masks for the given image. Arguments: image (np.ndarray): The image to generate masks for, in HWC uint8 format. Returns: list(dict(str, any)): A list over records for masks. Each record is a dict containing the following keys: segmentation (dict(str, any) or np.ndarray): The mask. If output_mode='binary_mask', is an array of shape HW. Otherwise, is a dictionary containing the RLE. bbox (list(float)): The box around the mask, in XYWH format. area (int): The area in pixels of the mask. predicted_iou (float): The model's own prediction of the mask's quality. This is filtered by the pred_iou_thresh parameter. point_coords (list(list(float))): The point coordinates input to the model to generate this mask. stability_score (float): A measure of the mask's quality. This is filtered on using the stability_score_thresh parameter. crop_box (list(float)): The crop of the image used to generate the mask, given in XYWH format. """ # Generate masks mask_data = self._generate_masks(image) # Filter small disconnected regions and holes in masks if self.min_mask_region_area > 0: mask_data = self.postprocess_small_regions( mask_data, self.min_mask_region_area, max(self.box_nms_thresh, self.crop_nms_thresh), ) # Encode masks if self.output_mode == "coco_rle": mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]] elif self.output_mode == "binary_mask":
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. class SamAutomaticMaskGenerator: def __init__( self, model: Sam, points_per_side: Optional[int] = 32, points_per_batch: int = 64, pred_iou_thresh: float = 0.88, stability_score_thresh: float = 0.95, stability_score_offset: float = 1.0, box_nms_thresh: float = 0.7, crop_n_layers: int = 0, crop_nms_thresh: float = 0.7, crop_overlap_ratio: float = 512 / 1500, crop_n_points_downscale_factor: int = 1, point_grids: Optional[List[np.ndarray]] = None, min_mask_region_area: int = 0, output_mode: str = "binary_mask", ) -> None: """ Using a SAM model, generates masks for the entire image. Generates a grid of point prompts over the image, then filters low quality and duplicate masks. The default settings are chosen for SAM with a ViT-H backbone. Arguments: model (Sam): The SAM model to use for mask prediction. points_per_side (int or None): The number of points to be sampled along one side of the image. The total number of points is points_per_side**2. If None, 'point_grids' must provide explicit point sampling. points_per_batch (int): Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU memory. pred_iou_thresh (float): A filtering threshold in [0,1], using the model's predicted mask quality. stability_score_thresh (float): A filtering threshold in [0,1], using the stability of the mask under changes to the cutoff used to binarize the model's mask predictions. stability_score_offset (float): The amount to shift the cutoff when calculated the stability score. box_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks. crops_n_layers (int): If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops. crops_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks between different crops. crop_overlap_ratio (float): Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. crop_n_points_downscale_factor (int): The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n. point_grids (list(np.ndarray) or None): A list over explicit grids of points used for sampling, normalized to [0,1]. The nth grid in the list is used in the nth crop layer. Exclusive with points_per_side. min_mask_region_area (int): If >0, postprocessing will be applied to remove disconnected regions and holes in masks with area smaller than min_mask_region_area. Requires opencv. output_mode (str): The form masks are returned in. Can be 'binary_mask', 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. For large resolutions, 'binary_mask' may consume large amounts of memory. """ assert (points_per_side is None) != ( point_grids is None ), "Exactly one of points_per_side or point_grid must be provided." if points_per_side is not None: self.point_grids = build_all_layer_point_grids( points_per_side, crop_n_layers, crop_n_points_downscale_factor, ) elif point_grids is not None: self.point_grids = point_grids else: raise ValueError("Can't have both points_per_side and point_grid be None.") assert output_mode in [ "binary_mask", "uncompressed_rle", "coco_rle", ], f"Unknown output_mode {output_mode}." if output_mode == "coco_rle": if min_mask_region_area > 0: self.predictor = SamPredictor(model) self.points_per_batch = points_per_batch self.pred_iou_thresh = pred_iou_thresh self.stability_score_thresh = stability_score_thresh self.stability_score_offset = stability_score_offset self.box_nms_thresh = box_nms_thresh self.crop_n_layers = crop_n_layers self.crop_nms_thresh = crop_nms_thresh self.crop_overlap_ratio = crop_overlap_ratio self.crop_n_points_downscale_factor = crop_n_points_downscale_factor self.min_mask_region_area = min_mask_region_area self.output_mode = output_mode @torch.no_grad() def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: """ Generates masks for the given image. Arguments: image (np.ndarray): The image to generate masks for, in HWC uint8 format. Returns: list(dict(str, any)): A list over records for masks. Each record is a dict containing the following keys: segmentation (dict(str, any) or np.ndarray): The mask. If output_mode='binary_mask', is an array of shape HW. Otherwise, is a dictionary containing the RLE. bbox (list(float)): The box around the mask, in XYWH format. area (int): The area in pixels of the mask. predicted_iou (float): The model's own prediction of the mask's quality. This is filtered by the pred_iou_thresh parameter. point_coords (list(list(float))): The point coordinates input to the model to generate this mask. stability_score (float): A measure of the mask's quality. This is filtered on using the stability_score_thresh parameter. crop_box (list(float)): The crop of the image used to generate the mask, given in XYWH format. """ # Generate masks mask_data = self._generate_masks(image) # Filter small disconnected regions and holes in masks if self.min_mask_region_area > 0: mask_data = self.postprocess_small_regions( mask_data, self.min_mask_region_area, max(self.box_nms_thresh, self.crop_nms_thresh), ) # Encode masks if self.output_mode == "coco_rle": mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]] elif self.output_mode == "binary_mask":
mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]]
14
2023-11-03 17:05:40+00:00
12k
microsoft/PLEX
scripts/exps_on_MW.py
[ { "identifier": "pretrain_EX", "path": "PLEX/pretraining_EX.py", "snippet": "def pretrain_EX(cmdline_args):\n os.environ[\"NCCL_DEBUG\"] = \"INFO\"\n print(\"=== Pretraining the Execuctor ===\")\n parser = argparse.ArgumentParser()\n\n # Add all relevant command-line arguments\n add_commo...
from PLEX.pretraining_EX import pretrain_EX from PLEX.pretraining_PL import pretrain_PL from PLEX.finetuning import finetune import argparse import random
7,451
parser.add_argument("-w", "--num_workers", type=int, default=0, help = "Number of worker for running the evaluation episodes. NOTE: applicable only if the training stage is 'ft' (finetuning).") args = parser.parse_args() common_flags = ['--relative_position_encodings', '--bc_learning_mode'] common_args = { 'seed': str(random.randint(0, 1000000)), 'data_dir': args.data_dir, 'log_dir': args.log_dir, 'robot': 'Sawyer', 'camera_names': 'corner', 'modalities_to_mask': 'proprio,action', 'record_camera': 'corner', 'image_size': '84', 'reward_type': 'sparse', 'image_encoder_arch': 'resnet18', 'impute_style': 'trainable', 'embed_dim': '256', 'future_step': '1', 'activation_function': 'relu', 'device': 'cuda', 'dropout': '0.2', 'weight_decay': '1e-05', 'warmup_steps': '200', 'batch_size': '256', 'action_output_type': 'deterministic', 'model': 'PLEX', 'obs_pred.n_layer': '3', 'obs_pred.n_head': '4', 'obs_pred.K': '30', 'inv_d_pred.n_layer': '3', 'inv_d_pred.n_head': '4', 'inv_d_pred.K': '30' } common_pretraining_flags = ['--no_video'] common_pretraining_args = { 'pretrain_learning_rate': '0.0005', 'pretrain_steps_per_iter': '250', 'num_steps_per_ft_eval_iter': '0', 'best_metric': 'evaluation/neg_val_error', 'validation_frac': '1.0', 'validation_samples': '30', # Validation tasks can be any MW tasks -- we don't use validation error to stop training. # We use the target tasks as validation tasks. 'validation_tasks': 'metaworld/hand-insert-v2/--TARGET_ROBOT--/noise0/,metaworld/door-lock-v2/--TARGET_ROBOT--/noise0/,metaworld/door-unlock-v2/--TARGET_ROBOT--/noise0/,metaworld/box-close-v2/--TARGET_ROBOT--/noise0/,metaworld/bin-picking-v2/--TARGET_ROBOT--/noise0/', } cmdline_args = common_flags for k in common_args: cmdline_args.append('--' + k) cmdline_args.append(common_args[k]) if args.training_stage == 'ex': cmdline_args.extend(common_pretraining_flags) for k in common_pretraining_args: cmdline_args.append('--' + k) cmdline_args.append(common_pretraining_args[k]) cmdline_args.extend([ '--max_iters', '10', # To pretrain the executor, use 75 play trajectories per task. '--max_pretrain_trajectories', '75', # During executor pretraining, we adapt both the executor's and the encoder's weights but keep the planner frozen. '--image_encoder_tune_style', 'all', '--obs_pred.transformer_tune_style', 'none', '--inv_d_pred.transformer_tune_style', 'all', # Use the dynamics data from Meta-World ML50's 5 downstream environments. '--noncontextual_pretrain_tasks', 'metaworld/hand-insert-v2/--TARGET_ROBOT--/noise0.5/,metaworld/door-lock-v2/--TARGET_ROBOT--/noise0.5/,metaworld/door-unlock-v2/--TARGET_ROBOT--/noise0.5/,metaworld/box-close-v2/--TARGET_ROBOT--/noise0.5/,metaworld/bin-picking-v2/--TARGET_ROBOT--/noise0.5/', ]) pretrain_EX(cmdline_args) elif args.training_stage == 'pl': cmdline_args.extend(common_pretraining_flags) for k in common_pretraining_args: cmdline_args.append('--' + k) cmdline_args.append(common_pretraining_args[k]) cmdline_args.extend([ '--max_iters', '10', # To pretrain the planner, use all (100) available video demonstrations per task. '--max_pretrain_trajectories', 100, '--context_style', 'first-success', '--context_from_diff_traj', # During planner pretraining, we want to keep the encoder and the executor's weights frozen, adapting only the weights of the planner itself. '--image_encoder_tune_style', 'none', '--obs_pred.transformer_tune_style', 'all', '--inv_d_pred.transformer_tune_style', 'none', # For pretraining, use video demonstrations from Meta-World ML50's 45 pretraining tasks. '--video_tasks', 'metaworld/pick-out-of-hole-v2/Sawyer/noise0/,metaworld/door-open-v2/Sawyer/noise0/,metaworld/pick-place-wall-v2/Sawyer/noise0/,metaworld/assembly-v2/Sawyer/noise0/,metaworld/faucet-close-v2/Sawyer/noise0/,metaworld/coffee-pull-v2/Sawyer/noise0/,metaworld/plate-slide-back-side-v2/Sawyer/noise0/,metaworld/dial-turn-v2/Sawyer/noise0/,metaworld/stick-push-v2/Sawyer/noise0/,metaworld/sweep-into-v2/Sawyer/noise0/,metaworld/handle-pull-side-v2/Sawyer/noise0/,metaworld/drawer-open-v2/Sawyer/noise0/,metaworld/window-open-v2/Sawyer/noise0/,metaworld/button-press-v2/Sawyer/noise0/,metaworld/assembly-v2/Sawyer/noise0/,metaworld/faucet-close-v2/Sawyer/noise0/,metaworld/coffee-pull-v2/Sawyer/noise0/,metaworld/plate-slide-back-side-v2/Sawyer/noise0/,metaworld/dial-turn-v2/Sawyer/noise0/,metaworld/stick-push-v2/Sawyer/noise0/,metaworld/sweep-into-v2/Sawyer/noise0/,metaworld/handle-pull-side-v2/Sawyer/noise0/,metaworld/shelf-place-v2/Sawyer/noise0/,metaworld/basketball-v2/Sawyer/noise0/,metaworld/button-press-topdown-v2/Sawyer/noise0/,metaworld/button-press-topdown-wall-v2/Sawyer/noise0/,metaworld/button-press-wall-v2/Sawyer/noise0/,metaworld/coffee-button-v2/Sawyer/noise0/,metaworld/coffee-push-v2/Sawyer/noise0/,metaworld/disassemble-v2/Sawyer/noise0/,metaworld/door-close-v2/Sawyer/noise0/,metaworld/drawer-close-v2/Sawyer/noise0/,metaworld/faucet-open-v2/Sawyer/noise0/,metaworld/hammer-v2/Sawyer/noise0/,metaworld/handle-press-side-v2/Sawyer/noise0/,metaworld/handle-press-v2/Sawyer/noise0/,metaworld/handle-pull-v2/Sawyer/noise0/,metaworld/lever-pull-v2/Sawyer/noise0/,metaworld/peg-insert-side-v2/Sawyer/noise0/,metaworld/reach-v2/Sawyer/noise0/,metaworld/push-back-v2/Sawyer/noise0/,metaworld/push-v2/Sawyer/noise0/,metaworld/pick-place-v2/Sawyer/noise0/,metaworld/plate-slide-v2/Sawyer/noise0/,metaworld/plate-slide-side-v2/Sawyer/noise0/,metaworld/plate-slide-back-v2/Sawyer/noise0/,metaworld/peg-unplug-side-v2/Sawyer/noise0/,metaworld/soccer-v2/Sawyer/noise0/,metaworld/stick-pull-v2/Sawyer/noise0/,metaworld/push-wall-v2/Sawyer/noise0/,metaworld/reach-wall-v2/Sawyer/noise0/,metaworld/sweep-v2/Sawyer/noise0/,metaworld/window-close-v2/Sawyer/noise0/', '--load_path', args.model_file ]) pretrain_PL(cmdline_args) elif args.training_stage == 'ft': cmdline_args.extend([ '--max_iters', '10', # Use just 10 trajectories of the target task for finetunning, randomly sampled from the set of all (100) of that task's training trajectories. '--max_target_trajectories', '10', '--target_task', args.target_task, '--context_style', 'first-success', '--context_from_diff_traj', # During finetuning we adapt just the last transformer layer of the planner, keeping the planner's other layers as well as the encoder and the executor frozen. # We could adapt other parts of PLEX too, but it's unnecessary to reproduce the PLEX paper's results. '--image_encoder_tune_style', 'none', '--obs_pred.transformer_tune_style', 'last_block', '--inv_d_pred.transformer_tune_style', 'none', '--finetune_learning_rate', '0.0005', '--finetune_steps_per_iter', '100', '--best_metric', 'evaluation/success_rate', '--max_eval_episode_len', '500', '--num_eval_episodes', '50', '--num_eval_workers', str(args.num_workers), # Remove this flag if you don't want videos of evaluation trajectories to be recorded. '--record_video', '--load_path', args.model_file ])
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-s", "--training_stage", type=str, default='ft', help = "The training stage. Can be 'ex' (pretaining the EXecutor), 'pl' (pretraining the PLanner), or 'ft' (finetuning a pretrained PLEX)") parser.add_argument("-d", "--data_dir", type=str, default='store/data', help = "Directory path where the training data is.") parser.add_argument("-l", "--log_dir", type=str, default='store/logs', help = "Directory path where to output logs and model checkpoints.") parser.add_argument("-m", "--model_file", type=str, default=None, help = "Model file path.") parser.add_argument("-t", "--target_task", type=str, default=None, help = "Directory path where the target task's data is. NOTE: applicable only if the training stage is 'ft' (finetuning).") parser.add_argument("-w", "--num_workers", type=int, default=0, help = "Number of worker for running the evaluation episodes. NOTE: applicable only if the training stage is 'ft' (finetuning).") args = parser.parse_args() common_flags = ['--relative_position_encodings', '--bc_learning_mode'] common_args = { 'seed': str(random.randint(0, 1000000)), 'data_dir': args.data_dir, 'log_dir': args.log_dir, 'robot': 'Sawyer', 'camera_names': 'corner', 'modalities_to_mask': 'proprio,action', 'record_camera': 'corner', 'image_size': '84', 'reward_type': 'sparse', 'image_encoder_arch': 'resnet18', 'impute_style': 'trainable', 'embed_dim': '256', 'future_step': '1', 'activation_function': 'relu', 'device': 'cuda', 'dropout': '0.2', 'weight_decay': '1e-05', 'warmup_steps': '200', 'batch_size': '256', 'action_output_type': 'deterministic', 'model': 'PLEX', 'obs_pred.n_layer': '3', 'obs_pred.n_head': '4', 'obs_pred.K': '30', 'inv_d_pred.n_layer': '3', 'inv_d_pred.n_head': '4', 'inv_d_pred.K': '30' } common_pretraining_flags = ['--no_video'] common_pretraining_args = { 'pretrain_learning_rate': '0.0005', 'pretrain_steps_per_iter': '250', 'num_steps_per_ft_eval_iter': '0', 'best_metric': 'evaluation/neg_val_error', 'validation_frac': '1.0', 'validation_samples': '30', # Validation tasks can be any MW tasks -- we don't use validation error to stop training. # We use the target tasks as validation tasks. 'validation_tasks': 'metaworld/hand-insert-v2/--TARGET_ROBOT--/noise0/,metaworld/door-lock-v2/--TARGET_ROBOT--/noise0/,metaworld/door-unlock-v2/--TARGET_ROBOT--/noise0/,metaworld/box-close-v2/--TARGET_ROBOT--/noise0/,metaworld/bin-picking-v2/--TARGET_ROBOT--/noise0/', } cmdline_args = common_flags for k in common_args: cmdline_args.append('--' + k) cmdline_args.append(common_args[k]) if args.training_stage == 'ex': cmdline_args.extend(common_pretraining_flags) for k in common_pretraining_args: cmdline_args.append('--' + k) cmdline_args.append(common_pretraining_args[k]) cmdline_args.extend([ '--max_iters', '10', # To pretrain the executor, use 75 play trajectories per task. '--max_pretrain_trajectories', '75', # During executor pretraining, we adapt both the executor's and the encoder's weights but keep the planner frozen. '--image_encoder_tune_style', 'all', '--obs_pred.transformer_tune_style', 'none', '--inv_d_pred.transformer_tune_style', 'all', # Use the dynamics data from Meta-World ML50's 5 downstream environments. '--noncontextual_pretrain_tasks', 'metaworld/hand-insert-v2/--TARGET_ROBOT--/noise0.5/,metaworld/door-lock-v2/--TARGET_ROBOT--/noise0.5/,metaworld/door-unlock-v2/--TARGET_ROBOT--/noise0.5/,metaworld/box-close-v2/--TARGET_ROBOT--/noise0.5/,metaworld/bin-picking-v2/--TARGET_ROBOT--/noise0.5/', ]) pretrain_EX(cmdline_args) elif args.training_stage == 'pl': cmdline_args.extend(common_pretraining_flags) for k in common_pretraining_args: cmdline_args.append('--' + k) cmdline_args.append(common_pretraining_args[k]) cmdline_args.extend([ '--max_iters', '10', # To pretrain the planner, use all (100) available video demonstrations per task. '--max_pretrain_trajectories', 100, '--context_style', 'first-success', '--context_from_diff_traj', # During planner pretraining, we want to keep the encoder and the executor's weights frozen, adapting only the weights of the planner itself. '--image_encoder_tune_style', 'none', '--obs_pred.transformer_tune_style', 'all', '--inv_d_pred.transformer_tune_style', 'none', # For pretraining, use video demonstrations from Meta-World ML50's 45 pretraining tasks. '--video_tasks', 'metaworld/pick-out-of-hole-v2/Sawyer/noise0/,metaworld/door-open-v2/Sawyer/noise0/,metaworld/pick-place-wall-v2/Sawyer/noise0/,metaworld/assembly-v2/Sawyer/noise0/,metaworld/faucet-close-v2/Sawyer/noise0/,metaworld/coffee-pull-v2/Sawyer/noise0/,metaworld/plate-slide-back-side-v2/Sawyer/noise0/,metaworld/dial-turn-v2/Sawyer/noise0/,metaworld/stick-push-v2/Sawyer/noise0/,metaworld/sweep-into-v2/Sawyer/noise0/,metaworld/handle-pull-side-v2/Sawyer/noise0/,metaworld/drawer-open-v2/Sawyer/noise0/,metaworld/window-open-v2/Sawyer/noise0/,metaworld/button-press-v2/Sawyer/noise0/,metaworld/assembly-v2/Sawyer/noise0/,metaworld/faucet-close-v2/Sawyer/noise0/,metaworld/coffee-pull-v2/Sawyer/noise0/,metaworld/plate-slide-back-side-v2/Sawyer/noise0/,metaworld/dial-turn-v2/Sawyer/noise0/,metaworld/stick-push-v2/Sawyer/noise0/,metaworld/sweep-into-v2/Sawyer/noise0/,metaworld/handle-pull-side-v2/Sawyer/noise0/,metaworld/shelf-place-v2/Sawyer/noise0/,metaworld/basketball-v2/Sawyer/noise0/,metaworld/button-press-topdown-v2/Sawyer/noise0/,metaworld/button-press-topdown-wall-v2/Sawyer/noise0/,metaworld/button-press-wall-v2/Sawyer/noise0/,metaworld/coffee-button-v2/Sawyer/noise0/,metaworld/coffee-push-v2/Sawyer/noise0/,metaworld/disassemble-v2/Sawyer/noise0/,metaworld/door-close-v2/Sawyer/noise0/,metaworld/drawer-close-v2/Sawyer/noise0/,metaworld/faucet-open-v2/Sawyer/noise0/,metaworld/hammer-v2/Sawyer/noise0/,metaworld/handle-press-side-v2/Sawyer/noise0/,metaworld/handle-press-v2/Sawyer/noise0/,metaworld/handle-pull-v2/Sawyer/noise0/,metaworld/lever-pull-v2/Sawyer/noise0/,metaworld/peg-insert-side-v2/Sawyer/noise0/,metaworld/reach-v2/Sawyer/noise0/,metaworld/push-back-v2/Sawyer/noise0/,metaworld/push-v2/Sawyer/noise0/,metaworld/pick-place-v2/Sawyer/noise0/,metaworld/plate-slide-v2/Sawyer/noise0/,metaworld/plate-slide-side-v2/Sawyer/noise0/,metaworld/plate-slide-back-v2/Sawyer/noise0/,metaworld/peg-unplug-side-v2/Sawyer/noise0/,metaworld/soccer-v2/Sawyer/noise0/,metaworld/stick-pull-v2/Sawyer/noise0/,metaworld/push-wall-v2/Sawyer/noise0/,metaworld/reach-wall-v2/Sawyer/noise0/,metaworld/sweep-v2/Sawyer/noise0/,metaworld/window-close-v2/Sawyer/noise0/', '--load_path', args.model_file ]) pretrain_PL(cmdline_args) elif args.training_stage == 'ft': cmdline_args.extend([ '--max_iters', '10', # Use just 10 trajectories of the target task for finetunning, randomly sampled from the set of all (100) of that task's training trajectories. '--max_target_trajectories', '10', '--target_task', args.target_task, '--context_style', 'first-success', '--context_from_diff_traj', # During finetuning we adapt just the last transformer layer of the planner, keeping the planner's other layers as well as the encoder and the executor frozen. # We could adapt other parts of PLEX too, but it's unnecessary to reproduce the PLEX paper's results. '--image_encoder_tune_style', 'none', '--obs_pred.transformer_tune_style', 'last_block', '--inv_d_pred.transformer_tune_style', 'none', '--finetune_learning_rate', '0.0005', '--finetune_steps_per_iter', '100', '--best_metric', 'evaluation/success_rate', '--max_eval_episode_len', '500', '--num_eval_episodes', '50', '--num_eval_workers', str(args.num_workers), # Remove this flag if you don't want videos of evaluation trajectories to be recorded. '--record_video', '--load_path', args.model_file ])
finetune(cmdline_args)
2
2023-11-06 09:38:09+00:00
12k
mitre/arlin
tests/test_samdp.py
[ { "identifier": "COLORS", "path": "arlin/analysis/visualization/colors.py", "snippet": "COLORS = [\n base[\"b\"],\n tableau[\"tab:orange\"],\n base[\"g\"],\n base[\"r\"],\n base[\"c\"],\n base[\"m\"],\n base[\"y\"],\n base[\"k\"],\n tableau[\"tab:blue\"],\n tableau[\"tab:gr...
import os import networkx as nx import numpy as np import pytest from arlin.analysis.visualization import COLORS from arlin.samdp import SAMDP
8,981
@pytest.fixture def samdp(random_dataset, random_clusters): samdp = SAMDP(random_clusters[0], random_dataset) return samdp class TestSAMDP: def test_init(self, random_clusters, random_dataset): samdp = SAMDP(random_clusters[0], random_dataset) assert np.array_equal(samdp.clusters, random_clusters[0]) assert samdp.dataset == random_dataset def test_generate(self, samdp): samdp_obj = samdp._generate() num_clusters = max(samdp.clusters) + 1 num_actions = samdp.dataset.env.action_space.n assert samdp_obj.shape == (num_clusters, num_actions + 1, num_clusters) for cluster_id in range(num_clusters): for action in range(num_actions): if sum(samdp_obj[cluster_id][action]) != 0: assert sum(samdp_obj[cluster_id][action]) == 1 assert np.sum(np.isnan(samdp_obj)) == 0 for i in range(samdp.dataset.num_datapoints): if samdp.dataset.terminateds[i] or samdp.dataset.truncateds[i]: continue action = samdp.dataset.actions[i] from_cluster = samdp.clusters[i] to_cluster = samdp.clusters[i + 1] if from_cluster != to_cluster: action_prob = samdp.samdp_counts[from_cluster][action][to_cluster] / sum( samdp.samdp_counts[from_cluster][action][:] ) assert samdp_obj[from_cluster][action][to_cluster] == action_prob total_prob = samdp.samdp_counts[from_cluster][-1][to_cluster] / sum( samdp.samdp_counts[from_cluster][-1][:] ) assert samdp_obj[from_cluster][-1][to_cluster] == total_prob def test_save_txt(self, samdp, tmpdir): samdp.save_txt(tmpdir) assert os.path.isfile(os.path.join(tmpdir, "samdp.txt")) def test_generate_graph(self, samdp): graph = samdp._generate_graph() num_clusters = max(samdp.clusters) + 1 assert graph.number_of_nodes() == num_clusters start_clusters = set(samdp.clusters[samdp.dataset.start_indices]) term_clusters = set(samdp.clusters[samdp.dataset.term_indices]) nodes = graph.nodes(data=True) for i in range(num_clusters): if i in start_clusters: edge_color = "g" elif i in term_clusters: edge_color = "r" else: edge_color = "k"
@pytest.fixture def samdp(random_dataset, random_clusters): samdp = SAMDP(random_clusters[0], random_dataset) return samdp class TestSAMDP: def test_init(self, random_clusters, random_dataset): samdp = SAMDP(random_clusters[0], random_dataset) assert np.array_equal(samdp.clusters, random_clusters[0]) assert samdp.dataset == random_dataset def test_generate(self, samdp): samdp_obj = samdp._generate() num_clusters = max(samdp.clusters) + 1 num_actions = samdp.dataset.env.action_space.n assert samdp_obj.shape == (num_clusters, num_actions + 1, num_clusters) for cluster_id in range(num_clusters): for action in range(num_actions): if sum(samdp_obj[cluster_id][action]) != 0: assert sum(samdp_obj[cluster_id][action]) == 1 assert np.sum(np.isnan(samdp_obj)) == 0 for i in range(samdp.dataset.num_datapoints): if samdp.dataset.terminateds[i] or samdp.dataset.truncateds[i]: continue action = samdp.dataset.actions[i] from_cluster = samdp.clusters[i] to_cluster = samdp.clusters[i + 1] if from_cluster != to_cluster: action_prob = samdp.samdp_counts[from_cluster][action][to_cluster] / sum( samdp.samdp_counts[from_cluster][action][:] ) assert samdp_obj[from_cluster][action][to_cluster] == action_prob total_prob = samdp.samdp_counts[from_cluster][-1][to_cluster] / sum( samdp.samdp_counts[from_cluster][-1][:] ) assert samdp_obj[from_cluster][-1][to_cluster] == total_prob def test_save_txt(self, samdp, tmpdir): samdp.save_txt(tmpdir) assert os.path.isfile(os.path.join(tmpdir, "samdp.txt")) def test_generate_graph(self, samdp): graph = samdp._generate_graph() num_clusters = max(samdp.clusters) + 1 assert graph.number_of_nodes() == num_clusters start_clusters = set(samdp.clusters[samdp.dataset.start_indices]) term_clusters = set(samdp.clusters[samdp.dataset.term_indices]) nodes = graph.nodes(data=True) for i in range(num_clusters): if i in start_clusters: edge_color = "g" elif i in term_clusters: edge_color = "r" else: edge_color = "k"
node = (f"Cluster \n{i}", {"edge_color": edge_color, "color": COLORS[i]})
0
2023-11-08 13:57:45+00:00
12k
Giftify-Bot/Giftify-Bot
models/giveaways.py
[ { "identifier": "ChannelConfig", "path": "models/giveaway_settings.py", "snippet": "class ChannelConfig:\n \"\"\"Represents the configuration settings for a channel.\n\n Attributes\n ----------\n channel: Union[discord.TextChannel, discord.CategoryChannel]\n The channel associated wit...
import contextlib import datetime import random import asyncpg import discord from enum import Enum from typing import TYPE_CHECKING, Dict, List, Optional from models.giveaway_settings import ChannelConfig, GuildConfig from utils.constants import GIFT_EMOJI from utils.exceptions import GiveawayError from utils.functions import bold, safe_format from utils.tree import Interaction from utils.view import BaseView, GiveawayView from bot import Giftify
7,767
else [], multiplier_roles={ role.id: entries for role, entries in multiplier_roles.items() if role is not None } if multiplier_roles else {}, messages={}, messages_required=messages_required, allowed_message_channels=[c.id for c in allowed_message_channels] if allowed_message_channels else [], extra_message_id=extra_message.id if extra_message else None, amari=amari, weekly_amari=weekly_amari, ) @classmethod async def create_entry( cls, bot: Giftify, guild_id: int, channel_id: int, message_id: int, prize: str, host_id: int, winner_count: int, ends: datetime.datetime, required_roles: List[int], blacklisted_roles: List[int], bypass_roles: List[int], donor_id: Optional[int], multiplier_roles: Optional[dict], messages: Optional[dict], messages_required: Optional[int], allowed_message_channels: Optional[List[int]], extra_message_id: Optional[int], amari: Optional[int], weekly_amari: Optional[int], ) -> "Giveaway": """ Create a new Giveaway object and insert it into the database. Parameters ---------- bot: Giftify The bot instance. guild_id: int The ID of the guild (server) where the giveaway is hosted. channel_id: int The ID of the channel where the giveaway is hosted. message_id: int The ID of the message having the giveaway view. prize: str The prize of the giveaway. host_id: int The ID of the user hosting the giveaway. donor_id: int The ID of the donor of the giveaway. winner_count: int The number of winners for the giveaway. ends: datetime.datetime The time when the giveaway ends. required_roles: List[int] The list of role IDs required to participate in the giveaway. blacklisted_roles: List[int] The list of role IDs excluded from participating in the giveaway. bypass_roles: List[int] The list of user IDs exempted from giveaway restrictions. multiplier_roles: Optional[dict] A dictionary containing multiplier_roles criteria for the giveaway. messages: Optional[dict] A dictionary containing message-based criteria for the giveaway. messages_required: Optional[int] The number of messages required to participate in the giveaway. allowed_message_channels: Optional[int] The ID of the channel where the message count is tracked. amari: Optional[int] The required Amari XP to participate in the giveaway. weekly_amari: Optional[int] The required weekly Amari XP to participate in the giveaway. Returns ------- Giveaway The created Giveaway object. """ record = await bot.pool.fetchrow( "INSERT INTO giveaways (guild, channel, message, extra_message, host, donor, prize, winner_count, ends, required_roles, blacklisted_roles, bypass_roles, multiplier_roles, messages, messages_required, messages_channel, amari, weekly_amari) " "VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) " "RETURNING *", guild_id, channel_id, message_id, extra_message_id, host_id, donor_id, prize, winner_count, ends, required_roles, blacklisted_roles, bypass_roles, multiplier_roles, messages, messages_required, allowed_message_channels, amari, weekly_amari, ) return cls(bot=bot, record=record) async def check_requirements(self, member: discord.Member) -> None: missing_roles = [ role.mention for role_id in self.required_roles if (role := member.guild.get_role(role_id)) and role not in member.roles ] if missing_roles:
from __future__ import annotations if TYPE_CHECKING: class Giveaway: """ Represents a giveaway object. Attributes ---------- bot: Giftify The bot instance to handle the giveaway. guild_id: int The ID of the guild (server) where the giveaway is hosted. channel_id: int The ID of the channel where the giveaway is hosted. message_id: int The ID of the giveaway message. extra_message_id: int The ID of the extra message with giveaway. host_id: int The ID of the user hosting the giveaway. donor_id: int The ID of the user donating for the giveaway. prize: int The prize of the giveaway. winner_count: int The number of winners for the giveaway. winners: List[int] The winners of the giveaway. participants: List[int] The IDs participants for the giveaway. ended: bool Indicates whether the giveaway has ended. ends: datetime.datetime The timestamp when the giveaway will be ended. required_roles: List[int] The list of role IDs required to participate in the giveaway. blacklisted_roles: List[int] The list of role IDs excluded from participating in the giveaway. bypass_roles: List[int] The list of user IDs exempted from giveaway restrictions. multiplier_roles: Optional[dict] A dictionary containing multiplier_roles criteria for the giveaway. messages: Optional[dict] A dictionary containing message-based criteria for the giveaway. messages_required: Optional[int] The number of messages required to participate in the giveaway. allowed_message_channels: Optional[List[int]] The ID of the channels where the message count is tracked. amari: Optional[int] The required Amari XP to participate in the giveaway. weekly_amari: Optional[int] The required weekly Amari XP to participate in the giveaway. """ __slots__ = ( "bot", "guild_id", "channel_id", "message_id", "extra_message_id", "prize", "host_id", "donor_id", "winner_count", "winners", "participants", "ended", "ends", "required_roles", "blacklisted_roles", "bypass_roles", "multiplier_roles", "messages", "messages_required", "allowed_message_channels", "amari", "weekly_amari", ) def __init__(self, *, bot: Giftify, record: asyncpg.Record): self.bot = bot self.guild_id: int = record["guild"] self.channel_id: int = record["channel"] self.message_id: int = record["message"] self.extra_message_id: int = record["extra_message"] self.prize: str = record["prize"] self.host_id: int = record["host"] self.donor_id: Optional[int] = record["donor"] self.winner_count: int = record["winner_count"] self.winners: List[int] = record["winners"] self.participants: List[int] = record["participants"] self.ended: bool = record["ended"] self.ends: datetime.datetime = record["ends"] self.required_roles: List[int] = record["required_roles"] or [] self.blacklisted_roles: List[int] = record["blacklisted_roles"] or [] self.bypass_roles: List[int] = record["bypass_roles"] or [] self.multiplier_roles: Dict[int, int] = { int(role): entries for role, entries in record["multiplier_roles"].items() if entries > 1 } self.messages: Dict[int, int] = { int(member): messages for member, messages in record["messages"].items() } self.messages_required: Optional[int] = record["messages_required"] self.allowed_message_channels: Optional[List[int]] = record["messages_channel"] self.amari: Optional[int] = record["amari"] self.weekly_amari: Optional[int] = record["weekly_amari"] def __eq__(self, other: "Giveaway") -> bool: try: return ( self.guild_id == other.guild_id and self.channel_id == other.channel_id and self.message_id == other.message_id ) except AttributeError: return False def __hash__(self) -> int: return hash((self.guild_id, self.channel_id, self.message_id)) def __repr__(self) -> str: return f"<Giveaway guild_id={self.guild_id} channel_id={self.channel_id} message_id={self.message_id}>" @property def jump_to_giveaway(self) -> discord.ui.View: url = f"https://discord.com/channels/{self.guild_id}/{self.channel_id}/{self.message_id}" view = BaseView(timeout=None) button = discord.ui.Button(label="Jump To Giveaway", url=url) view.add_item(button) return view @staticmethod def create_embed( interaction: Interaction, config: GuildConfig, duration: datetime.datetime, winners: int, prize: str, required_roles: Optional[List[discord.Role]] = None, blacklisted_roles: Optional[List[discord.Role]] = None, bypass_roles: Optional[List[discord.Role]] = None, multiplier_roles: Optional[Dict[discord.Role, int]] = None, messages_required: Optional[int] = None, allowed_message_channels: Optional[List[discord.TextChannel]] = None, amari: Optional[int] = None, weekly_amari: Optional[int] = None, donor: Optional[discord.Member] = None, ) -> discord.Embed: assert interaction.guild is not None description = f"Click the {config.reaction} button to join the giveaway!\n" description += f"Hosted By: {interaction.user.mention}\n" if donor: description += f"Donor: {donor.mention}\n" description += f"Ends: {discord.utils.format_dt(duration, style='R')} ({discord.utils.format_dt(duration, style='f')})\n" embed = discord.Embed( title=prize, description=description, colour=config.color, timestamp=duration, ) embed.set_footer( text=f"{winners} winner(s) • Ends", icon_url=interaction.guild.icon or interaction.client.user.display_avatar, ) requirements = "" if required_roles: requirements += f"Required Roles: {', '.join(role.mention for role in required_roles if role is not None)}\n" if bypass_roles: requirements += f"Bypass Roles: {', '.join(role.mention for role in bypass_roles if role is not None)}\n" if blacklisted_roles: requirements += f"Blacklisted Roles: {', '.join(role.mention for role in blacklisted_roles if role is not None)}\n" if messages_required: requirements += ( f"Messages Required: **{messages_required}** message(s) (5s cooldown)\n" ) if allowed_message_channels: requirements += f"Allowed Channels: {', '.join(f'<#{c.id}>' for c in allowed_message_channels)}\n" if amari: requirements += f"Amari Level: {amari}\n" if weekly_amari: requirements += f"Weekly Amari: {weekly_amari} XP Points\n" if requirements: embed.add_field(name="Requirements", value=requirements, inline=False) if multiplier_roles: multiplier_roles_mention = "\n".join( [ f"- {entry}x ・ {role.mention}" for role, entry in multiplier_roles.items() if role is not None ] ) embed.add_field( name="Bonus Entries", value=multiplier_roles_mention, inline=False ) return embed @classmethod async def start( cls, interaction: Interaction, duration: datetime.datetime, winners: int, prize: str, config: GuildConfig, channel_config: Optional[ChannelConfig], required_roles: Optional[List[discord.Role]] = None, blacklisted_roles: Optional[List[discord.Role]] = None, bypass_roles: Optional[List[discord.Role]] = None, multiplier_roles: Optional[Dict[discord.Role, int]] = None, messages_required: Optional[int] = None, allowed_message_channels: Optional[List[discord.TextChannel]] = None, amari: Optional[int] = None, weekly_amari: Optional[int] = None, image: Optional[discord.Attachment] = None, donor: Optional[discord.Member] = None, ping: bool = False, message: Optional[str] = None, ): assert isinstance(interaction.channel, discord.TextChannel) assert interaction.guild is not None embed = cls.create_embed( interaction=interaction, config=config, duration=duration, winners=winners, prize=prize, required_roles=required_roles, blacklisted_roles=blacklisted_roles, bypass_roles=bypass_roles, multiplier_roles=multiplier_roles, messages_required=messages_required, allowed_message_channels=allowed_message_channels, amari=amari, weekly_amari=weekly_amari, donor=donor, ) view = GiveawayView( config.reaction, config.participants_reaction, config.button_style ) giveaway_message = await interaction.channel.send( config.gw_header, embed=embed, view=view ) message_embed = discord.Embed( title=f"{GIFT_EMOJI} Giveaway", description=f"**Message・** {message}" if message else None, color=config.color, ) if image: message_embed.set_image(url=image) extra_message = None if ping or image: ping_role = ( channel_config.ping if channel_config and channel_config.ping else config.ping ) extra_message = await interaction.channel.send( ping_role.mention if ping_role else "", embed=message_embed if message or image else None, # type: ignore allowed_mentions=discord.AllowedMentions(roles=True), ) if extra_message is None and message is not None: extra_message = await interaction.channel.send(embed=message_embed) await interaction.client.timer_cog.create_timer( message_id=giveaway_message.id, channel_id=interaction.channel.id, guild_id=interaction.guild.id, author_id=interaction.user.id, title="Giveaway", event="giveaway", expires=duration, pool=interaction.client.pool, ) return await cls.create_entry( bot=interaction.client, guild_id=interaction.guild.id, channel_id=interaction.channel.id, message_id=giveaway_message.id, prize=prize, host_id=interaction.user.id, donor_id=donor.id if donor else None, winner_count=winners, ends=duration, required_roles=[role.id for role in required_roles if role is not None] if required_roles else [], blacklisted_roles=[ role.id for role in blacklisted_roles if role is not None ] if blacklisted_roles else [], bypass_roles=[role.id for role in bypass_roles if role is not None] if bypass_roles else [], multiplier_roles={ role.id: entries for role, entries in multiplier_roles.items() if role is not None } if multiplier_roles else {}, messages={}, messages_required=messages_required, allowed_message_channels=[c.id for c in allowed_message_channels] if allowed_message_channels else [], extra_message_id=extra_message.id if extra_message else None, amari=amari, weekly_amari=weekly_amari, ) @classmethod async def create_entry( cls, bot: Giftify, guild_id: int, channel_id: int, message_id: int, prize: str, host_id: int, winner_count: int, ends: datetime.datetime, required_roles: List[int], blacklisted_roles: List[int], bypass_roles: List[int], donor_id: Optional[int], multiplier_roles: Optional[dict], messages: Optional[dict], messages_required: Optional[int], allowed_message_channels: Optional[List[int]], extra_message_id: Optional[int], amari: Optional[int], weekly_amari: Optional[int], ) -> "Giveaway": """ Create a new Giveaway object and insert it into the database. Parameters ---------- bot: Giftify The bot instance. guild_id: int The ID of the guild (server) where the giveaway is hosted. channel_id: int The ID of the channel where the giveaway is hosted. message_id: int The ID of the message having the giveaway view. prize: str The prize of the giveaway. host_id: int The ID of the user hosting the giveaway. donor_id: int The ID of the donor of the giveaway. winner_count: int The number of winners for the giveaway. ends: datetime.datetime The time when the giveaway ends. required_roles: List[int] The list of role IDs required to participate in the giveaway. blacklisted_roles: List[int] The list of role IDs excluded from participating in the giveaway. bypass_roles: List[int] The list of user IDs exempted from giveaway restrictions. multiplier_roles: Optional[dict] A dictionary containing multiplier_roles criteria for the giveaway. messages: Optional[dict] A dictionary containing message-based criteria for the giveaway. messages_required: Optional[int] The number of messages required to participate in the giveaway. allowed_message_channels: Optional[int] The ID of the channel where the message count is tracked. amari: Optional[int] The required Amari XP to participate in the giveaway. weekly_amari: Optional[int] The required weekly Amari XP to participate in the giveaway. Returns ------- Giveaway The created Giveaway object. """ record = await bot.pool.fetchrow( "INSERT INTO giveaways (guild, channel, message, extra_message, host, donor, prize, winner_count, ends, required_roles, blacklisted_roles, bypass_roles, multiplier_roles, messages, messages_required, messages_channel, amari, weekly_amari) " "VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) " "RETURNING *", guild_id, channel_id, message_id, extra_message_id, host_id, donor_id, prize, winner_count, ends, required_roles, blacklisted_roles, bypass_roles, multiplier_roles, messages, messages_required, allowed_message_channels, amari, weekly_amari, ) return cls(bot=bot, record=record) async def check_requirements(self, member: discord.Member) -> None: missing_roles = [ role.mention for role_id in self.required_roles if (role := member.guild.get_role(role_id)) and role not in member.roles ] if missing_roles:
raise GiveawayError(
3
2023-11-09 15:00:15+00:00
12k
Zjy0401/CoCoFormer
train.py
[ { "identifier": "create_jsf_datasets", "path": "dataset/jsf.py", "snippet": "def create_jsf_datasets(dataset_root, max_seq, random_seq=True):\n\n train_root = os.path.join(dataset_root, \"train\")\n # val_root = os.path.join(dataset_root, \"val\")\n test_root = os.path.join(dataset_root, \"test...
import os import csv import shutil import torch import torch.nn as nn import pickle from thop import profile from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from torch.optim import Adam from dataset.jsf import create_jsf_datasets from model.CoCoFormer import CoCoformer, Discriminator, PureTransformer from model.loss import SmoothCrossEntropyLoss from utilities.constants import * from utilities.device import get_device, use_cuda from utilities.lr_scheduling import LrStepTracker, get_lr from utilities.argument_funcs import parse_train_args, print_train_args, write_model_params from utilities.run_model import train_epoch, train_with_adv, eval_model, get_metrics, train_with_pure_transformer, params from tensorboardX import SummaryWriter
10,336
# from dataset.e_piano import create_epiano_datasets, compute_epiano_accuracy, split_train_test CSV_HEADER = ["Epoch", "Learn rate", "Avg Train loss", "Train Accuracy", "Avg Eval loss", "Eval accuracy"] # Baseline is an untrained epoch that we evaluate as a baseline loss and accuracy BASELINE_EPOCH = -1 # main def main(): """ ---------- Author: Damon Gwinn ---------- Entry point. Trains a model specified by command line arguments ---------- """ args = parse_train_args()
# from dataset.e_piano import create_epiano_datasets, compute_epiano_accuracy, split_train_test CSV_HEADER = ["Epoch", "Learn rate", "Avg Train loss", "Train Accuracy", "Avg Eval loss", "Eval accuracy"] # Baseline is an untrained epoch that we evaluate as a baseline loss and accuracy BASELINE_EPOCH = -1 # main def main(): """ ---------- Author: Damon Gwinn ---------- Entry point. Trains a model specified by command line arguments ---------- """ args = parse_train_args()
print_train_args(args)
10
2023-11-01 08:33:08+00:00
12k
serl-robot/serl
serl/agents/vice/vice_learner.py
[ { "identifier": "batched_random_crop", "path": "serl/utils/augmentations.py", "snippet": "def batched_random_crop(key, obs, pixel_key, padding=4):\n imgs = obs[pixel_key]\n keys = jax.random.split(key, imgs.shape[0])\n imgs = jax.vmap(random_crop, (0, 0, None))(keys, imgs, padding)\n return ...
from functools import partial from itertools import zip_longest from typing import Callable, Dict, Optional, Sequence, Tuple, OrderedDict from collections import OrderedDict from jax import numpy as jnp from flax import struct from flax.core import FrozenDict, freeze from flax.training.train_state import TrainState from serl.utils.augmentations import batched_random_crop from serl.agents.sac.sac_learner import SACLearner from serl.agents.drq.drq_learner import DrQLearner from serl.agents.sac.temperature import Temperature from serl.data.dataset import DatasetDict from serl.distributions import TanhNormal from serl.networks import MLP, Ensemble, PixelMultiplexer, StateActionValue from serl.networks.encoders import TwoMobileNetEncoder, MobileNetEncoder, TwoD4PGEncoder from serl.networks.encoded_encoder import EncodedEncoder from serl.networks.one_d_output import OneDimOutput from serl.utils.commons import _unpack, _share_encoder from jeffnet.linen import create_model, EfficientNet import gym import jax import optax import flax.linen as nn
8,365
"""Implementations of algorithms for continuous control.""" class VICELearner(DrQLearner): vice_classifiers: OrderedDict[str, TrainState] vice_label_smoothing: float vice_goal_pool: jnp.ndarray vice_encoder: TrainState vice_encoder_params: FrozenDict @classmethod def create( cls, seed: int, observation_space: gym.Space, action_space: gym.Space, actor_lr: float = 3e-4, critic_lr: float = 3e-4, vice_lr: float = 3e-4, temp_lr: float = 3e-4, cnn_features: Sequence[int] = (32, 32, 32, 32), cnn_filters: Sequence[int] = (3, 3, 3, 3), cnn_strides: Sequence[int] = (2, 1, 1, 1), cnn_padding: str = "VALID", latent_dim: int = 50, encoder: str = "d4pg", hidden_dims: Sequence[int] = (256, 256), discount: float = 0.99, tau: float = 0.005, num_qs: int = 2, num_min_qs: Optional[int] = None, critic_dropout_rate: Optional[float] = None, vice_dropout_rate: Optional[float] = None, vice_label_smoothing: float = 0.1, critic_layer_norm: bool = False, target_entropy: Optional[float] = None, init_temperature: float = 1.0, backup_entropy: bool = True, pixel_keys: Tuple[str, ...] = ("pixels",), depth_keys: Tuple[str, ...] = (), vice_goal_pool: jnp.ndarray = None ): """ An implementation of the version of Soft-Actor-Critic described in https://arxiv.org/abs/1812.05905 """ action_dim = action_space.shape[-1] observations = observation_space.sample() actions = action_space.sample() if target_entropy is None: target_entropy = -action_dim rng = jax.random.PRNGKey(seed) rng, actor_key, critic_key, temp_key, vice_encoder_key = jax.random.split(rng, 5) rng_vice_keys = jax.random.split(rng, 1 + len(pixel_keys)) rng, vice_keys = rng_vice_keys[0], rng_vice_keys[1:] if encoder == "d4pg": encoder_cls = partial( TwoD4PGEncoder, features=cnn_features, filters=cnn_filters, strides=cnn_strides, padding=cnn_padding, ) elif encoder == "resnet": raise NotImplementedError elif encoder == "mobilenet": MobileNet, mobilenet_variables = create_model('tf_mobilenetv3_large_100', pretrained=True) encoder_cls = partial(TwoMobileNetEncoder, mobilenet=MobileNet, params=mobilenet_variables) actor_base_cls = partial(MLP, hidden_dims=hidden_dims, activate_final=True) actor_cls = partial(TanhNormal, base_cls=actor_base_cls, action_dim=action_dim) actor_def = PixelMultiplexer( encoder_cls=encoder_cls, network_cls=actor_cls, latent_dim=latent_dim, stop_gradient=True, # do not update the encoder params pixel_keys=pixel_keys, depth_keys=depth_keys, ) actor_params = actor_def.init(actor_key, observations)["params"] actor = TrainState.create( apply_fn=actor_def.apply, params=actor_params, tx=optax.adam(learning_rate=actor_lr), ) critic_base_cls = partial( MLP, hidden_dims=hidden_dims, activate_final=True, dropout_rate=critic_dropout_rate, use_layer_norm=critic_layer_norm, )
"""Implementations of algorithms for continuous control.""" class VICELearner(DrQLearner): vice_classifiers: OrderedDict[str, TrainState] vice_label_smoothing: float vice_goal_pool: jnp.ndarray vice_encoder: TrainState vice_encoder_params: FrozenDict @classmethod def create( cls, seed: int, observation_space: gym.Space, action_space: gym.Space, actor_lr: float = 3e-4, critic_lr: float = 3e-4, vice_lr: float = 3e-4, temp_lr: float = 3e-4, cnn_features: Sequence[int] = (32, 32, 32, 32), cnn_filters: Sequence[int] = (3, 3, 3, 3), cnn_strides: Sequence[int] = (2, 1, 1, 1), cnn_padding: str = "VALID", latent_dim: int = 50, encoder: str = "d4pg", hidden_dims: Sequence[int] = (256, 256), discount: float = 0.99, tau: float = 0.005, num_qs: int = 2, num_min_qs: Optional[int] = None, critic_dropout_rate: Optional[float] = None, vice_dropout_rate: Optional[float] = None, vice_label_smoothing: float = 0.1, critic_layer_norm: bool = False, target_entropy: Optional[float] = None, init_temperature: float = 1.0, backup_entropy: bool = True, pixel_keys: Tuple[str, ...] = ("pixels",), depth_keys: Tuple[str, ...] = (), vice_goal_pool: jnp.ndarray = None ): """ An implementation of the version of Soft-Actor-Critic described in https://arxiv.org/abs/1812.05905 """ action_dim = action_space.shape[-1] observations = observation_space.sample() actions = action_space.sample() if target_entropy is None: target_entropy = -action_dim rng = jax.random.PRNGKey(seed) rng, actor_key, critic_key, temp_key, vice_encoder_key = jax.random.split(rng, 5) rng_vice_keys = jax.random.split(rng, 1 + len(pixel_keys)) rng, vice_keys = rng_vice_keys[0], rng_vice_keys[1:] if encoder == "d4pg": encoder_cls = partial( TwoD4PGEncoder, features=cnn_features, filters=cnn_filters, strides=cnn_strides, padding=cnn_padding, ) elif encoder == "resnet": raise NotImplementedError elif encoder == "mobilenet": MobileNet, mobilenet_variables = create_model('tf_mobilenetv3_large_100', pretrained=True) encoder_cls = partial(TwoMobileNetEncoder, mobilenet=MobileNet, params=mobilenet_variables) actor_base_cls = partial(MLP, hidden_dims=hidden_dims, activate_final=True) actor_cls = partial(TanhNormal, base_cls=actor_base_cls, action_dim=action_dim) actor_def = PixelMultiplexer( encoder_cls=encoder_cls, network_cls=actor_cls, latent_dim=latent_dim, stop_gradient=True, # do not update the encoder params pixel_keys=pixel_keys, depth_keys=depth_keys, ) actor_params = actor_def.init(actor_key, observations)["params"] actor = TrainState.create( apply_fn=actor_def.apply, params=actor_params, tx=optax.adam(learning_rate=actor_lr), ) critic_base_cls = partial( MLP, hidden_dims=hidden_dims, activate_final=True, dropout_rate=critic_dropout_rate, use_layer_norm=critic_layer_norm, )
critic_cls = partial(StateActionValue, base_cls=critic_base_cls)
9
2023-11-02 23:32:24+00:00
12k
tiendatnguyen-vision/Orbit-symmetrize
RotatedMNIST/LPS/emlp-pytorch/emlp_pytorch/reps/representation.py
[ { "identifier": "Group", "path": "RotatedMNIST/LPS/emlp-pytorch/emlp_pytorch/groups.py", "snippet": "class Group(nn.Module):\n \"\"\" Abstract Group Object which new groups should inherit from. \"\"\"\n\n def __init__(self):\n super().__init__()\n self.lie_algebra = NotImplemented #...
import math import logging import itertools import torch from functools import lru_cache as cache, reduce from collections import defaultdict from plum import dispatch from torch import nn from ..groups import Group from .linear_operator_base import LinearOperator from .linear_operators import ConcatLazy, I, lazify, densify, LazyJVP, LazyPerm, \ LazyDirectSum, LazyKron, LazyKronsum, lazy_direct_matmat, product from .utils import orthogonal_complement, krylov_constraint_solve, get_device
9,361
""" The base Representation class. """ class Rep(nn.Module): """ The base Representation class. Representation objects formalize the vector space V on which the group acts, the group representation matrix ρ(g), and the Lie Algebra representation dρ(A) in a single object. Representations act as types for vectors coming from V. These types can be manipulated and transformed with the built in operators ⊕,⊗,dual, as well as incorporating custom representations. Representation objects should be immutable. At minimum, new representations need to implement ``rho``, ``__str__``.""" def __init__(self): super().__init__() self.is_permutation = False self._size = None self.G = None def rho(self, M): """ Group representation of the matrix M of shape (d,d)""" raise NotImplementedError def drho(self, A): """ Lie Algebra representation of the matrix A of shape (d,d)""" In = torch.eye(A.size(0), dtype=A.dtype, device=A.device) return LazyJVP(self.rho, In, A) def forward(self, G): """ Instantiate (nonconcrete) representation with a symmetry group (forward) """ raise NotImplementedError def __str__(self): return repr(self) def __repr__(self): raise NotImplementedError def __eq__(self, other): if type(self) is not type(other): # pylint: disable=unidiomatic-typecheck return False return self.__hash__() == other.__hash__() def __hash__(self): raise NotImplementedError def size(self): """ Dimension dim(V) of the representation """ if self._size is not None: return self._size if self.concrete() and isinstance(self.G, Group): self._size = self.rho(self.G.sample()).size(-1) return self._size raise NotImplementedError def canonicalize(self): """ An optional method to convert the representation into a canonical form in order to reuse equivalent solutions in the solver. Should return both the canonically ordered representation, along with a permutation which can be applied to vectors of the current representation to achieve that ordering. """ # return canonicalized rep return self, torch.arange(self.size()) def rho_dense(self, M): """ A convenience function which returns rho(M) as a dense matrix."""
""" The base Representation class. """ class Rep(nn.Module): """ The base Representation class. Representation objects formalize the vector space V on which the group acts, the group representation matrix ρ(g), and the Lie Algebra representation dρ(A) in a single object. Representations act as types for vectors coming from V. These types can be manipulated and transformed with the built in operators ⊕,⊗,dual, as well as incorporating custom representations. Representation objects should be immutable. At minimum, new representations need to implement ``rho``, ``__str__``.""" def __init__(self): super().__init__() self.is_permutation = False self._size = None self.G = None def rho(self, M): """ Group representation of the matrix M of shape (d,d)""" raise NotImplementedError def drho(self, A): """ Lie Algebra representation of the matrix A of shape (d,d)""" In = torch.eye(A.size(0), dtype=A.dtype, device=A.device) return LazyJVP(self.rho, In, A) def forward(self, G): """ Instantiate (nonconcrete) representation with a symmetry group (forward) """ raise NotImplementedError def __str__(self): return repr(self) def __repr__(self): raise NotImplementedError def __eq__(self, other): if type(self) is not type(other): # pylint: disable=unidiomatic-typecheck return False return self.__hash__() == other.__hash__() def __hash__(self): raise NotImplementedError def size(self): """ Dimension dim(V) of the representation """ if self._size is not None: return self._size if self.concrete() and isinstance(self.G, Group): self._size = self.rho(self.G.sample()).size(-1) return self._size raise NotImplementedError def canonicalize(self): """ An optional method to convert the representation into a canonical form in order to reuse equivalent solutions in the solver. Should return both the canonically ordered representation, along with a permutation which can be applied to vectors of the current representation to achieve that ordering. """ # return canonicalized rep return self, torch.arange(self.size()) def rho_dense(self, M): """ A convenience function which returns rho(M) as a dense matrix."""
return densify(self.rho(M))
5
2023-11-01 07:19:02+00:00
12k
xenxxxx/BitPay-Crypto-Signal-Trading-Bot
tests/conftest.py
[ { "identifier": "leverage_trade", "path": "tests/conftest_trades.py", "snippet": "def leverage_trade(fee):\n \"\"\"\n 5 hour short limit trade on kraken\n\n Short trade\n fee: 0.25% base\n interest_rate: 0.05% per day\n open_rate: 0.123 base\n close_rate: 0.128 b...
import json import logging import re import numpy as np import pandas as pd import pytest import builtins from copy import deepcopy from datetime import timedelta from pathlib import Path from typing import Optional from unittest.mock import MagicMock, Mock, PropertyMock from freqtrade import constants from freqtrade.commands import Arguments from freqtrade.data.converter import ohlcv_to_dataframe, trades_list_to_df from freqtrade.edge import PairInfo from freqtrade.enums import CandleType, MarginMode, RunMode, SignalDirection, TradingMode from freqtrade.exchange import Exchange from freqtrade.exchange.exchange import timeframe_to_minutes from freqtrade.freqtradebot import FreqtradeBot from freqtrade.persistence import LocalTrade, Order, Trade, init_db from freqtrade.resolvers import ExchangeResolver from freqtrade.util import dt_ts from freqtrade.util.datetime_helpers import dt_now from freqtrade.worker import Worker from tests.conftest_trades import (leverage_trade, mock_trade_1, mock_trade_2, mock_trade_3, mock_trade_4, mock_trade_5, mock_trade_6, short_trade) from tests.conftest_trades_usdt import (mock_trade_usdt_1, mock_trade_usdt_2, mock_trade_usdt_3, mock_trade_usdt_4, mock_trade_usdt_5, mock_trade_usdt_6, mock_trade_usdt_7)
7,370
) -> None: """ :param mocker: mocker to patch IStrategy class :return: None """ # returns (Signal-direction, signaname) def patched_get_entry_signal(*args, **kwargs): direction = None if enter_long and not any([exit_long, enter_short]): direction = SignalDirection.LONG if enter_short and not any([exit_short, enter_long]): direction = SignalDirection.SHORT return direction, enter_tag freqtrade.strategy.get_entry_signal = patched_get_entry_signal def patched_get_exit_signal(pair, timeframe, dataframe, is_short): if is_short: return enter_short, exit_short, exit_tag else: return enter_long, exit_long, exit_tag # returns (enter, exit) freqtrade.strategy.get_exit_signal = patched_get_exit_signal freqtrade.exchange.refresh_latest_ohlcv = lambda p: None def create_mock_trades(fee, is_short: Optional[bool] = False, use_db: bool = True): """ Create some fake trades ... :param is_short: Optional bool, None creates a mix of long and short trades. """ def add_trade(trade): if use_db: Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) is_short1 = is_short if is_short is not None else True is_short2 = is_short if is_short is not None else False # Simulate dry_run entries trade = mock_trade_1(fee, is_short1) add_trade(trade) trade = mock_trade_2(fee, is_short1) add_trade(trade) trade = mock_trade_3(fee, is_short2) add_trade(trade) trade = mock_trade_4(fee, is_short2) add_trade(trade) trade = mock_trade_5(fee, is_short2) add_trade(trade) trade = mock_trade_6(fee, is_short1) add_trade(trade) if use_db: Trade.commit() def create_mock_trades_with_leverage(fee, use_db: bool = True): """ Create some fake trades ... """ if use_db: Trade.session.rollback() def add_trade(trade): if use_db: Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) # Simulate dry_run entries trade = mock_trade_1(fee, False) add_trade(trade) trade = mock_trade_2(fee, False) add_trade(trade) trade = mock_trade_3(fee, False) add_trade(trade) trade = mock_trade_4(fee, False) add_trade(trade) trade = mock_trade_5(fee, False) add_trade(trade) trade = mock_trade_6(fee, False) add_trade(trade) trade = short_trade(fee) add_trade(trade) trade = leverage_trade(fee) add_trade(trade) if use_db: Trade.session.flush() def create_mock_trades_usdt(fee, is_short: Optional[bool] = False, use_db: bool = True): """ Create some fake trades ... """ def add_trade(trade): if use_db: Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) is_short1 = is_short if is_short is not None else True is_short2 = is_short if is_short is not None else False # Simulate dry_run entries
# pragma pylint: disable=missing-docstring logging.getLogger('').setLevel(logging.INFO) # Do not mask numpy errors as warnings that no one read, raise the exсeption np.seterr(all='raise') CURRENT_TEST_STRATEGY = 'StrategyTestV3' TRADE_SIDES = ('long', 'short') EXMS = 'freqtrade.exchange.exchange.Exchange' def pytest_addoption(parser): parser.addoption('--longrun', action='store_true', dest="longrun", default=False, help="Enable long-run tests (ccxt compat)") def pytest_configure(config): config.addinivalue_line( "markers", "longrun: mark test that is running slowly and should not be run regularily" ) if not config.option.longrun: setattr(config.option, 'markexpr', 'not longrun') def log_has(line, logs): """Check if line is found on some caplog's message.""" return any(line == message for message in logs.messages) def log_has_when(line, logs, when): """Check if line is found in caplog's messages during a specified stage""" return any(line == message.message for message in logs.get_records(when)) def log_has_re(line, logs): """Check if line matches some caplog's message.""" return any(re.match(line, message) for message in logs.messages) def num_log_has(line, logs): """Check how many times line is found in caplog's messages.""" return sum(line == message for message in logs.messages) def num_log_has_re(line, logs): """Check how many times line matches caplog's messages.""" return sum(bool(re.match(line, message)) for message in logs.messages) def get_args(args): return Arguments(args).get_parsed_arg() def generate_test_data(timeframe: str, size: int, start: str = '2020-07-05'): np.random.seed(42) tf_mins = timeframe_to_minutes(timeframe) base = np.random.normal(20, 2, size=size) date = pd.date_range(start, periods=size, freq=f'{tf_mins}min', tz='UTC') df = pd.DataFrame({ 'date': date, 'open': base, 'high': base + np.random.normal(2, 1, size=size), 'low': base - np.random.normal(2, 1, size=size), 'close': base + np.random.normal(0, 1, size=size), 'volume': np.random.normal(200, size=size) } ) df = df.dropna() return df def generate_test_data_raw(timeframe: str, size: int, start: str = '2020-07-05'): """ Generates data in the ohlcv format used by ccxt """ df = generate_test_data(timeframe, size, start) df['date'] = df.loc[:, 'date'].view(np.int64) // 1000 // 1000 return list(list(x) for x in zip(*(df[x].values.tolist() for x in df.columns))) # Source: https://stackoverflow.com/questions/29881236/how-to-mock-asyncio-coroutines # TODO: This should be replaced with AsyncMock once support for python 3.7 is dropped. def get_mock_coro(return_value=None, side_effect=None): async def mock_coro(*args, **kwargs): if side_effect: if isinstance(side_effect, list): effect = side_effect.pop(0) else: effect = side_effect if isinstance(effect, Exception): raise effect if callable(effect): return effect(*args, **kwargs) return effect else: return return_value return Mock(wraps=mock_coro) def patched_configuration_load_config_file(mocker, config) -> None: mocker.patch( 'freqtrade.configuration.load_config.load_config_file', lambda *args, **kwargs: config ) def patch_exchange( mocker, api_mock=None, id='binance', mock_markets=True, mock_supported_modes=True ) -> None: mocker.patch(f'{EXMS}._load_async_markets', return_value={}) mocker.patch(f'{EXMS}.validate_config', MagicMock()) mocker.patch(f'{EXMS}.validate_timeframes', MagicMock()) mocker.patch(f'{EXMS}.id', PropertyMock(return_value=id)) mocker.patch(f'{EXMS}.name', PropertyMock(return_value=id.title())) mocker.patch(f'{EXMS}.precisionMode', PropertyMock(return_value=2)) if mock_markets: if isinstance(mock_markets, bool): mock_markets = get_markets() mocker.patch(f'{EXMS}.markets', PropertyMock(return_value=mock_markets)) if mock_supported_modes: mocker.patch( f'freqtrade.exchange.{id}.{id.capitalize()}._supported_trading_mode_margin_pairs', PropertyMock(return_value=[ (TradingMode.MARGIN, MarginMode.CROSS), (TradingMode.MARGIN, MarginMode.ISOLATED), (TradingMode.FUTURES, MarginMode.CROSS), (TradingMode.FUTURES, MarginMode.ISOLATED) ]) ) if api_mock: mocker.patch(f'{EXMS}._init_ccxt', return_value=api_mock) else: mocker.patch(f'{EXMS}._init_ccxt', MagicMock()) mocker.patch(f'{EXMS}.timeframes', PropertyMock( return_value=['5m', '15m', '1h', '1d'])) def get_patched_exchange(mocker, config, api_mock=None, id='binance', mock_markets=True, mock_supported_modes=True) -> Exchange: patch_exchange(mocker, api_mock, id, mock_markets, mock_supported_modes) config['exchange']['name'] = id try: exchange = ExchangeResolver.load_exchange(config, load_leverage_tiers=True) except ImportError: exchange = Exchange(config) return exchange def patch_wallet(mocker, free=999.9) -> None: mocker.patch('freqtrade.wallets.Wallets.get_free', MagicMock( return_value=free )) def patch_whitelist(mocker, conf) -> None: mocker.patch('freqtrade.freqtradebot.FreqtradeBot._refresh_active_whitelist', MagicMock(return_value=conf['exchange']['pair_whitelist'])) def patch_edge(mocker) -> None: # "ETH/BTC", # "LTC/BTC", # "XRP/BTC", # "NEO/BTC" mocker.patch('freqtrade.edge.Edge._cached_pairs', mocker.PropertyMock( return_value={ 'NEO/BTC': PairInfo(-0.20, 0.66, 3.71, 0.50, 1.71, 10, 25), 'LTC/BTC': PairInfo(-0.21, 0.66, 3.71, 0.50, 1.71, 11, 20), } )) mocker.patch('freqtrade.edge.Edge.calculate', MagicMock(return_value=True)) # Functions for recurrent object patching def patch_freqtradebot(mocker, config) -> None: """ This function patch _init_modules() to not call dependencies :param mocker: a Mocker object to apply patches :param config: Config to pass to the bot :return: None """ mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock()) patch_exchange(mocker) mocker.patch('freqtrade.freqtradebot.RPCManager._init', MagicMock()) mocker.patch('freqtrade.freqtradebot.RPCManager.send_msg', MagicMock()) patch_whitelist(mocker, config) mocker.patch('freqtrade.freqtradebot.ExternalMessageConsumer') mocker.patch('freqtrade.configuration.config_validation._validate_consumers') def get_patched_freqtradebot(mocker, config) -> FreqtradeBot: """ This function patches _init_modules() to not call dependencies :param mocker: a Mocker object to apply patches :param config: Config to pass to the bot :return: FreqtradeBot """ patch_freqtradebot(mocker, config) return FreqtradeBot(config) def get_patched_worker(mocker, config) -> Worker: """ This function patches _init_modules() to not call dependencies :param mocker: a Mocker object to apply patches :param config: Config to pass to the bot :return: Worker """ patch_freqtradebot(mocker, config) return Worker(args=None, config=config) def patch_get_signal( freqtrade: FreqtradeBot, enter_long=True, exit_long=False, enter_short=False, exit_short=False, enter_tag: Optional[str] = None, exit_tag: Optional[str] = None, ) -> None: """ :param mocker: mocker to patch IStrategy class :return: None """ # returns (Signal-direction, signaname) def patched_get_entry_signal(*args, **kwargs): direction = None if enter_long and not any([exit_long, enter_short]): direction = SignalDirection.LONG if enter_short and not any([exit_short, enter_long]): direction = SignalDirection.SHORT return direction, enter_tag freqtrade.strategy.get_entry_signal = patched_get_entry_signal def patched_get_exit_signal(pair, timeframe, dataframe, is_short): if is_short: return enter_short, exit_short, exit_tag else: return enter_long, exit_long, exit_tag # returns (enter, exit) freqtrade.strategy.get_exit_signal = patched_get_exit_signal freqtrade.exchange.refresh_latest_ohlcv = lambda p: None def create_mock_trades(fee, is_short: Optional[bool] = False, use_db: bool = True): """ Create some fake trades ... :param is_short: Optional bool, None creates a mix of long and short trades. """ def add_trade(trade): if use_db: Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) is_short1 = is_short if is_short is not None else True is_short2 = is_short if is_short is not None else False # Simulate dry_run entries trade = mock_trade_1(fee, is_short1) add_trade(trade) trade = mock_trade_2(fee, is_short1) add_trade(trade) trade = mock_trade_3(fee, is_short2) add_trade(trade) trade = mock_trade_4(fee, is_short2) add_trade(trade) trade = mock_trade_5(fee, is_short2) add_trade(trade) trade = mock_trade_6(fee, is_short1) add_trade(trade) if use_db: Trade.commit() def create_mock_trades_with_leverage(fee, use_db: bool = True): """ Create some fake trades ... """ if use_db: Trade.session.rollback() def add_trade(trade): if use_db: Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) # Simulate dry_run entries trade = mock_trade_1(fee, False) add_trade(trade) trade = mock_trade_2(fee, False) add_trade(trade) trade = mock_trade_3(fee, False) add_trade(trade) trade = mock_trade_4(fee, False) add_trade(trade) trade = mock_trade_5(fee, False) add_trade(trade) trade = mock_trade_6(fee, False) add_trade(trade) trade = short_trade(fee) add_trade(trade) trade = leverage_trade(fee) add_trade(trade) if use_db: Trade.session.flush() def create_mock_trades_usdt(fee, is_short: Optional[bool] = False, use_db: bool = True): """ Create some fake trades ... """ def add_trade(trade): if use_db: Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) is_short1 = is_short if is_short is not None else True is_short2 = is_short if is_short is not None else False # Simulate dry_run entries
trade = mock_trade_usdt_1(fee, is_short1)
8
2023-11-07 18:46:03+00:00
12k
awslabs/optimizing-multitask-training-through-dynamic-pipelines
scripts/simulation/compare_batching_methods.py
[ { "identifier": "ProfileBasedCostModelWithRC", "path": "dynapipe/data_opt/cost_models.py", "snippet": "class ProfileBasedCostModelWithRC(object):\n \"\"\"\n Wrapper class for multiple ProfileBasedCostModel objects, one for each\n tensor parallel degree and recomputation method.\n \"\"\"\n\n ...
import argparse import math import jsonlines import numpy as np import pickle from multiprocessing import Pool from typing import Optional from tqdm import tqdm from dynapipe.data_opt.cost_models import ProfileBasedCostModelWithRC from dynapipe.data_opt.optimizer import DataAssignmentOptimizer from dynapipe.model import TransformerModelSpec
7,493
"-c", "--cost-model", type=str, required=True, help="Path to a cost model file, needed for dynamic " " batching.", ) parser.add_argument( "-m", "--model", type=str, required=True, choices=["gpt", "t5"], help="Model to use.", ) parser.add_argument( "-g", "--global-batch-size", type=int, default=65536, help="Global batch size.", ) parser.add_argument( "-o", "--output", type=str, default="compare_batching_methods.jsonl", help="Output file.", ) parser.add_argument( "-ml", "--mem-limit", type=float, default=float("inf"), help="Memory limit for the data assignment optimizer.", ) parser.add_argument( "-ppr", "--pp-degree-range", type=str, default="1", help="Range of pipeline stages to simulate.", ) parser.add_argument( "-tpd", "--tp-degree", type=int, default=1, help="TP degree to simulate.", ) parser.add_argument( "-p", "--num-processes", type=int, default=64, help="Number of processes to use.", ) args = parser.parse_args() args.max_seqlen_range = [int(x) for x in args.max_seqlen_range.split(",")] args.pp_degree_range = [int(x) for x in args.pp_degree_range.split(",")] return args def get_powers_of_2_up_to(n): return [2**i for i in range(math.floor(math.log2(n)) + 1)] def get_candidate_mbs(maxn=512): return get_powers_of_2_up_to(maxn) def get_candidate_tokens(maxn=65536): return [x for x in get_powers_of_2_up_to(maxn) if x >= 32] def get_sequence_lengths(dataset_path, max_seqlen): """Get the sequence lengths from a Megatron-LM processed dataset.""" with open(dataset_path, "rb") as f: dataset = np.load(f) # dataset contains 3 columns: [start_id, end_id, sequence_length] # we only need the sequence length return np.clip(dataset[:, 2], 1, max_seqlen).astype(np.int32)[:100000] def get_global_batches(input_seqlens, target_seqlens, gbs=65536): """Get the number of global batches for a given global batch size.""" global_batches = [] current_batch = [] current_batch_size = 0 for input_seqlen, target_seqlen in zip(input_seqlens, target_seqlens): if current_batch_size + input_seqlen + target_seqlen > gbs: global_batches.append(current_batch.copy()) current_batch = [] current_batch_size = 0 current_batch.append((input_seqlen, target_seqlen)) current_batch_size += input_seqlen + target_seqlen if current_batch: global_batches.append(current_batch.copy()) return global_batches def get_model_spec(pp_degree, model="gpt"): if model == "gpt": return TransformerModelSpec(4 * pp_degree, 0, 4096, 32, 16384, 128) elif model == "t5": return TransformerModelSpec( 2 * pp_degree, 2 * pp_degree, 1024, 128, 65536, 128 ) else: raise ValueError("Unsupported model: {}".format(model)) def get_dataopt( pp_degree, cost_model, model="gpt", memlimit=float("inf"), tp_degree=1 ): num_stages = pp_degree model_spec = get_model_spec(pp_degree, model) zero_stage = 0 n_layers_per_stage = 4 dp_size = 1
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 def parse_args(): parser = argparse.ArgumentParser("Compare batching methods") parser.add_argument( "-t", "--method", type=str, choices=["none", "packing", "dynamic", "fixed_mbs", "fixed_tokens"], required=True, help="Micro-batching method to use.", ) parser.add_argument( "-s", "--max-seqlen-range", type=str, default="2048", help="Range of maximum sequence length to simulate. " "Format as comma separated list of integers.", ) parser.add_argument( "-di", "--input-dataset", type=str, required=True, help="Path to a Megatron-LM processed indexfile, " "which records the sequence length of samples in npy " "format. For input sequences.", ) parser.add_argument( "-dt", "--target-dataset", type=str, required=True, help="Dataset path for target sequences.", ) parser.add_argument( "-c", "--cost-model", type=str, required=True, help="Path to a cost model file, needed for dynamic " " batching.", ) parser.add_argument( "-m", "--model", type=str, required=True, choices=["gpt", "t5"], help="Model to use.", ) parser.add_argument( "-g", "--global-batch-size", type=int, default=65536, help="Global batch size.", ) parser.add_argument( "-o", "--output", type=str, default="compare_batching_methods.jsonl", help="Output file.", ) parser.add_argument( "-ml", "--mem-limit", type=float, default=float("inf"), help="Memory limit for the data assignment optimizer.", ) parser.add_argument( "-ppr", "--pp-degree-range", type=str, default="1", help="Range of pipeline stages to simulate.", ) parser.add_argument( "-tpd", "--tp-degree", type=int, default=1, help="TP degree to simulate.", ) parser.add_argument( "-p", "--num-processes", type=int, default=64, help="Number of processes to use.", ) args = parser.parse_args() args.max_seqlen_range = [int(x) for x in args.max_seqlen_range.split(",")] args.pp_degree_range = [int(x) for x in args.pp_degree_range.split(",")] return args def get_powers_of_2_up_to(n): return [2**i for i in range(math.floor(math.log2(n)) + 1)] def get_candidate_mbs(maxn=512): return get_powers_of_2_up_to(maxn) def get_candidate_tokens(maxn=65536): return [x for x in get_powers_of_2_up_to(maxn) if x >= 32] def get_sequence_lengths(dataset_path, max_seqlen): """Get the sequence lengths from a Megatron-LM processed dataset.""" with open(dataset_path, "rb") as f: dataset = np.load(f) # dataset contains 3 columns: [start_id, end_id, sequence_length] # we only need the sequence length return np.clip(dataset[:, 2], 1, max_seqlen).astype(np.int32)[:100000] def get_global_batches(input_seqlens, target_seqlens, gbs=65536): """Get the number of global batches for a given global batch size.""" global_batches = [] current_batch = [] current_batch_size = 0 for input_seqlen, target_seqlen in zip(input_seqlens, target_seqlens): if current_batch_size + input_seqlen + target_seqlen > gbs: global_batches.append(current_batch.copy()) current_batch = [] current_batch_size = 0 current_batch.append((input_seqlen, target_seqlen)) current_batch_size += input_seqlen + target_seqlen if current_batch: global_batches.append(current_batch.copy()) return global_batches def get_model_spec(pp_degree, model="gpt"): if model == "gpt": return TransformerModelSpec(4 * pp_degree, 0, 4096, 32, 16384, 128) elif model == "t5": return TransformerModelSpec( 2 * pp_degree, 2 * pp_degree, 1024, 128, 65536, 128 ) else: raise ValueError("Unsupported model: {}".format(model)) def get_dataopt( pp_degree, cost_model, model="gpt", memlimit=float("inf"), tp_degree=1 ): num_stages = pp_degree model_spec = get_model_spec(pp_degree, model) zero_stage = 0 n_layers_per_stage = 4 dp_size = 1
dataopt = DataAssignmentOptimizer(
1
2023-11-08 07:58:20+00:00
12k
apple/ml-reed
reed/data/environment_observation_dataset.py
[ { "identifier": "TrajectoryReplayBuffer", "path": "BPref/replay_buffer.py", "snippet": "class TrajectoryReplayBuffer:\n \"\"\"\n Buffer to store trajectories of environment transitions. Unlike ReplayBuffer, which stores all transitions in a\n flat manner, transitions are sorted by trajectory. E...
import torch import typing as t from BPref.replay_buffer import TrajectoryReplayBuffer from pathlib import Path from reed.data.environment_transition_dataset import EnvironmentContrastiveDatapoint, EnvironmentTransitionDataset, \ EnvironmentContrastiveBatch from torchvision import transforms from torchvision.transforms import ToTensor, Normalize, \ Grayscale, RandomGrayscale, ColorJitter, RandomApply, RandomHorizontalFlip, GaussianBlur, RandomResizedCrop
8,807
# # For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. # JITTER_FACTORS = {'brightness': 0.4, 'contrast': 0.4, 'saturation': 0.4, 'hue': 0.1} DEFAULT_ARGS = { 'normalization_mean': [0.485, 0.456, 0.406], 'normalization_std': [0.229, 0.224, 0.225], 'blur_sigma_min': 0.1, 'blur_sigma_max': 2.0, 'jitter_default': 0., 'strong_jitter_pval': 0.05, 'strong_blur_pval': 0.01, 'strong_crop_scale_min': 0.2, 'strong_crop_scale_max': 0.7, 'strong_crop_ratio_min': 1.2, 'strong_crop_ratio_max': 1.8, 'weak_jitter_pval': 0.1, 'weak_blur_pval': 0., 'weak_crop_scale_min': 0.8, 'weak_crop_scale_max': 1.0, 'weak_crop_ratio_min': 1.6, 'weak_crop_ratio_max': 1.8, 'gaussian_blur_kernel_size': 5, }
# # For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. # JITTER_FACTORS = {'brightness': 0.4, 'contrast': 0.4, 'saturation': 0.4, 'hue': 0.1} DEFAULT_ARGS = { 'normalization_mean': [0.485, 0.456, 0.406], 'normalization_std': [0.229, 0.224, 0.225], 'blur_sigma_min': 0.1, 'blur_sigma_max': 2.0, 'jitter_default': 0., 'strong_jitter_pval': 0.05, 'strong_blur_pval': 0.01, 'strong_crop_scale_min': 0.2, 'strong_crop_scale_max': 0.7, 'strong_crop_ratio_min': 1.2, 'strong_crop_ratio_max': 1.8, 'weak_jitter_pval': 0.1, 'weak_blur_pval': 0., 'weak_crop_scale_min': 0.8, 'weak_crop_scale_max': 1.0, 'weak_crop_ratio_min': 1.6, 'weak_crop_ratio_max': 1.8, 'gaussian_blur_kernel_size': 5, }
class AugmentedEnvironmentObservationDataset(EnvironmentTransitionDataset):
2
2023-11-06 23:14:20+00:00
12k
ApolloAuto/apollo-model-yolox
yolox/models/yolox.py
[ { "identifier": "YOLOXHead", "path": "yolox/models/yolo_head.py", "snippet": "class YOLOXHead(nn.Module):\n def __init__(\n self,\n num_classes,\n width=1.0,\n strides=[8, 16, 32],\n in_channels=[256, 512, 1024],\n act=\"silu\",\n depthwise=False,\n ...
import torch.nn as nn from .yolo_head import YOLOXHead from .yolo_pafpn import YOLOPAFPN
7,728
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) Megvii Inc. All rights reserved. class YOLOX(nn.Module): """ YOLOX model module. The module list is defined by create_yolov3_modules function. The network returns loss values from three YOLO layers during training and detection results during test. """ def __init__(self, backbone=None, head=None): super().__init__() if backbone is None:
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) Megvii Inc. All rights reserved. class YOLOX(nn.Module): """ YOLOX model module. The module list is defined by create_yolov3_modules function. The network returns loss values from three YOLO layers during training and detection results during test. """ def __init__(self, backbone=None, head=None): super().__init__() if backbone is None:
backbone = YOLOPAFPN()
1
2023-11-08 07:07:24+00:00
12k
ndiamant/spice
experiments/train_eval.py
[ { "identifier": "ConditionalHist", "path": "spice/conditional_histogram.py", "snippet": "class ConditionalHist(BaseLightning):\n def __init__(\n self, input_dim: int, hidden_dim: int,\n max_iter: int, bins: torch.Tensor,\n y_min: float,\n lr: float = 1e-3, wd: float = 0,\n...
import argparse import os import wandb from pytorch_lightning import seed_everything, Trainer from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor from spice.conditional_histogram import ConditionalHist from spice.chr import CHR from spice.datasets import RegressionData from spice.cqr import CQR from spice.pcp import PCP from spice.utils import timestamp, rename_metrics, WANDB_PROJECT from spice.spice_n2 import SPICEn2, smart_bin_init from spice.spice_n1 import SPICEn1 from spice.spice_n1 import smart_bin_init as spice_n1_smart_bin_init
9,236
trainer.fit(model, datamodule=data) model = model.load_from_checkpoint(checkpoint.best_model_path) model: ConditionalHist = model.eval() # run conformal x_cal, y_cal = data.cal_dset.tensors x_cal_val, y_cal_val = data.cal_val_dset.tensors thresholds = [] hpd_thresholds = [] for alpha in alphas: threshold = model.find_prob_threshold(x_cal, y_cal, alpha) thresholds.append(threshold) metrics = model.get_metrics(x_cal_val, y_cal_val, threshold) logger.log_metrics(rename_metrics(metrics, "val", alpha)) # hpd hpd_threshold = model.get_hpd_threshold(x_cal, y_cal, alpha) hpd_thresholds.append(hpd_threshold) metrics = model.get_hpd_metrics(x_cal_val, y_cal_val, hpd_threshold) logger.log_metrics(rename_metrics(metrics, "val", alpha)) # testing if not run_test: wandb.finish() return model, data, thresholds x_test, y_test = data.test_dset.tensors for alpha, threshold, hpd_threshold in zip(alphas, thresholds, hpd_thresholds): thresholds.append(threshold) metrics = model.get_metrics(x_test, y_test, threshold) logger.log_metrics(rename_metrics(metrics, "test", alpha)) # hpd hpd_thresholds.append(hpd_threshold) metrics = model.get_hpd_metrics(x_test, y_test, hpd_threshold) logger.log_metrics(rename_metrics(metrics, "test", alpha)) def run_cqr( dataset_name: str, lr: float, wd: float, epochs: int, hidden: int, seed: int, alphas: list[float], qr_interval: float, # saving settings checkpoint_folder: str, version: str, wandb_log_dir: str, # run_test: bool = False, ): ts = timestamp() name = f"cqr_version-{version}_{ts}" trainer, logger, checkpoint, data = setup_trainer_and_data( name=name, wandb_log_dir=wandb_log_dir, epochs=epochs, version=version, dataset_name=dataset_name, seed=seed, checkpoint_folder=checkpoint_folder, y_scaling="std", ) seed_everything(seed) wandb.config.update({ "dataset_name": dataset_name, "alphas": alphas, "model": "cqr", "qr_interval": qr_interval, "seed": seed, }) # set up model x_dim = data.train_dset.tensors[0].shape[1] low_quantile = round((1 - qr_interval) / 2, 3) high_quantile = 1 - low_quantile model = CQR( input_dim=x_dim, hidden_dim=hidden, lr=lr, wd=wd, max_iter=trainer.max_steps, low_quantile=low_quantile, high_quantile=high_quantile, ) # fit model trainer.fit(model, datamodule=data) model = model.load_from_checkpoint(checkpoint.best_model_path) model: CQR = model.eval() # run conformal x_cal, y_cal = data.cal_dset.tensors x_cal_val, y_cal_val = data.cal_val_dset.tensors q_hats = [] for alpha in alphas: q_hat = model.get_q_hat(x_cal, y_cal, alpha) metrics = model.get_metrics( x_cal_val, y_cal_val, q_hat, ) metrics["size"] /= data.y_min_max_scaler.data_range_.item() logger.log_metrics(rename_metrics(metrics, "val", alpha)) q_hats.append(q_hat) # testing if not run_test: wandb.finish() return model, data, q_hats x_test, y_test = data.test_dset.tensors for alpha, q_hat in zip(alphas, q_hats): metrics = model.get_metrics( x_test, y_test, q_hat, ) metrics["size"] /= data.y_min_max_scaler.data_range_.item() logger.log_metrics(rename_metrics(metrics, "test", alpha)) def run_pcp( dataset_name: str, lr: float, wd: float, epochs: int, hidden: int, seed: int, alphas: list[float], n_mixture: int, # saving settings checkpoint_folder: str, version: str, wandb_log_dir: str, # run_test: bool = False, ): ts = timestamp() name = f"pcp_version-{version}_{ts}" trainer, logger, checkpoint, data = setup_trainer_and_data( name=name, wandb_log_dir=wandb_log_dir, epochs=epochs, version=version, dataset_name=dataset_name, seed=seed, checkpoint_folder=checkpoint_folder, y_scaling="std", ) seed_everything(seed) wandb.config.update({ "dataset_name": dataset_name, "alphas": alphas, "model": "pcp", "seed": seed, }) # set up model x_dim = data.train_dset.tensors[0].shape[1]
def setup_trainer_and_data( name: str, wandb_log_dir: str, epochs: int, version: str, checkpoint_folder: str, dataset_name: str, seed: int, y_scaling: str = "min_max", discretize_n_bins: int = None, smart_discretize: bool = True, ) -> tuple[Trainer, WandbLogger, ModelCheckpoint, RegressionData]: data = RegressionData( dataset_name, train_seed=seed, y_scaling=y_scaling, discretize_n_bins=discretize_n_bins, smart_discretize=smart_discretize, ) logger = WandbLogger( project=WANDB_PROJECT, save_dir=wandb_log_dir, name=name, group=version, version=f"{version}_{name}", ) checkpoint = ModelCheckpoint( dirpath=os.path.join(checkpoint_folder, name) ) max_steps_per_epoch = 100 max_val_steps = 10 train_batches = data.train_batches(max_steps_per_epoch) trainer = Trainer( logger=logger, callbacks=[ EarlyStopping(monitor="val/loss", patience=epochs // 4, mode="min"), LearningRateMonitor(), checkpoint, ], accelerator="gpu", max_steps=epochs * max_steps_per_epoch, check_val_every_n_epoch=1, limit_train_batches=train_batches, limit_val_batches=data.val_batches(max_val_steps), enable_progress_bar=False, gradient_clip_val=5, log_every_n_steps=train_batches, ) return trainer, logger, checkpoint, data def run_conditional_histogram( dataset_name: str, lr: float, wd: float, epochs: int, hidden: int, n_bins: int, seed: int, alphas: list[float], smart_bin_positions: bool, # saving settings checkpoint_folder: str, version: str, wandb_log_dir: str, # run_test: bool = False, ): # set up data ts = timestamp() name = f"conditional_hist_version-{version}_{ts}" trainer, logger, checkpoint, data = setup_trainer_and_data( name=name, wandb_log_dir=wandb_log_dir, epochs=epochs, version=version, dataset_name=dataset_name, seed=seed, checkpoint_folder=checkpoint_folder, discretize_n_bins=n_bins, smart_discretize=smart_bin_positions, ) seed_everything(seed) wandb.config.update({ "dataset_name": dataset_name, "alphas": alphas, "model": "conditional_hist", "n_bins": n_bins, "smart_bin_positions": smart_bin_positions, "seed": seed, }) # set up model x_train, y_train = data.train_dset.tensors model = ConditionalHist( input_dim=x_train.shape[1], hidden_dim=hidden, bins=data.bins, lr=lr, wd=wd, max_iter=trainer.max_steps, y_min=0.0, ) # fit model trainer.fit(model, datamodule=data) model = model.load_from_checkpoint(checkpoint.best_model_path) model: ConditionalHist = model.eval() # run conformal x_cal, y_cal = data.cal_dset.tensors x_cal_val, y_cal_val = data.cal_val_dset.tensors thresholds = [] hpd_thresholds = [] for alpha in alphas: threshold = model.find_prob_threshold(x_cal, y_cal, alpha) thresholds.append(threshold) metrics = model.get_metrics(x_cal_val, y_cal_val, threshold) logger.log_metrics(rename_metrics(metrics, "val", alpha)) # hpd hpd_threshold = model.get_hpd_threshold(x_cal, y_cal, alpha) hpd_thresholds.append(hpd_threshold) metrics = model.get_hpd_metrics(x_cal_val, y_cal_val, hpd_threshold) logger.log_metrics(rename_metrics(metrics, "val", alpha)) # testing if not run_test: wandb.finish() return model, data, thresholds x_test, y_test = data.test_dset.tensors for alpha, threshold, hpd_threshold in zip(alphas, thresholds, hpd_thresholds): thresholds.append(threshold) metrics = model.get_metrics(x_test, y_test, threshold) logger.log_metrics(rename_metrics(metrics, "test", alpha)) # hpd hpd_thresholds.append(hpd_threshold) metrics = model.get_hpd_metrics(x_test, y_test, hpd_threshold) logger.log_metrics(rename_metrics(metrics, "test", alpha)) def run_cqr( dataset_name: str, lr: float, wd: float, epochs: int, hidden: int, seed: int, alphas: list[float], qr_interval: float, # saving settings checkpoint_folder: str, version: str, wandb_log_dir: str, # run_test: bool = False, ): ts = timestamp() name = f"cqr_version-{version}_{ts}" trainer, logger, checkpoint, data = setup_trainer_and_data( name=name, wandb_log_dir=wandb_log_dir, epochs=epochs, version=version, dataset_name=dataset_name, seed=seed, checkpoint_folder=checkpoint_folder, y_scaling="std", ) seed_everything(seed) wandb.config.update({ "dataset_name": dataset_name, "alphas": alphas, "model": "cqr", "qr_interval": qr_interval, "seed": seed, }) # set up model x_dim = data.train_dset.tensors[0].shape[1] low_quantile = round((1 - qr_interval) / 2, 3) high_quantile = 1 - low_quantile model = CQR( input_dim=x_dim, hidden_dim=hidden, lr=lr, wd=wd, max_iter=trainer.max_steps, low_quantile=low_quantile, high_quantile=high_quantile, ) # fit model trainer.fit(model, datamodule=data) model = model.load_from_checkpoint(checkpoint.best_model_path) model: CQR = model.eval() # run conformal x_cal, y_cal = data.cal_dset.tensors x_cal_val, y_cal_val = data.cal_val_dset.tensors q_hats = [] for alpha in alphas: q_hat = model.get_q_hat(x_cal, y_cal, alpha) metrics = model.get_metrics( x_cal_val, y_cal_val, q_hat, ) metrics["size"] /= data.y_min_max_scaler.data_range_.item() logger.log_metrics(rename_metrics(metrics, "val", alpha)) q_hats.append(q_hat) # testing if not run_test: wandb.finish() return model, data, q_hats x_test, y_test = data.test_dset.tensors for alpha, q_hat in zip(alphas, q_hats): metrics = model.get_metrics( x_test, y_test, q_hat, ) metrics["size"] /= data.y_min_max_scaler.data_range_.item() logger.log_metrics(rename_metrics(metrics, "test", alpha)) def run_pcp( dataset_name: str, lr: float, wd: float, epochs: int, hidden: int, seed: int, alphas: list[float], n_mixture: int, # saving settings checkpoint_folder: str, version: str, wandb_log_dir: str, # run_test: bool = False, ): ts = timestamp() name = f"pcp_version-{version}_{ts}" trainer, logger, checkpoint, data = setup_trainer_and_data( name=name, wandb_log_dir=wandb_log_dir, epochs=epochs, version=version, dataset_name=dataset_name, seed=seed, checkpoint_folder=checkpoint_folder, y_scaling="std", ) seed_everything(seed) wandb.config.update({ "dataset_name": dataset_name, "alphas": alphas, "model": "pcp", "seed": seed, }) # set up model x_dim = data.train_dset.tensors[0].shape[1]
model = PCP(
4
2023-11-01 18:04:29+00:00
12k
nik-sm/com-hom-emg
scripts/collect_fresh_classifier_stats.py
[ { "identifier": "DataModule", "path": "com_hom_emg/data.py", "snippet": "class DataModule(LightningDataModule):\n @staticmethod\n def add_argparse_args(parent_parser):\n parser = parent_parser.add_argument_group(\"DataModule\")\n parser.add_argument(\"--fold\", type=int, required=Tru...
import argparse import re import sys import numpy as np import pandas as pd import torch import yaml from copy import deepcopy from pathlib import Path from typing import List, Optional from ablation_settings import settings_names as ablation_settings_names from loguru import logger from pytorch_lightning import seed_everything from regular_settings import settings_names as regular_settings_names from rich.console import Console from rich.table import Table from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA from sklearn.ensemble import RandomForestClassifier as RF from sklearn.linear_model import LogisticRegression as LogR from sklearn.neighbors import KNeighborsClassifier as KNN from sklearn.tree import DecisionTreeClassifier as DT from tqdm import tqdm from utils import table_to_csv from com_hom_emg.data import DataModule, get_per_subj_data from com_hom_emg.model import LearnedEmbedding from com_hom_emg.parallel_models import ControlModel_RandomGuess, ParallelA from com_hom_emg.scoring import get_combo_conf_mat from com_hom_emg.utils import PROJECT_PATH
9,105
result_x.append(x) result_y.append(y) return torch.cat(result_x), torch.cat(result_y) def get_clf(name: str): if name == "logr": return LogR(class_weight="balanced", max_iter=4000, n_jobs=-1) elif name == "lda": return LDA() elif name == "knn": return KNN(n_jobs=-1) elif name == "rf": return RF(n_jobs=-1, class_weight="balanced") elif name == "dt": return DT(class_weight="balanced") else: raise ValueError(f"Unknown classifier name: {name}") @torch.no_grad() def try_fresh_classifier(embedding, test_loader, clf_name: str, test_frac=0.2, N_aug_each_class=500): # Get features embedding.to(device) features, labels, is_single = [], [], [] for batch_data, batch_labels, batch_is_single, _subj_ids in test_loader: features.append(embedding(batch_data.to(device))) labels.append(batch_labels.to(device)) is_single.append(batch_is_single) features = torch.cat(features) labels = torch.cat(labels) is_single = torch.cat(is_single) # Create a single train/test split N_single = is_single.sum().item() N_single_test = int(N_single * test_frac) N_double = (~is_single).sum().item() N_double_test = int(N_double * test_frac) np.random.seed(0) single_perm = np.random.permutation(N_single) test_single_feat = features[is_single][single_perm[:N_single_test]] test_single_labels = labels[is_single][single_perm[:N_single_test]] train_single_feat = features[is_single][single_perm[N_single_test:]] train_single_labels = labels[is_single][single_perm[N_single_test:]] double_perm = np.random.permutation(N_double) test_double_feat = features[~is_single][double_perm[:N_double_test]] test_double_labels = labels[~is_single][double_perm[:N_double_test]] train_double_feat = features[~is_single][double_perm[N_double_test:]] train_double_labels = labels[~is_single][double_perm[N_double_test:]] # Define function to train a single sklearn clf def try_once(which: str): # logger.info(f"Train an example model for scenario: {which}") clf = ParallelA(dir_clf=get_clf(clf_name), mod_clf=get_clf(clf_name)) control = ControlModel_RandomGuess() model = {"upper": clf, "lower": clf, "aug": clf, "control": control}[which] use_aug = {"upper": False, "lower": False, "aug": True, "control": False}[which] doubles_in_train = {"upper": True, "lower": False, "aug": False, "control": True}[which] if doubles_in_train: x_train = torch.cat((train_single_feat, train_double_feat)) y_train = torch.cat((train_single_labels, train_double_labels)) else: x_train = train_single_feat y_train = train_single_labels if use_aug: x_aug, y_aug = embedding.feature_combination(train_single_feat, train_single_labels) # logger.info(f"Real singles: {len(x_train)}, augmented: {len(x_aug)}") if N_aug_each_class is not None: x_aug, y_aug = subset_each_class(x_aug, y_aug, N_aug_each_class) # logger.info(f"Subset augmented: {len(x_aug)}") x_train = torch.cat([x_train, x_aug]) y_train = torch.cat([y_train, y_aug]) x_test = torch.cat([test_single_feat, test_double_feat]) y_test = torch.cat([test_single_labels, test_double_labels]) # After (possibly) applying augmentation fn - then we can convert to numpy # That way, augmentation fn can assume its input to be torch tensor x_train = x_train.cpu().numpy() y_train = y_train.cpu().numpy() x_test = x_test.cpu().numpy() y_test = y_test.cpu().numpy() model.fit(x_train, y_train) preds = model.predict(x_test) cm = get_combo_conf_mat(y_test, preds) cm_counts = get_combo_conf_mat(y_test, preds, normalize=False) single_bal_acc = np.nanmean(np.diag(cm)[:8]) double_bal_acc = np.nanmean(np.diag(cm)[8:]) overall_bal_acc = np.nanmean(np.diag(cm)) return { "single_bal_acc": single_bal_acc, "double_bal_acc": double_bal_acc, "overall_bal_acc": overall_bal_acc, "confusion_matrix": cm, "confusion_matrix_counts": cm_counts, } return { # Train once with singles and doubles (upper-bound performance) "upper_bound": try_once("upper"), # Train once with only singles, no augmentation (lower-bound performance) "lower_bound": try_once("lower"), # Train once with singles only and augmentation "augmented": try_once("aug"), # Train once with a random model (lower-bound performance) # "control": try_once("control"), } def fresh_classifier_one_ckpt(ckpt, clf_name: str, n_aug: Optional[int]): embedding = LearnedEmbedding.load_from_checkpoint(ckpt) embedding.eval() per_subj_data = get_per_subj_data()
"""Train fresh classifiers using test checkpoints""" device = torch.device("cuda" if torch.cuda.is_available() else "cpu") logger.remove() logger.add(lambda msg: tqdm.write(msg, end=""), colorize=True) class FailedRunError(Exception): pass def load_one(folder: Path, which="best"): """Extract train, val, and test metrics from the specified checkpoint (best or last). Also extract hyperparams from hparams.yaml file.""" # Given a checkpoint like this: best__epoch=38__step=14664__val_aug_overall_acc=0.569.ckpt # We want to extract the step: 14664 ckpts = folder / "checkpoints" matching_ckpts = list(ckpts.glob(f"{which}*.ckpt")) if len(matching_ckpts) == 0: raise FailedRunError(f"No checkpoint found for {which} in {folder}") # When there are multiple runs, take the most recent. # Since only 1 metrics.csv is kept, this matches the latest ckpt chosen_ckpt = max(matching_ckpts, key=lambda x: x.stat().st_mtime) step = int(re.match(rf"{which}__epoch=\d+__step=(\d+)", chosen_ckpt.name).group(1)) metrics = pd.read_csv(folder / "metrics.csv") results = {} # NOTE - for this experiment, we ignore the test results, which come from fine-tuning, # since we will train a fresh classifier instead for split in ["train", "val"]: cols = [col for col in metrics.columns if col.startswith(split)] if len(cols) == 0: raise FailedRunError(f"No {split} metrics found in {folder}") cols.append("step") subset = metrics[cols].dropna().set_index("step") subset = subset.iloc[subset.index.get_indexer([step], method="nearest")] assert len(subset) == 1 results.update(**subset.to_dict(orient="records")[0]) hparams = yaml.safe_load((folder / "hparams.yaml").read_text()) return hparams, results, chosen_ckpt def subset_one_class(X, Y, N): idx = np.random.choice(len(X), size=N, replace=False) return X[idx], Y[idx] def subset_each_class(X, Y, N): result_x, result_y = [], [] for y in Y.unique(dim=0): idx = (Y == y).all(-1) x = X[idx] y = Y[idx] x, y = subset_one_class(x, y, N) result_x.append(x) result_y.append(y) return torch.cat(result_x), torch.cat(result_y) def get_clf(name: str): if name == "logr": return LogR(class_weight="balanced", max_iter=4000, n_jobs=-1) elif name == "lda": return LDA() elif name == "knn": return KNN(n_jobs=-1) elif name == "rf": return RF(n_jobs=-1, class_weight="balanced") elif name == "dt": return DT(class_weight="balanced") else: raise ValueError(f"Unknown classifier name: {name}") @torch.no_grad() def try_fresh_classifier(embedding, test_loader, clf_name: str, test_frac=0.2, N_aug_each_class=500): # Get features embedding.to(device) features, labels, is_single = [], [], [] for batch_data, batch_labels, batch_is_single, _subj_ids in test_loader: features.append(embedding(batch_data.to(device))) labels.append(batch_labels.to(device)) is_single.append(batch_is_single) features = torch.cat(features) labels = torch.cat(labels) is_single = torch.cat(is_single) # Create a single train/test split N_single = is_single.sum().item() N_single_test = int(N_single * test_frac) N_double = (~is_single).sum().item() N_double_test = int(N_double * test_frac) np.random.seed(0) single_perm = np.random.permutation(N_single) test_single_feat = features[is_single][single_perm[:N_single_test]] test_single_labels = labels[is_single][single_perm[:N_single_test]] train_single_feat = features[is_single][single_perm[N_single_test:]] train_single_labels = labels[is_single][single_perm[N_single_test:]] double_perm = np.random.permutation(N_double) test_double_feat = features[~is_single][double_perm[:N_double_test]] test_double_labels = labels[~is_single][double_perm[:N_double_test]] train_double_feat = features[~is_single][double_perm[N_double_test:]] train_double_labels = labels[~is_single][double_perm[N_double_test:]] # Define function to train a single sklearn clf def try_once(which: str): # logger.info(f"Train an example model for scenario: {which}") clf = ParallelA(dir_clf=get_clf(clf_name), mod_clf=get_clf(clf_name)) control = ControlModel_RandomGuess() model = {"upper": clf, "lower": clf, "aug": clf, "control": control}[which] use_aug = {"upper": False, "lower": False, "aug": True, "control": False}[which] doubles_in_train = {"upper": True, "lower": False, "aug": False, "control": True}[which] if doubles_in_train: x_train = torch.cat((train_single_feat, train_double_feat)) y_train = torch.cat((train_single_labels, train_double_labels)) else: x_train = train_single_feat y_train = train_single_labels if use_aug: x_aug, y_aug = embedding.feature_combination(train_single_feat, train_single_labels) # logger.info(f"Real singles: {len(x_train)}, augmented: {len(x_aug)}") if N_aug_each_class is not None: x_aug, y_aug = subset_each_class(x_aug, y_aug, N_aug_each_class) # logger.info(f"Subset augmented: {len(x_aug)}") x_train = torch.cat([x_train, x_aug]) y_train = torch.cat([y_train, y_aug]) x_test = torch.cat([test_single_feat, test_double_feat]) y_test = torch.cat([test_single_labels, test_double_labels]) # After (possibly) applying augmentation fn - then we can convert to numpy # That way, augmentation fn can assume its input to be torch tensor x_train = x_train.cpu().numpy() y_train = y_train.cpu().numpy() x_test = x_test.cpu().numpy() y_test = y_test.cpu().numpy() model.fit(x_train, y_train) preds = model.predict(x_test) cm = get_combo_conf_mat(y_test, preds) cm_counts = get_combo_conf_mat(y_test, preds, normalize=False) single_bal_acc = np.nanmean(np.diag(cm)[:8]) double_bal_acc = np.nanmean(np.diag(cm)[8:]) overall_bal_acc = np.nanmean(np.diag(cm)) return { "single_bal_acc": single_bal_acc, "double_bal_acc": double_bal_acc, "overall_bal_acc": overall_bal_acc, "confusion_matrix": cm, "confusion_matrix_counts": cm_counts, } return { # Train once with singles and doubles (upper-bound performance) "upper_bound": try_once("upper"), # Train once with only singles, no augmentation (lower-bound performance) "lower_bound": try_once("lower"), # Train once with singles only and augmentation "augmented": try_once("aug"), # Train once with a random model (lower-bound performance) # "control": try_once("control"), } def fresh_classifier_one_ckpt(ckpt, clf_name: str, n_aug: Optional[int]): embedding = LearnedEmbedding.load_from_checkpoint(ckpt) embedding.eval() per_subj_data = get_per_subj_data()
datamodule = DataModule(per_subj_data=per_subj_data, **embedding.hparams)
0
2023-11-01 21:12:05+00:00
12k
SqueezeAILab/LLMCompiler
src/chains/llm_math_chain.py
[ { "identifier": "Chain", "path": "src/chains/chain.py", "snippet": "class Chain(Serializable, Runnable[Dict[str, Any], Dict[str, Any]], ABC):\n \"\"\"Abstract base class for creating structured sequences of calls to components.\n\n Chains should be used to encode a sequence of calls to components ...
import ast import math import re import warnings import numexpr from typing import Any, Dict, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain.prompts.prompt import PromptTemplate from langchain.pydantic_v1 import Extra, root_validator from langchain.schema import BasePromptTemplate from langchain.schema.language_model import BaseLanguageModel from src.chains.chain import Chain from src.chains.llm_chain import LLMChain
9,431
"""Chain that interprets a prompt and executes python code to do math.""" from __future__ import annotations # flake8: noqa _PROMPT_TEMPLATE = """Translate a math problem into a expression that can be executed using Python's numexpr library. Use the output of running this code to answer the question. You MUST follow the following guidelines: - Do not use "where(...)" expressions in your code since it is not supported. - Do not use "fmax(...)" expression in your code since it is not supported. Use "max(...)" instead. - Never introduce a variable. For instance "gazelle_max_speed * 1.4" is not allowed. Pick up a correct number from the given context. Question: ${{Question with math problem.}} ```text ${{single line mathematical expression that solves the problem}} ``` ...numexpr.evaluate(text)... ```output ${{Output of running the code}} ``` Answer: ${{Answer}} Begin. Question: What is 37593 * 67? ```text 37593 * 67 ``` ...numexpr.evaluate("37593 * 67")... ```output 2518731 ``` Answer: 2518731 Question: 37593^(1/5) ```text 37593**(1/5) ``` ...numexpr.evaluate("37593**(1/5)")... ```output 8.222831614237718 ``` Answer: 8.222831614237718 Question: {question} """ PROMPT = PromptTemplate( input_variables=["question"], template=_PROMPT_TEMPLATE, ) # helper functions to handle min and max functions def compute_function(match): func, values = match.groups() # Extract numbers and remove commas from between digits numbers = [float(re.sub(r"(?<=\d),(?=\d)", "", v)) for v in values.split(",")] # Compute the min or max based on the detected function result = min(numbers) if func == "min" else max(numbers) return str(result) class MaxTransformer(ast.NodeTransformer): def visit_Call(self, node): self.generic_visit(node) # Apply the transformation to child nodes first if isinstance(node.func, ast.Name) and node.func.id in ("max", "min"): if all(isinstance(arg, (ast.Num, ast.Constant)) for arg in node.args): # Calculate the max value # print(node.args) args_as_strings = (ast.unparse(arg) for arg in node.args) args_str = ", ".join(args_as_strings) print(args_str) if node.func.id == "min": value = min( arg.n if isinstance(arg, ast.Num) else arg.value for arg in node.args ) else: value = max( arg.n if isinstance(arg, ast.Num) else arg.value for arg in node.args ) # Replace the max call with the max value directly return ast.copy_location(ast.Constant(value=value), node) return node def replace_min_max_functions(expression): # Parse the expression into an AST parsed_expression = ast.parse(expression, mode="eval") # Transform the AST transformer = MaxTransformer() transformed_ast = transformer.visit(parsed_expression) # Fix the missing locations in the AST transformed_ast = ast.fix_missing_locations(transformed_ast) # Compile the transformed AST compiled_code = compile(transformed_ast, "<string>", "eval") # Evaluate the compiled code result = eval(compiled_code) return str(result)
"""Chain that interprets a prompt and executes python code to do math.""" from __future__ import annotations # flake8: noqa _PROMPT_TEMPLATE = """Translate a math problem into a expression that can be executed using Python's numexpr library. Use the output of running this code to answer the question. You MUST follow the following guidelines: - Do not use "where(...)" expressions in your code since it is not supported. - Do not use "fmax(...)" expression in your code since it is not supported. Use "max(...)" instead. - Never introduce a variable. For instance "gazelle_max_speed * 1.4" is not allowed. Pick up a correct number from the given context. Question: ${{Question with math problem.}} ```text ${{single line mathematical expression that solves the problem}} ``` ...numexpr.evaluate(text)... ```output ${{Output of running the code}} ``` Answer: ${{Answer}} Begin. Question: What is 37593 * 67? ```text 37593 * 67 ``` ...numexpr.evaluate("37593 * 67")... ```output 2518731 ``` Answer: 2518731 Question: 37593^(1/5) ```text 37593**(1/5) ``` ...numexpr.evaluate("37593**(1/5)")... ```output 8.222831614237718 ``` Answer: 8.222831614237718 Question: {question} """ PROMPT = PromptTemplate( input_variables=["question"], template=_PROMPT_TEMPLATE, ) # helper functions to handle min and max functions def compute_function(match): func, values = match.groups() # Extract numbers and remove commas from between digits numbers = [float(re.sub(r"(?<=\d),(?=\d)", "", v)) for v in values.split(",")] # Compute the min or max based on the detected function result = min(numbers) if func == "min" else max(numbers) return str(result) class MaxTransformer(ast.NodeTransformer): def visit_Call(self, node): self.generic_visit(node) # Apply the transformation to child nodes first if isinstance(node.func, ast.Name) and node.func.id in ("max", "min"): if all(isinstance(arg, (ast.Num, ast.Constant)) for arg in node.args): # Calculate the max value # print(node.args) args_as_strings = (ast.unparse(arg) for arg in node.args) args_str = ", ".join(args_as_strings) print(args_str) if node.func.id == "min": value = min( arg.n if isinstance(arg, ast.Num) else arg.value for arg in node.args ) else: value = max( arg.n if isinstance(arg, ast.Num) else arg.value for arg in node.args ) # Replace the max call with the max value directly return ast.copy_location(ast.Constant(value=value), node) return node def replace_min_max_functions(expression): # Parse the expression into an AST parsed_expression = ast.parse(expression, mode="eval") # Transform the AST transformer = MaxTransformer() transformed_ast = transformer.visit(parsed_expression) # Fix the missing locations in the AST transformed_ast = ast.fix_missing_locations(transformed_ast) # Compile the transformed AST compiled_code = compile(transformed_ast, "<string>", "eval") # Evaluate the compiled code result = eval(compiled_code) return str(result)
class LLMMathChain(Chain):
0
2023-12-06 21:12:54+00:00
12k
bytedance/ImageDream
extern/ldm_zero123/models/diffusion/ddpm.py
[ { "identifier": "AutoencoderKL", "path": "extern/ldm_zero123/models/autoencoder.py", "snippet": "class AutoencoderKL(pl.LightningModule):\n def __init__(\n self,\n ddconfig,\n lossconfig,\n embed_dim,\n ckpt_path=None,\n ignore_keys=[],\n image_key=\"i...
import itertools import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn from contextlib import contextmanager, nullcontext from functools import partial from einops import rearrange, repeat from omegaconf import ListConfig from pytorch_lightning.utilities.rank_zero import rank_zero_only from torch.optim.lr_scheduler import LambdaLR from torchvision.utils import make_grid from tqdm import tqdm from extern.ldm_zero123.models.autoencoder import ( AutoencoderKL, IdentityFirstStage, VQModelInterface, ) from extern.ldm_zero123.models.diffusion.ddim import DDIMSampler from extern.ldm_zero123.modules.attention import CrossAttention from extern.ldm_zero123.modules.diffusionmodules.util import ( extract_into_tensor, make_beta_schedule, noise_like, ) from extern.ldm_zero123.modules.distributions.distributions import ( DiagonalGaussianDistribution, normal_kl, ) from extern.ldm_zero123.modules.ema import LitEma from extern.ldm_zero123.util import ( count_params, default, exists, instantiate_from_config, isimage, ismap, log_txt_as_img, mean_flat, )
10,530
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {"concat": "c_concat", "crossattn": "c_crossattn", "adm": "y"} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__( self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0.0, v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1.0, conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0.0, make_it_fit=False, ucg_training=None, ): super().__init__() assert parameterization in [ "eps", "x0", ], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print( f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode" ) self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema:
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {"concat": "c_concat", "crossattn": "c_crossattn", "adm": "y"} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__( self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0.0, v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1.0, conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0.0, make_it_fit=False, ucg_training=None, ): super().__init__() assert parameterization in [ "eps", "x0", ], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print( f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode" ) self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema:
self.model_ema = LitEma(self.model)
10
2023-12-13 21:09:37+00:00
12k
TencentARC/MotionCtrl
app.py
[ { "identifier": "CAMERA_MOTION_MODE", "path": "gradio_utils/camera_utils.py", "snippet": "CAMERA_MOTION_MODE = [\"Basic Camera Poses\", \"Provided Complex Camera Poses\", \"Custom Camera Poses\"]" }, { "identifier": "process_camera", "path": "gradio_utils/camera_utils.py", "snippet": "de...
import argparse import os import tempfile import cv2 import gradio as gr import imageio import numpy as np import torch import torchvision from functools import partial from omegaconf import OmegaConf from PIL import Image from pytorch_lightning import seed_everything from gradio_utils.camera_utils import CAMERA_MOTION_MODE, process_camera from gradio_utils.traj_utils import (OBJECT_MOTION_MODE, get_provided_traj, process_points, process_traj) from gradio_utils.utils import vis_camera from lvdm.models.samplers.ddim import DDIMSampler from main.evaluation.motionctrl_inference import (DEFAULT_NEGATIVE_PROMPT, load_model_checkpoint, post_prompt) from utils.utils import instantiate_from_config
8,274
global camera_dict if camera_dict['complex'] is not None: camera_dict['complex'] = None if camera_mode == CAMERA_MOTION_MODE[2] and len(camera_dict['motion']) <2: camera_dict['motion'].append(camera_motion) else: camera_dict['motion']=[camera_motion] return display_camera_info(camera_dict, camera_mode) def add_complex_camera_motion(camera_motion): global camera_dict camera_dict['complex']=camera_motion return display_camera_info(camera_dict) def change_camera_mode(combine_type, camera_mode): global camera_dict camera_dict['mode'] = combine_type return display_camera_info(camera_dict, camera_mode) def change_camera_speed(camera_speed): global camera_dict camera_dict['speed'] = camera_speed return display_camera_info(camera_dict) def reset_camera(): global camera_dict camera_dict = { "motion":[], "mode": "Customized Mode 1: First A then B", "speed": 1.0, "complex": None } return display_camera_info(camera_dict) def fn_traj_droplast(): global traj_list if traj_list: traj_list.pop() if traj_list: traj_str = [f"{traj}" for traj in traj_list] return ", ".join(traj_str) else: return "Click to specify trajectory" def fn_traj_reset(): global traj_list traj_list = [] return "Click to specify trajectory" ########################################### model_path='./checkpoints/motionctrl.pth' config_path='./configs/inference/config_both.yaml' config = OmegaConf.load(config_path) model_config = config.pop("model", OmegaConf.create()) model = instantiate_from_config(model_config) if torch.cuda.is_available(): model = model.cuda() model = load_model_checkpoint(model, model_path) model.eval() def model_run(prompts, infer_mode, seed, n_samples): global traj_list global camera_dict RT = process_camera(camera_dict).reshape(-1,12) traj_flow = process_traj(traj_list).transpose(3,0,1,2) print(prompts) print(RT.shape) print(traj_flow.shape) noise_shape = [1, 4, 16, 32, 32] unconditional_guidance_scale = 7.5 unconditional_guidance_scale_temporal = None # n_samples = 1 ddim_steps= 50 ddim_eta=1.0 cond_T=800 if n_samples < 1: n_samples = 1 if n_samples > 4: n_samples = 4 seed_everything(seed) if infer_mode == MODE[0]: camera_poses = RT camera_poses = torch.tensor(camera_poses).float() camera_poses = camera_poses.unsqueeze(0) trajs = None if torch.cuda.is_available(): camera_poses = camera_poses.cuda() elif infer_mode == MODE[1]: trajs = traj_flow trajs = torch.tensor(trajs).float() trajs = trajs.unsqueeze(0) camera_poses = None if torch.cuda.is_available(): trajs = trajs.cuda() else: camera_poses = RT trajs = traj_flow camera_poses = torch.tensor(camera_poses).float() trajs = torch.tensor(trajs).float() camera_poses = camera_poses.unsqueeze(0) trajs = trajs.unsqueeze(0) if torch.cuda.is_available(): camera_poses = camera_poses.cuda() trajs = trajs.cuda()
os.environ['KMP_DUPLICATE_LIB_OK']='True' SPACE_ID = os.environ.get('SPACE_ID', '') #### Description #### title = r"""<h1 align="center">MotionCtrl: A Unified and Flexible Motion Controller for Video Generation</h1>""" description = r""" <b>Official Gradio demo</b> for <a href='https://github.com/TencentARC/MotionCtrl' target='_blank'><b>MotionCtrl: A Unified and Flexible Motion Controller for Video Generation</b></a>.<br> 🔥 MotionCtrl is capable of independently and flexibly controling the camera motion and object motion of a generated video, with only a unified model.<br> 🤗 Try to control the motion of the generated videos yourself!<br> ❗❗❗ Please note that current version of **MotionCtrl** is deployed on **LVDM/VideoCrafter**. The versions that depolyed on **AnimateDiff** and **SVD** will be released soon.<br> """ article = r""" If MotionCtrl is helpful, please help to ⭐ the <a href='https://github.com/TencentARC/MotionCtrl' target='_blank'>Github Repo</a>. Thanks! [![GitHub Stars](https://img.shields.io/github/stars/TencentARC%2FMotionCtrl )](https://github.com/TencentARC/MotionCtrl) --- 📝 **Citation** <br> If our work is useful for your research, please consider citing: ```bibtex @inproceedings{wang2023motionctrl, title={MotionCtrl: A Unified and Flexible Motion Controller for Video Generation}, author={Wang, Zhouxia and Yuan, Ziyang and Wang, Xintao and Chen, Tianshui and Xia, Menghan and Luo, Ping and Shan, Yin}, booktitle={arXiv preprint arXiv:2312.03641}, year={2023} } ``` 📧 **Contact** <br> If you have any questions, please feel free to reach me out at <b>wzhoux@connect.hku.hk</b>. """ css = """ .gradio-container {width: 85% !important} .gr-monochrome-group {border-radius: 5px !important; border: revert-layer !important; border-width: 2px !important; color: black !important;} span.svelte-s1r2yt {font-size: 17px !important; font-weight: bold !important; color: #d30f2f !important;} button {border-radius: 8px !important;} .add_button {background-color: #4CAF50 !important;} .remove_button {background-color: #f44336 !important;} .clear_button {background-color: gray !important;} .mask_button_group {gap: 10px !important;} .video {height: 300px !important;} .image {height: 300px !important;} .video .wrap.svelte-lcpz3o {display: flex !important; align-items: center !important; justify-content: center !important;} .video .wrap.svelte-lcpz3o > :first-child {height: 100% !important;} .margin_center {width: 50% !important; margin: auto !important;} .jc_center {justify-content: center !important;} """ T_base = [ [1.,0.,0.], ## W2C left [-1.,0.,0.], ## W2C right [0., 1., 0.], ## W2C up [0.,-1.,0.], ## W2C down [0.,0.,1.], ## W2C zoom out [0.,0.,-1.], ## W2C zoom in ] radius = 1 n = 16 # step = look_at = np.array([0, 0, 0.8]).reshape(3,1) # look_at = np.array([0, 0, 0.2]).reshape(3,1) T_list = [] base_R = np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) res = [] res_forsave = [] T_range = 1.8 for i in range(0, 16): # theta = (1)*np.pi*i/n R = base_R[:,:3] T = np.array([0.,0.,1.]).reshape(3,1) * (i/n)*2 RT = np.concatenate([R,T], axis=1) res.append(RT) fig = vis_camera(res) # MODE = ["camera motion control", "object motion control", "camera + object motion control"] MODE = ["control camera poses", "control object trajectory", "control both camera and object motion"] BASE_MODEL = ['LVDM/VideoCrafter', 'AnimateDiff', 'SVD'] traj_list = [] camera_dict = { "motion":[], "mode": "Customized Mode 1: First A then B", # "First A then B", "Both A and B", "Custom" "speed": 1.0, "complex": None } def fn_vis_camera(info_mode): global camera_dict RT = process_camera(camera_dict) # [t, 3, 4] if camera_dict['complex'] is not None: # rescale T to [-2,2] for i in range(3): min_T = np.min(RT[:,i,-1]) max_T = np.max(RT[:,i,-1]) if min_T < -2 or max_T > 2: RT[:,i,-1] = RT[:,i,-1] - min_T RT[:,i,-1] = RT[:,i,-1] / (np.max(RT[:,:,-1]) + 1e-6) RT[:,i,-1] = RT[:,i,-1] * 4 RT[:,i,-1] = RT[:,i,-1] - 2 fig = vis_camera(RT) if info_mode == MODE[0]: vis_step3_prompt_generate = True vis_prompt = True vis_num_samples = True vis_seed = True vis_start = True vis_gen_video = True vis_object_mode = False vis_object_info = False else: vis_step3_prompt_generate = False vis_prompt = False vis_num_samples = False vis_seed = False vis_start = False vis_gen_video = False vis_object_mode = True vis_object_info = True return fig, \ gr.update(visible=vis_object_mode), \ gr.update(visible=vis_object_info), \ gr.update(visible=vis_step3_prompt_generate), \ gr.update(visible=vis_prompt), \ gr.update(visible=vis_num_samples), \ gr.update(visible=vis_seed), \ gr.update(visible=vis_start), \ gr.update(visible=vis_gen_video, value=None) def fn_vis_traj(): global traj_list xy_range = 1024 points = process_points(traj_list) imgs = [] for idx in range(16): bg_img = np.ones((1024, 1024, 3), dtype=np.uint8) * 255 for i in range(15): p = points[i] p1 = points[i+1] cv2.line(bg_img, p, p1, (255, 0, 0), 2) if i == idx: cv2.circle(bg_img, p, 2, (0, 255, 0), 20) if idx==(15): cv2.circle(bg_img, points[-1], 2, (0, 255, 0), 20) imgs.append(bg_img.astype(np.uint8)) # size = (512, 512) fps = 10 path = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name writer = imageio.get_writer(path, format='mp4', mode='I', fps=fps) for img in imgs: writer.append_data(img) writer.close() vis_step3_prompt_generate = True vis_prompt = True vis_num_samples = True vis_seed = True vis_start = True vis_gen_video = True return path, gr.update(visible=vis_step3_prompt_generate), \ gr.update(visible=vis_prompt), \ gr.update(visible=vis_num_samples), \ gr.update(visible=vis_seed), \ gr.update(visible=vis_start), \ gr.update(visible=vis_gen_video, value=None) def display_camera_info(camera_dict, camera_mode=None): if camera_dict['complex'] is not None: res = f"complex : {camera_dict['complex']}. " else: res = "" res += f"motion : {[_ for _ in camera_dict['motion']]}. " res += f"speed : {camera_dict['speed']}. " if camera_mode == CAMERA_MOTION_MODE[2]: res += f"mode : {camera_dict['mode']}. " return res def add_traj_point(evt: gr.SelectData, ): global traj_list traj_list.append(evt.index) traj_str = [f"{traj}" for traj in traj_list] return ", ".join(traj_str) def add_provided_traj(traj_name): global traj_list traj_list = get_provided_traj(traj_name) traj_str = [f"{traj}" for traj in traj_list] return ", ".join(traj_str) def add_camera_motion(camera_motion, camera_mode): global camera_dict if camera_dict['complex'] is not None: camera_dict['complex'] = None if camera_mode == CAMERA_MOTION_MODE[2] and len(camera_dict['motion']) <2: camera_dict['motion'].append(camera_motion) else: camera_dict['motion']=[camera_motion] return display_camera_info(camera_dict, camera_mode) def add_complex_camera_motion(camera_motion): global camera_dict camera_dict['complex']=camera_motion return display_camera_info(camera_dict) def change_camera_mode(combine_type, camera_mode): global camera_dict camera_dict['mode'] = combine_type return display_camera_info(camera_dict, camera_mode) def change_camera_speed(camera_speed): global camera_dict camera_dict['speed'] = camera_speed return display_camera_info(camera_dict) def reset_camera(): global camera_dict camera_dict = { "motion":[], "mode": "Customized Mode 1: First A then B", "speed": 1.0, "complex": None } return display_camera_info(camera_dict) def fn_traj_droplast(): global traj_list if traj_list: traj_list.pop() if traj_list: traj_str = [f"{traj}" for traj in traj_list] return ", ".join(traj_str) else: return "Click to specify trajectory" def fn_traj_reset(): global traj_list traj_list = [] return "Click to specify trajectory" ########################################### model_path='./checkpoints/motionctrl.pth' config_path='./configs/inference/config_both.yaml' config = OmegaConf.load(config_path) model_config = config.pop("model", OmegaConf.create()) model = instantiate_from_config(model_config) if torch.cuda.is_available(): model = model.cuda() model = load_model_checkpoint(model, model_path) model.eval() def model_run(prompts, infer_mode, seed, n_samples): global traj_list global camera_dict RT = process_camera(camera_dict).reshape(-1,12) traj_flow = process_traj(traj_list).transpose(3,0,1,2) print(prompts) print(RT.shape) print(traj_flow.shape) noise_shape = [1, 4, 16, 32, 32] unconditional_guidance_scale = 7.5 unconditional_guidance_scale_temporal = None # n_samples = 1 ddim_steps= 50 ddim_eta=1.0 cond_T=800 if n_samples < 1: n_samples = 1 if n_samples > 4: n_samples = 4 seed_everything(seed) if infer_mode == MODE[0]: camera_poses = RT camera_poses = torch.tensor(camera_poses).float() camera_poses = camera_poses.unsqueeze(0) trajs = None if torch.cuda.is_available(): camera_poses = camera_poses.cuda() elif infer_mode == MODE[1]: trajs = traj_flow trajs = torch.tensor(trajs).float() trajs = trajs.unsqueeze(0) camera_poses = None if torch.cuda.is_available(): trajs = trajs.cuda() else: camera_poses = RT trajs = traj_flow camera_poses = torch.tensor(camera_poses).float() trajs = torch.tensor(trajs).float() camera_poses = camera_poses.unsqueeze(0) trajs = trajs.unsqueeze(0) if torch.cuda.is_available(): camera_poses = camera_poses.cuda() trajs = trajs.cuda()
ddim_sampler = DDIMSampler(model)
7
2023-12-06 07:27:45+00:00
12k
TianxingWu/FreeInit
examples/AnimateDiff/animatediff/pipelines/pipeline_animation.py
[ { "identifier": "UNet3DConditionModel", "path": "examples/AnimateDiff/animatediff/models/unet.py", "snippet": "class UNet3DConditionModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n sample_size: Optional[int...
import inspect import numpy as np import torch import os from typing import Callable, List, Optional, Union from dataclasses import dataclass from tqdm import tqdm from diffusers.utils import is_accelerate_available from packaging import version from transformers import CLIPTextModel, CLIPTokenizer from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL from diffusers.pipeline_utils import DiffusionPipeline from diffusers.schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from diffusers.utils import deprecate, logging, BaseOutput from einops import rearrange from ..models.unet import UNet3DConditionModel from ..utils.freeinit_utils import ( get_freq_filter, freq_mix_3d, ) from ..utils.util import save_videos_grid from accelerate import cpu_offload
8,736
width = width or self.unet.config.sample_size * self.vae_scale_factor # Check inputs. Raise error if not correct # import pdb # pdb.set_trace() self.check_inputs(prompt, height, width, callback_steps) # Define call parameters # batch_size = 1 if isinstance(prompt, str) else len(prompt) batch_size = 1 if latents is not None: batch_size = latents.shape[0] if isinstance(prompt, list): batch_size = len(prompt) device = self._execution_device # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. do_classifier_free_guidance = guidance_scale > 1.0 # Encode input prompt prompt = prompt if isinstance(prompt, list) else [prompt] * batch_size if negative_prompt is not None: negative_prompt = negative_prompt if isinstance(negative_prompt, list) else [negative_prompt] * batch_size text_embeddings = self._encode_prompt( prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt ) # Prepare timesteps self.scheduler.set_timesteps(num_inference_steps, device=device) timesteps = self.scheduler.timesteps # Prepare latent variables num_channels_latents = self.unet.in_channels latents = self.prepare_latents( batch_size * num_videos_per_prompt, num_channels_latents, video_length, height, width, text_embeddings.dtype, device, generator, latents, ) latents_dtype = latents.dtype # Prepare extra step kwargs. extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) # Sampling with FreeInit. for iter in range(num_iters): # FreeInit ------------------------------------------------------------------ if iter == 0: initial_noise = latents.detach().clone() else: # 1. DDPM Forward with initial noise, get noisy latents z_T # if use_fast_sampling: # current_diffuse_timestep = self.scheduler.config.num_train_timesteps / num_iters * (iter + 1) - 1 # else: # current_diffuse_timestep = self.scheduler.config.num_train_timesteps - 1 current_diffuse_timestep = self.scheduler.config.num_train_timesteps - 1 # diffuse to t=999 noise level diffuse_timesteps = torch.full((batch_size,),int(current_diffuse_timestep)) diffuse_timesteps = diffuse_timesteps.long() z_T = self.scheduler.add_noise( original_samples=latents.to(device), noise=initial_noise.to(device), timesteps=diffuse_timesteps.to(device) ) # 2. create random noise z_rand for high-frequency z_rand = torch.randn((batch_size * num_videos_per_prompt, num_channels_latents, video_length, height // self.vae_scale_factor, width // self.vae_scale_factor), device=device) # 3. Roise Reinitialization latents = freq_mix_3d(z_T.to(dtype=torch.float32), z_rand, LPF=self.freq_filter) latents = latents.to(latents_dtype) # Coarse-to-Fine Sampling for Fast Inference (can lead to sub-optimal results) if use_fast_sampling: current_num_inference_steps= int(num_inference_steps / num_iters * (iter + 1)) self.scheduler.set_timesteps(current_num_inference_steps, device=device) timesteps = self.scheduler.timesteps # -------------------------------------------------------------------------- # Denoising loop num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order with self.progress_bar(total=num_inference_steps) as progress_bar: # if use_fast_sampling: # # Coarse-to-Fine Sampling for Fast Inference # current_num_inference_steps= int(num_inference_steps / num_iters * (iter + 1)) # current_timesteps = timesteps[:current_num_inference_steps] # else: current_timesteps = timesteps for i, t in enumerate(current_timesteps): # expand the latents if we are doing classifier free guidance latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) # predict the noise residual noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample.to(dtype=latents_dtype) # perform guidance if do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample # call the callback, if provided if i == len(current_timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): progress_bar.update() if callback is not None and i % callback_steps == 0: callback(i, t, latents) # save intermediate results if save_intermediate: # Post-processing video = self.decode_latents(latents) video = torch.from_numpy(video) os.makedirs(save_dir, exist_ok=True)
# Adapted from https://github.com/showlab/Tune-A-Video/blob/main/tuneavideo/pipelines/pipeline_tuneavideo.py logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class AnimationPipelineOutput(BaseOutput): videos: Union[torch.Tensor, np.ndarray] @dataclass class AnimationFreeInitPipelineOutput(BaseOutput): videos: Union[torch.Tensor, np.ndarray] orig_videos: Union[torch.Tensor, np.ndarray] class AnimationPipeline(DiffusionPipeline): _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet3DConditionModel, scheduler: Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ], ): super().__init__() if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: deprecation_message = ( f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(scheduler.config) new_config["steps_offset"] = 1 scheduler._internal_dict = FrozenDict(new_config) if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: deprecation_message = ( f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`." " `clip_sample` should be set to False in the configuration file. Please make sure to update the" " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in" " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very" " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file" ) deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(scheduler.config) new_config["clip_sample"] = False scheduler._internal_dict = FrozenDict(new_config) is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse( version.parse(unet.config._diffusers_version).base_version ) < version.parse("0.9.0.dev0") is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: deprecation_message = ( "The configuration file of the unet has set the default `sample_size` to smaller than" " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the" " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" " in the config might lead to incorrect results in future versions. If you have downloaded this" " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" " the `unet/config.json` file" ) deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(unet.config) new_config["sample_size"] = 64 unet._internal_dict = FrozenDict(new_config) self.register_modules( vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, scheduler=scheduler, ) self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) def enable_vae_slicing(self): self.vae.enable_slicing() def disable_vae_slicing(self): self.vae.disable_slicing() def enable_sequential_cpu_offload(self, gpu_id=0): if is_accelerate_available(): else: raise ImportError("Please install accelerate via `pip install accelerate`") device = torch.device(f"cuda:{gpu_id}") for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]: if cpu_offloaded_model is not None: cpu_offload(cpu_offloaded_model, device) @property def _execution_device(self): if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"): return self.device for module in self.unet.modules(): if ( hasattr(module, "_hf_hook") and hasattr(module._hf_hook, "execution_device") and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device) return self.device def _encode_prompt(self, prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt): batch_size = len(prompt) if isinstance(prompt, list) else 1 text_inputs = self.tokenizer( prompt, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt", ) text_input_ids = text_inputs.input_ids untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids): removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" f" {self.tokenizer.model_max_length} tokens: {removed_text}" ) if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: attention_mask = text_inputs.attention_mask.to(device) else: attention_mask = None text_embeddings = self.text_encoder( text_input_ids.to(device), attention_mask=attention_mask, ) text_embeddings = text_embeddings[0] # duplicate text embeddings for each generation per prompt, using mps friendly method bs_embed, seq_len, _ = text_embeddings.shape text_embeddings = text_embeddings.repeat(1, num_videos_per_prompt, 1) text_embeddings = text_embeddings.view(bs_embed * num_videos_per_prompt, seq_len, -1) # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: uncond_tokens: List[str] if negative_prompt is None: uncond_tokens = [""] * batch_size elif type(prompt) is not type(negative_prompt): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" f" {type(prompt)}." ) elif isinstance(negative_prompt, str): uncond_tokens = [negative_prompt] elif batch_size != len(negative_prompt): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" " the batch size of `prompt`." ) else: uncond_tokens = negative_prompt max_length = text_input_ids.shape[-1] uncond_input = self.tokenizer( uncond_tokens, padding="max_length", max_length=max_length, truncation=True, return_tensors="pt", ) if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: attention_mask = uncond_input.attention_mask.to(device) else: attention_mask = None uncond_embeddings = self.text_encoder( uncond_input.input_ids.to(device), attention_mask=attention_mask, ) uncond_embeddings = uncond_embeddings[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method seq_len = uncond_embeddings.shape[1] uncond_embeddings = uncond_embeddings.repeat(1, num_videos_per_prompt, 1) uncond_embeddings = uncond_embeddings.view(batch_size * num_videos_per_prompt, seq_len, -1) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes text_embeddings = torch.cat([uncond_embeddings, text_embeddings]) return text_embeddings def decode_latents(self, latents): video_length = latents.shape[2] latents = 1 / 0.18215 * latents latents = rearrange(latents, "b c f h w -> (b f) c h w") # video = self.vae.decode(latents).sample video = [] for frame_idx in tqdm(range(latents.shape[0])): video.append(self.vae.decode(latents[frame_idx:frame_idx+1]).sample) video = torch.cat(video) video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length) video = (video / 2 + 0.5).clamp(0, 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16 video = video.cpu().float().numpy() return video def prepare_extra_step_kwargs(self, generator, eta): # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) extra_step_kwargs = {} if accepts_eta: extra_step_kwargs["eta"] = eta # check if the scheduler accepts generator accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) if accepts_generator: extra_step_kwargs["generator"] = generator return extra_step_kwargs def check_inputs(self, prompt, height, width, callback_steps): if not isinstance(prompt, str) and not isinstance(prompt, list): raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") if height % 8 != 0 or width % 8 != 0: raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") if (callback_steps is None) or ( callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) ): raise ValueError( f"`callback_steps` has to be a positive integer but is {callback_steps} of type" f" {type(callback_steps)}." ) def prepare_latents(self, batch_size, num_channels_latents, video_length, height, width, dtype, device, generator, latents=None): shape = (batch_size, num_channels_latents, video_length, height // self.vae_scale_factor, width // self.vae_scale_factor) if isinstance(generator, list) and len(generator) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." ) if latents is None: rand_device = "cpu" if device.type == "mps" else device if isinstance(generator, list): shape = shape # shape = (1,) + shape[1:] latents = [ torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype) for i in range(batch_size) ] latents = torch.cat(latents, dim=0).to(device) else: latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype).to(device) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}") latents = latents.to(device) # scale the initial noise by the standard deviation required by the scheduler latents = latents * self.scheduler.init_noise_sigma return latents @torch.no_grad() def __call__( self, prompt: Union[str, List[str]], video_length: Optional[int], height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: Optional[Union[str, List[str]]] = None, num_videos_per_prompt: Optional[int] = 1, eta: float = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.FloatTensor] = None, output_type: Optional[str] = "tensor", return_dict: bool = True, callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, callback_steps: Optional[int] = 1, **kwargs, ): # Default height and width to unet height = height or self.unet.config.sample_size * self.vae_scale_factor width = width or self.unet.config.sample_size * self.vae_scale_factor # Check inputs. Raise error if not correct self.check_inputs(prompt, height, width, callback_steps) # Define call parameters # batch_size = 1 if isinstance(prompt, str) else len(prompt) batch_size = 1 if latents is not None: batch_size = latents.shape[0] if isinstance(prompt, list): batch_size = len(prompt) device = self._execution_device # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. do_classifier_free_guidance = guidance_scale > 1.0 # Encode input prompt prompt = prompt if isinstance(prompt, list) else [prompt] * batch_size if negative_prompt is not None: negative_prompt = negative_prompt if isinstance(negative_prompt, list) else [negative_prompt] * batch_size text_embeddings = self._encode_prompt( prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt ) # Prepare timesteps self.scheduler.set_timesteps(num_inference_steps, device=device) timesteps = self.scheduler.timesteps # Prepare latent variables num_channels_latents = self.unet.in_channels latents = self.prepare_latents( batch_size * num_videos_per_prompt, num_channels_latents, video_length, height, width, text_embeddings.dtype, device, generator, latents, ) latents_dtype = latents.dtype # Prepare extra step kwargs. extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) # Denoising loop num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order with self.progress_bar(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): # expand the latents if we are doing classifier free guidance latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) # predict the noise residual noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample.to(dtype=latents_dtype) # perform guidance if do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample # call the callback, if provided if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): progress_bar.update() if callback is not None and i % callback_steps == 0: callback(i, t, latents) # Post-processing video = self.decode_latents(latents) # Convert to tensor if output_type == "tensor": video = torch.from_numpy(video) if not return_dict: return video return AnimationPipelineOutput(videos=video) class AnimationFreeInitPipeline(AnimationPipeline): _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet3DConditionModel, scheduler: Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ], ): super().__init__(vae, text_encoder, tokenizer, unet, scheduler) self.freq_filter = None @torch.no_grad() def init_filter(self, video_length, height, width, filter_params): # initialize frequency filter for noise reinitialization batch_size = 1 num_channels_latents = self.unet.in_channels filter_shape = [ batch_size, num_channels_latents, video_length, height // self.vae_scale_factor, width // self.vae_scale_factor ] # self.freq_filter = get_freq_filter(filter_shape, device=self._execution_device, params=filter_params) self.freq_filter = get_freq_filter( filter_shape, device=self._execution_device, filter_type=filter_params.method, n=filter_params.n if filter_params.method=="butterworth" else None, d_s=filter_params.d_s, d_t=filter_params.d_t ) @torch.no_grad() def __call__( self, prompt: Union[str, List[str]], video_length: Optional[int], height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: Optional[Union[str, List[str]]] = None, num_videos_per_prompt: Optional[int] = 1, eta: float = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.FloatTensor] = None, output_type: Optional[str] = "tensor", return_dict: bool = True, callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, callback_steps: Optional[int] = 1, # freeinit args num_iters: int = 5, use_fast_sampling: bool = False, save_intermediate: bool = False, return_orig: bool = False, save_dir: str = None, save_name: str = None, use_fp16: bool = False, **kwargs ): if use_fp16: print('Warning: using half percision for inferencing!') self.vae.to(dtype=torch.float16) self.unet.to(dtype=torch.float16) self.text_encoder.to(dtype=torch.float16) # Default height and width to unet height = height or self.unet.config.sample_size * self.vae_scale_factor width = width or self.unet.config.sample_size * self.vae_scale_factor # Check inputs. Raise error if not correct # import pdb # pdb.set_trace() self.check_inputs(prompt, height, width, callback_steps) # Define call parameters # batch_size = 1 if isinstance(prompt, str) else len(prompt) batch_size = 1 if latents is not None: batch_size = latents.shape[0] if isinstance(prompt, list): batch_size = len(prompt) device = self._execution_device # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. do_classifier_free_guidance = guidance_scale > 1.0 # Encode input prompt prompt = prompt if isinstance(prompt, list) else [prompt] * batch_size if negative_prompt is not None: negative_prompt = negative_prompt if isinstance(negative_prompt, list) else [negative_prompt] * batch_size text_embeddings = self._encode_prompt( prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt ) # Prepare timesteps self.scheduler.set_timesteps(num_inference_steps, device=device) timesteps = self.scheduler.timesteps # Prepare latent variables num_channels_latents = self.unet.in_channels latents = self.prepare_latents( batch_size * num_videos_per_prompt, num_channels_latents, video_length, height, width, text_embeddings.dtype, device, generator, latents, ) latents_dtype = latents.dtype # Prepare extra step kwargs. extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) # Sampling with FreeInit. for iter in range(num_iters): # FreeInit ------------------------------------------------------------------ if iter == 0: initial_noise = latents.detach().clone() else: # 1. DDPM Forward with initial noise, get noisy latents z_T # if use_fast_sampling: # current_diffuse_timestep = self.scheduler.config.num_train_timesteps / num_iters * (iter + 1) - 1 # else: # current_diffuse_timestep = self.scheduler.config.num_train_timesteps - 1 current_diffuse_timestep = self.scheduler.config.num_train_timesteps - 1 # diffuse to t=999 noise level diffuse_timesteps = torch.full((batch_size,),int(current_diffuse_timestep)) diffuse_timesteps = diffuse_timesteps.long() z_T = self.scheduler.add_noise( original_samples=latents.to(device), noise=initial_noise.to(device), timesteps=diffuse_timesteps.to(device) ) # 2. create random noise z_rand for high-frequency z_rand = torch.randn((batch_size * num_videos_per_prompt, num_channels_latents, video_length, height // self.vae_scale_factor, width // self.vae_scale_factor), device=device) # 3. Roise Reinitialization latents = freq_mix_3d(z_T.to(dtype=torch.float32), z_rand, LPF=self.freq_filter) latents = latents.to(latents_dtype) # Coarse-to-Fine Sampling for Fast Inference (can lead to sub-optimal results) if use_fast_sampling: current_num_inference_steps= int(num_inference_steps / num_iters * (iter + 1)) self.scheduler.set_timesteps(current_num_inference_steps, device=device) timesteps = self.scheduler.timesteps # -------------------------------------------------------------------------- # Denoising loop num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order with self.progress_bar(total=num_inference_steps) as progress_bar: # if use_fast_sampling: # # Coarse-to-Fine Sampling for Fast Inference # current_num_inference_steps= int(num_inference_steps / num_iters * (iter + 1)) # current_timesteps = timesteps[:current_num_inference_steps] # else: current_timesteps = timesteps for i, t in enumerate(current_timesteps): # expand the latents if we are doing classifier free guidance latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) # predict the noise residual noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample.to(dtype=latents_dtype) # perform guidance if do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample # call the callback, if provided if i == len(current_timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): progress_bar.update() if callback is not None and i % callback_steps == 0: callback(i, t, latents) # save intermediate results if save_intermediate: # Post-processing video = self.decode_latents(latents) video = torch.from_numpy(video) os.makedirs(save_dir, exist_ok=True)
save_videos_grid(video, f"{save_dir}/{save_name}_iter{iter}.gif")
3
2023-12-12 13:11:24+00:00
12k
allenai/unified-io-2
t5x/trainer_test.py
[ { "identifier": "metrics", "path": "t5x/metrics.py", "snippet": "def _check_param(value, *, ndim=None, dtype=jnp.float32):\n def from_model_output(cls, values: Scalar, **_) -> clu_metrics.Metric:\n def merge(self, other: \"Sum\") -> \"Sum\":\n def compute(self) -> Scalar:\n def replace_steps(self, s...
import collections import contextlib import os import chex import clu.metrics import clu.values import flax import jax import jax.numpy as jnp import numpy as np import tensorflow as tf from absl.testing import absltest from absl.testing import parameterized from clu import metric_writers from jax._src import dispatch as jax_dispatch from t5x import metrics as metrics_lib from t5x import models as models_lib from t5x import optimizers from t5x import partitioning from t5x import test_utils from t5x import train_state as train_state_lib from t5x import trainer as trainer_lib from tensorflow.io import gfile
10,061
"""Tests for t5x.trainer_lib.""" mock = absltest.mock jax.config.parse_flags_with_absl() FlaxMutables = flax.core.FrozenDict # Make `log_elapsed_time` a no-op to simplify mocking of `time.time()`. @contextlib.contextmanager def fake_log_elapsed_time(_): yield jax_dispatch.log_elapsed_time = fake_log_elapsed_time def _validate_events(test_case, summary_dir, expected_metrics, steps): summaries = gfile.listdir(summary_dir) test_case.assertLen(summaries, 1) summary_path = os.path.join(summary_dir, summaries[0]) event_file = os.path.join(summary_path) events = list(tf.compat.v1.train.summary_iterator(event_file)) actual_events = {} # First event is boilerplate test_case.assertLen(events, len(steps) + 1) for step, event in zip(steps, events[1:]): test_case.assertEqual(event.step, step) test_case.assertLen(event.summary.value, 1) tensor = event.summary.value[0].tensor if tensor.string_val: actual_events[event.summary.value[0].tag] = tensor.string_val[0].decode() else: actual_events[event.summary.value[0].tag] = float(tf.make_ndarray(tensor)) <<<<<<< HEAD jax.tree_map(test_case.assertAlmostEqual, actual_events, expected_metrics) ======= jax.tree_map(test_case.assertAlmostEqual, actual_events, expected_metrics) >>>>>>> 1f8cec78b1f28f1955d70741792d7b6e7dd76226 class MetricsManagerTest(absltest.TestCase): def setUp(self): super().setUp() self.model_dir = self.create_tempdir().full_path def test_summary_dir(self): # All hosts have the summary dir. with mock.patch('jax.process_index', return_value=0): mm = trainer_lib.MetricsManager('eval', self.model_dir) self.assertEqual(mm.summary_dir, os.path.join(self.model_dir, 'eval')) mm.close() with mock.patch('jax.process_index', return_value=1): mm = trainer_lib.MetricsManager('eval', self.model_dir) self.assertEqual(mm.summary_dir, os.path.join(self.model_dir, 'eval')) mm.close() def test_summary_writer(self): # Only host 0 creates a non-empty summary writer. with mock.patch('jax.process_index', return_value=1): mm = trainer_lib.MetricsManager('eval', self.model_dir) self.assertFalse(gfile.exists(mm.summary_dir)) mm.close() with mock.patch('jax.process_index', return_value=0): mm = trainer_lib.MetricsManager('eval', self.model_dir) self.assertIsInstance(mm.summary_writer, metric_writers.MetricWriter) self.assertTrue(gfile.exists(mm.summary_dir)) mm.close() def test_write_scalar(self): gfile.makedirs(os.path.join(self.model_dir, 'eval')) # tag, value, step scalars = [('loss', 1.0, 1), ('accuracy', 100.0, 2)] # Only host 0 has actually writes summaries. with mock.patch('jax.process_index', return_value=1): mm = trainer_lib.MetricsManager('eval', self.model_dir) for s in scalars: mm.write_scalar(*s) self.assertEmpty(gfile.listdir(mm.summary_dir)) mm.close() with mock.patch('jax.process_index', return_value=0): mm = trainer_lib.MetricsManager('eval', self.model_dir) for s in scalars: mm.write_scalar(*s) mm.flush() summaries = gfile.listdir(mm.summary_dir) self.assertLen(summaries, 1) event_file = os.path.join(mm.summary_dir, summaries[0]) events = list(tf.compat.v1.train.summary_iterator(event_file)) # First event is boilerplate self.assertLen(events, 3) for event, (tag, value, step) in zip(events[1:], scalars): self.assertEqual(event.step, step) self.assertLen(event.summary.value, 1) self.assertEqual(event.summary.value[0].tag, tag) self.assertEqual(tf.make_ndarray(event.summary.value[0].tensor), value) mm.close() def test_write_metrics_summary(self): gfile.makedirs(os.path.join(self.model_dir, 'eval')) @flax.struct.dataclass class MockTextMetric(clu.metrics.Metric): def compute_value(self): return clu.values.Text('test metric') accumulated_metrics = {
# Copyright 2022 The T5X Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for t5x.trainer_lib.""" mock = absltest.mock jax.config.parse_flags_with_absl() FlaxMutables = flax.core.FrozenDict # Make `log_elapsed_time` a no-op to simplify mocking of `time.time()`. @contextlib.contextmanager def fake_log_elapsed_time(_): yield jax_dispatch.log_elapsed_time = fake_log_elapsed_time def _validate_events(test_case, summary_dir, expected_metrics, steps): summaries = gfile.listdir(summary_dir) test_case.assertLen(summaries, 1) summary_path = os.path.join(summary_dir, summaries[0]) event_file = os.path.join(summary_path) events = list(tf.compat.v1.train.summary_iterator(event_file)) actual_events = {} # First event is boilerplate test_case.assertLen(events, len(steps) + 1) for step, event in zip(steps, events[1:]): test_case.assertEqual(event.step, step) test_case.assertLen(event.summary.value, 1) tensor = event.summary.value[0].tensor if tensor.string_val: actual_events[event.summary.value[0].tag] = tensor.string_val[0].decode() else: actual_events[event.summary.value[0].tag] = float(tf.make_ndarray(tensor)) <<<<<<< HEAD jax.tree_map(test_case.assertAlmostEqual, actual_events, expected_metrics) ======= jax.tree_map(test_case.assertAlmostEqual, actual_events, expected_metrics) >>>>>>> 1f8cec78b1f28f1955d70741792d7b6e7dd76226 class MetricsManagerTest(absltest.TestCase): def setUp(self): super().setUp() self.model_dir = self.create_tempdir().full_path def test_summary_dir(self): # All hosts have the summary dir. with mock.patch('jax.process_index', return_value=0): mm = trainer_lib.MetricsManager('eval', self.model_dir) self.assertEqual(mm.summary_dir, os.path.join(self.model_dir, 'eval')) mm.close() with mock.patch('jax.process_index', return_value=1): mm = trainer_lib.MetricsManager('eval', self.model_dir) self.assertEqual(mm.summary_dir, os.path.join(self.model_dir, 'eval')) mm.close() def test_summary_writer(self): # Only host 0 creates a non-empty summary writer. with mock.patch('jax.process_index', return_value=1): mm = trainer_lib.MetricsManager('eval', self.model_dir) self.assertFalse(gfile.exists(mm.summary_dir)) mm.close() with mock.patch('jax.process_index', return_value=0): mm = trainer_lib.MetricsManager('eval', self.model_dir) self.assertIsInstance(mm.summary_writer, metric_writers.MetricWriter) self.assertTrue(gfile.exists(mm.summary_dir)) mm.close() def test_write_scalar(self): gfile.makedirs(os.path.join(self.model_dir, 'eval')) # tag, value, step scalars = [('loss', 1.0, 1), ('accuracy', 100.0, 2)] # Only host 0 has actually writes summaries. with mock.patch('jax.process_index', return_value=1): mm = trainer_lib.MetricsManager('eval', self.model_dir) for s in scalars: mm.write_scalar(*s) self.assertEmpty(gfile.listdir(mm.summary_dir)) mm.close() with mock.patch('jax.process_index', return_value=0): mm = trainer_lib.MetricsManager('eval', self.model_dir) for s in scalars: mm.write_scalar(*s) mm.flush() summaries = gfile.listdir(mm.summary_dir) self.assertLen(summaries, 1) event_file = os.path.join(mm.summary_dir, summaries[0]) events = list(tf.compat.v1.train.summary_iterator(event_file)) # First event is boilerplate self.assertLen(events, 3) for event, (tag, value, step) in zip(events[1:], scalars): self.assertEqual(event.step, step) self.assertLen(event.summary.value, 1) self.assertEqual(event.summary.value[0].tag, tag) self.assertEqual(tf.make_ndarray(event.summary.value[0].tensor), value) mm.close() def test_write_metrics_summary(self): gfile.makedirs(os.path.join(self.model_dir, 'eval')) @flax.struct.dataclass class MockTextMetric(clu.metrics.Metric): def compute_value(self): return clu.values.Text('test metric') accumulated_metrics = {
'loss': metrics_lib.Sum(40.0),
9
2023-12-12 20:23:33+00:00
12k
SafeAILab/EAGLE
train/main.py
[ { "identifier": "Model", "path": "model/cnets.py", "snippet": "class Model(nn.Module):\r\n def __init__(self,config,load_emb=False,path=None):\r\n super().__init__()\r\n\r\n\r\n\r\n\r\n self.gradient_checkpointing = True\r\n self.padding_idx = config.pad_token_id\r\n self....
import argparse import json import os import torch import numpy as np import wandb from safetensors import safe_open from accelerate import Accelerator from accelerate.utils import set_seed from model.cnets import Model from model.configs import EConfig from typing import Any, Dict, List from torch import nn, optim from torch.utils.data import Dataset, DataLoader from tqdm import tqdm from transformers import get_linear_schedule_with_warmup, AutoConfig
9,190
batch_input_ids = torch.cat([self.paddingtensor2D(item['input_ids'], max_length) for item in features]) batch_hidden_states = torch.cat([self.paddingtensor(item['hidden_state_big'], max_length) for item in features]) batch_target = torch.cat([self.paddingtensor(item['target'], max_length) for item in features]) batch_loss_mask = torch.tensor( [item['loss_mask'] + [0] * (max_length - len(item['loss_mask'])) for item in features]) batch_attention_mask = torch.tensor( [item['attention_mask'] + [0] * (max_length - len(item['attention_mask'])) for item in features]) # batch_loss_mask = torch.ones_like(batch_loss_mask) # batch_attention_mask=torch.ones_like(batch_attention_mask) batch = { "input_ids": batch_input_ids, "hidden_states": batch_hidden_states, "target": batch_target, "attention_mask": batch_attention_mask, "loss_mask": batch_loss_mask, } return batch def top_accuracy(output, target, topk=(1,)): # output.shape (bs, num_classes), target.shape (bs, ) """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(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) res.append(correct_k) return res @torch.no_grad() def getkacc(model, data, head, max_length=5): hidden_states = data["hidden_states"] input_ids = data["input_ids"] # attention_mask=data["attention_mask"] loss_mask = data["loss_mask"] # sample_mask=data["sample_mask"] target = data["target"] total = [0 for _ in range(max_length)] correct = [0 for _ in range(max_length)] bs, sl = hidden_states.shape[0], hidden_states.shape[1] target_headout = head(target) hidden_states_headout = head(hidden_states) for i in range(bs): for j in range(sl): single_hidden_states = hidden_states[i, :j] single_input_ids = input_ids[i, :j] single_hidden_states = single_hidden_states[None, :, :] single_input_ids = single_input_ids[None, :] for k in range(max_length): if loss_mask[i, single_hidden_states.shape[1] - 1] == 0: break tmp_in_target_headout = hidden_states_headout[i, single_hidden_states.shape[1] - 1] tmp_out_target_headout = target_headout[i, single_hidden_states.shape[1] - 1] target_in_token = torch.argmax(tmp_in_target_headout) target_out_token = torch.argmax(tmp_out_target_headout) tmp_token = input_ids[i, single_hidden_states.shape[1] - 1] # tmp_sample_mask=sample_mask[i,single_hidden_states.shape[1]-1] if not (target_in_token == tmp_token): break out_hidden = model(single_hidden_states, input_ids=single_input_ids) last_hidden = out_hidden[:, -1] last_headout = head(last_hidden) token = torch.argmax(last_headout) total[k] += 1 if token == target_out_token: correct[k] += 1 else: for kk in range(k + 1, max_length): total[kk] += 1 break single_hidden_states = torch.cat((single_hidden_states, out_hidden[:, -1:]), dim=1) single_input_ids = torch.cat((single_input_ids, torch.tensor([[token]]).to(single_input_ids.device)), dim=1) acc = [correct[i] / total[i] for i in range(len(correct))] return acc if train_config["data_noise"]: if train_config["noise"] == "uniform": aug = AddUniformNoise(std=train_config["std"]) else: aug = AddGaussianNoise(mean=train_config["mean"], std=train_config["std"]) else: aug = None datapath = list_files(train_config["datapath"]) traindatapath = datapath[:int(len(datapath) * 0.95)] testdatapath = datapath[int(len(datapath) * 0.95):] # print('td',train_config["datapath"]) # print(datapath) # exit() traindataset = CustomDataset(traindatapath, transform=aug) testdataset = CustomDataset(testdatapath) train_loader = DataLoader(traindataset, batch_size=train_config["bs"], shuffle=True, collate_fn=DataCollatorWithPadding(), num_workers=train_config["num_workers"], pin_memory=True) test_loader = DataLoader(testdataset, batch_size=train_config["bs"], shuffle=False, collate_fn=DataCollatorWithPadding(), num_workers=train_config["num_workers"], pin_memory=True) # for batch_data in train_loader: # print(batch_data) if accelerator.is_main_process: if not os.path.exists(args.cpdir): os.makedirs(args.cpdir) config = EConfig.from_pretrained(train_config["config_path"])
parser = argparse.ArgumentParser(description='sp') parser.add_argument('--basepath', type=str, default='/home/lyh/weights/hf/vicuna_v13/7B/') parser.add_argument('--configpath', type=str, default="config.json") parser.add_argument('--lr', type=float, default=3e-5) parser.add_argument('--bs', type=int, default=4) parser.add_argument('--gradient-accumulation-steps', type=int, default=8) parser.add_argument('--tmpdir', type=str, default='0') parser.add_argument('--outdir', type=str, default='0') parser.add_argument('--cpdir', type=str, default='0') args = parser.parse_args() train_config = { "lr": args.lr, "bs": args.bs, "gradient_accumulation_steps": args.gradient_accumulation_steps, "datapath": f"{args.tmpdir}", "is_warmup": True, "num_epochs": 20, # Depending on your data and model size, the larger the model, the higher the sample efficiency. We recommend setting it between 20-40. "num_warmup_steps": 2000, "total_steps": 800000, "p_w": 0.1, "v_w": 1.0, "head_w": 0.1, "num_workers": 2, "embeding": True, "act": "No", "data_noise": True, "noise": "uniform", "mean": 0.0, "std": 0.2, "residual": "true,norm", "max_len": 2048, # During training, truncating the training sequences means that the larger the setting, the more training data is used, and the better the effect, but it also consumes more VRAM. "config_path": args.configpath, "b1": 0.9, "b2": 0.95, "grad_clip": 0.5, "save_freq": 5 } # from transformers import AutoModelForCausalLM, AutoTokenizer,AutoModelForSequenceClassification # os.environ["CUDA_VISIBLE_DEVICES"] = "0,1" torch.backends.cuda.matmul.allow_tf32 = True set_seed(0) accelerator = Accelerator(mixed_precision='bf16', gradient_accumulation_steps=train_config["gradient_accumulation_steps"]) # import accelerate if accelerator.is_main_process: wandb.init(project="ess", entity="yuhui-li", config=train_config) baseconfig = AutoConfig.from_pretrained(args.basepath) head = torch.nn.Linear(baseconfig.hidden_size, baseconfig.vocab_size, bias=False) try: with open(os.path.join(args.basepath, "model.safetensors.index.json"), "r") as f: index_json = json.loads(f.read()) head_path = index_json["weight_map"]["lm_head.weight"] with safe_open(os.path.join(args.basepath, head_path), framework="pt", device="cpu") as f: tensor_slice = f.get_slice("lm_head.weight") vocab_size, hidden_dim = tensor_slice.get_shape() tensor = tensor_slice[:, :hidden_dim].float() except: with open(os.path.join(args.basepath, "pytorch_model.bin.index.json"), "r") as f: index_json = json.loads(f.read()) head_path = index_json["weight_map"]["lm_head.weight"] weights = torch.load(os.path.join(args.basepath, head_path)) tensor = weights["lm_head.weight"].float() head.weight.data = tensor head.eval() for param in head.parameters(): param.requires_grad = False def list_files(path): datapath = [] for root, directories, files in os.walk(path): for file in files: file_path = os.path.join(root, file) datapath.append(file_path) return datapath class AddGaussianNoise: def __init__(self, mean=0.0, std=0.0): self.mean = mean self.std = std def __call__(self, data): tensor = data["hidden_state_big"] noise = torch.randn(tensor.size()) * self.std + self.mean noisy_tensor = tensor + noise data["hidden_state_big"] = noisy_tensor return data class AddUniformNoise: def __init__(self, std=0.0): self.std = std def __call__(self, data): tensor = data["hidden_state_big"] noise = (torch.rand_like(tensor) - 0.5) * self.std * 512 / tensor.shape[1] noisy_tensor = tensor + noise data["hidden_state_big"] = noisy_tensor return data class CustomDataset(Dataset): def __init__(self, datapath, transform=None): self.data = datapath self.transform = transform def __len__(self): return len(self.data) def __getitem__(self, index): # try: data = torch.load(self.data[index]) new_data = {} hidden_state = data['hidden_state'][:train_config["max_len"]][None, :] input_ids = data['input_ids'][:train_config["max_len"]][None, :] loss_mask = data["loss_mask"][:train_config["max_len"]][None, :] # except: # with open("error_path.txt", "w") as file: # file.write(self.data[index]) # print('error path',self.data[index]) length = hidden_state.shape[1] # length_q = data['query_ids'].shape[1] attention_mask = [1] * length loss_mask = loss_mask[0].tolist() loss_mask[-1] = 0 input_ids_target = input_ids[:, 1:] zeropadding = torch.tensor([[0]]) input_ids_target = torch.cat((input_ids_target, zeropadding), dim=1) target = hidden_state[:, 1:, :] zeropadding = torch.zeros(1, 1, target.shape[2]) target = torch.cat((target, zeropadding), dim=1) loss_mask[-1] = 0 new_data["attention_mask"] = attention_mask new_data["loss_mask"] = loss_mask new_data["target"] = target new_data["hidden_state_big"] = hidden_state new_data["input_ids"] = input_ids_target # sample = torch.cat((data['xs'],data['xb'])) # sample=torch.cat((self.data[index]['x'],self.data[index]['logits'])) # label = data['y'] if self.transform: new_data = self.transform(new_data) return new_data class DataCollatorWithPadding: def paddingtensor(self, intensors, N): B, n, S = intensors.shape # padding_tensor = torch.zeros(B, N - n, S,dtype=intensors.dtype) padding_tensor = torch.zeros(B, N - n, S) outtensors = torch.cat((intensors, padding_tensor), dim=1) return outtensors def paddingtensor2D(self, intensors, N): B, n = intensors.shape padding_tensor = torch.zeros(B, N - n, dtype=intensors.dtype) outtensors = torch.cat((intensors, padding_tensor), dim=1) return outtensors def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: max_length = max(item['hidden_state_big'].shape[1] for item in features) batch_input_ids = torch.cat([self.paddingtensor2D(item['input_ids'], max_length) for item in features]) batch_hidden_states = torch.cat([self.paddingtensor(item['hidden_state_big'], max_length) for item in features]) batch_target = torch.cat([self.paddingtensor(item['target'], max_length) for item in features]) batch_loss_mask = torch.tensor( [item['loss_mask'] + [0] * (max_length - len(item['loss_mask'])) for item in features]) batch_attention_mask = torch.tensor( [item['attention_mask'] + [0] * (max_length - len(item['attention_mask'])) for item in features]) # batch_loss_mask = torch.ones_like(batch_loss_mask) # batch_attention_mask=torch.ones_like(batch_attention_mask) batch = { "input_ids": batch_input_ids, "hidden_states": batch_hidden_states, "target": batch_target, "attention_mask": batch_attention_mask, "loss_mask": batch_loss_mask, } return batch def top_accuracy(output, target, topk=(1,)): # output.shape (bs, num_classes), target.shape (bs, ) """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(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) res.append(correct_k) return res @torch.no_grad() def getkacc(model, data, head, max_length=5): hidden_states = data["hidden_states"] input_ids = data["input_ids"] # attention_mask=data["attention_mask"] loss_mask = data["loss_mask"] # sample_mask=data["sample_mask"] target = data["target"] total = [0 for _ in range(max_length)] correct = [0 for _ in range(max_length)] bs, sl = hidden_states.shape[0], hidden_states.shape[1] target_headout = head(target) hidden_states_headout = head(hidden_states) for i in range(bs): for j in range(sl): single_hidden_states = hidden_states[i, :j] single_input_ids = input_ids[i, :j] single_hidden_states = single_hidden_states[None, :, :] single_input_ids = single_input_ids[None, :] for k in range(max_length): if loss_mask[i, single_hidden_states.shape[1] - 1] == 0: break tmp_in_target_headout = hidden_states_headout[i, single_hidden_states.shape[1] - 1] tmp_out_target_headout = target_headout[i, single_hidden_states.shape[1] - 1] target_in_token = torch.argmax(tmp_in_target_headout) target_out_token = torch.argmax(tmp_out_target_headout) tmp_token = input_ids[i, single_hidden_states.shape[1] - 1] # tmp_sample_mask=sample_mask[i,single_hidden_states.shape[1]-1] if not (target_in_token == tmp_token): break out_hidden = model(single_hidden_states, input_ids=single_input_ids) last_hidden = out_hidden[:, -1] last_headout = head(last_hidden) token = torch.argmax(last_headout) total[k] += 1 if token == target_out_token: correct[k] += 1 else: for kk in range(k + 1, max_length): total[kk] += 1 break single_hidden_states = torch.cat((single_hidden_states, out_hidden[:, -1:]), dim=1) single_input_ids = torch.cat((single_input_ids, torch.tensor([[token]]).to(single_input_ids.device)), dim=1) acc = [correct[i] / total[i] for i in range(len(correct))] return acc if train_config["data_noise"]: if train_config["noise"] == "uniform": aug = AddUniformNoise(std=train_config["std"]) else: aug = AddGaussianNoise(mean=train_config["mean"], std=train_config["std"]) else: aug = None datapath = list_files(train_config["datapath"]) traindatapath = datapath[:int(len(datapath) * 0.95)] testdatapath = datapath[int(len(datapath) * 0.95):] # print('td',train_config["datapath"]) # print(datapath) # exit() traindataset = CustomDataset(traindatapath, transform=aug) testdataset = CustomDataset(testdatapath) train_loader = DataLoader(traindataset, batch_size=train_config["bs"], shuffle=True, collate_fn=DataCollatorWithPadding(), num_workers=train_config["num_workers"], pin_memory=True) test_loader = DataLoader(testdataset, batch_size=train_config["bs"], shuffle=False, collate_fn=DataCollatorWithPadding(), num_workers=train_config["num_workers"], pin_memory=True) # for batch_data in train_loader: # print(batch_data) if accelerator.is_main_process: if not os.path.exists(args.cpdir): os.makedirs(args.cpdir) config = EConfig.from_pretrained(train_config["config_path"])
model = Model(config, load_emb=True, path=args.basepath)
0
2023-12-07 19:08:39+00:00
12k
zju3dv/EasyVolcap
easyvolcap/engine/registry.py
[ { "identifier": "deprecated_api_warning", "path": "easyvolcap/engine/misc.py", "snippet": "def deprecated_api_warning(name_dict, cls_name=None):\n \"\"\"A decorator to check if some arguments are deprecate and try to replace\n deprecate src_arg_name to dst_arg_name.\n Args:\n name_dict(d...
import inspect import warnings from functools import partial from typing import Any, Dict, Optional, Callable from .misc import deprecated_api_warning, is_seq_of from .config import Config, BASE_KEY, DELETE_KEY, APPEND_KEY, DEPRECATION_KEY from easyvolcap.utils.base_utils import dotdict from easyvolcap.utils.console_utils import * # This is the actual entry point
8,407
# Copyright (c) OpenMMLab. All rights reserved. def get_func_args(func: Callable): signature = inspect.signature(func) return { k: v for k, v in signature.parameters.items() # if v.default is not inspect.Parameter.empty } def call_from_cfg(func: Callable, cfg: dict, **kwargs): cfg = dotdict(cfg) cfg.update(kwargs) func_args = get_func_args(func) call_args = dotdict() for k, v in func_args.items(): if v.kind == inspect.Parameter.VAR_KEYWORD: call_args = cfg break if not call_args: # empty for k, v in cfg.items(): if k not in func_args: # Maybe be quite about it # log(f'Unused arg:', line(k), '=', line(v), 'for', line(func)) # FIXME: Easy for undebuggable bugs to slip through (typo in config keys)
# Copyright (c) OpenMMLab. All rights reserved. def get_func_args(func: Callable): signature = inspect.signature(func) return { k: v for k, v in signature.parameters.items() # if v.default is not inspect.Parameter.empty } def call_from_cfg(func: Callable, cfg: dict, **kwargs): cfg = dotdict(cfg) cfg.update(kwargs) func_args = get_func_args(func) call_args = dotdict() for k, v in func_args.items(): if v.kind == inspect.Parameter.VAR_KEYWORD: call_args = cfg break if not call_args: # empty for k, v in cfg.items(): if k not in func_args: # Maybe be quite about it # log(f'Unused arg:', line(k), '=', line(v), 'for', line(func)) # FIXME: Easy for undebuggable bugs to slip through (typo in config keys)
if k not in [BASE_KEY, DELETE_KEY, APPEND_KEY, DEPRECATION_KEY]:
4
2023-12-07 08:53:42+00:00
12k
alibaba/animate-anything
models/unet_3d_condition_mask.py
[ { "identifier": "CrossAttnDownBlock3D", "path": "models/unet_3d_blocks.py", "snippet": "class CrossAttnDownBlock3D(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n temb_channels: int,\n dropout: float = 0.0,\n num_layers: int = 1...
from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.utils import BaseOutput, logging from diffusers.models.embeddings import TimestepEmbedding, Timesteps from diffusers.models.modeling_utils import ModelMixin from diffusers.models.transformer_temporal import TransformerTemporalModel from einops import rearrange, repeat from .unet_3d_blocks import ( CrossAttnDownBlock3D, CrossAttnUpBlock3D, DownBlock3D, UNetMidBlock3DCrossAttn, UpBlock3D, get_down_block, get_up_block, transformer_g_c ) import torch import torch.nn as nn import torch.utils.checkpoint
8,980
raise ValueError(f"size {size} has to be smaller or equal to {dim}.") # Recursively walk through all the children. # Any children which exposes the set_attention_slice method # gets the message def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]): if hasattr(module, "set_attention_slice"): module.set_attention_slice(slice_size.pop()) for child in module.children(): fn_recursive_set_attention_slice(child, slice_size) reversed_slice_size = list(reversed(slice_size)) for module in self.children(): fn_recursive_set_attention_slice(module, reversed_slice_size) def _set_gradient_checkpointing(self, value=False): self.gradient_checkpointing = value self.mid_block.gradient_checkpointing = value for module in self.down_blocks + self.up_blocks: if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)): module.gradient_checkpointing = value def forward( self, sample: torch.FloatTensor, timestep: Union[torch.Tensor, float, int], encoder_hidden_states: torch.Tensor, condition_latent: torch.Tensor, mask: torch.Tensor, class_labels: Optional[torch.Tensor] = None, timestep_cond: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, cross_attention_kwargs: Optional[Dict[str, Any]] = None, down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None, mid_block_additional_residual: Optional[torch.Tensor] = None, motion = None, return_dict: bool = True, ) -> Union[UNet3DConditionOutput, Tuple]: r""" Args: sample (`torch.FloatTensor`): (batch, num_frames, channel, height, width) noisy inputs tensor timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`models.unet_2d_condition.UNet3DConditionOutput`] instead of a plain tuple. cross_attention_kwargs (`dict`, *optional*): A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under `self.processor` in [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py). Returns: [`~models.unet_2d_condition.UNet3DConditionOutput`] or `tuple`: [`~models.unet_2d_condition.UNet3DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is the sample tensor. """ # By default samples have to be AT least a multiple of the overall upsampling factor. # The overall upsampling factor is equal to 2 ** (# num of upsampling layears). # However, the upsampling interpolation output size can be forced to fit any upsampling size # on the fly if necessary. default_overall_up_factor = 2**self.num_upsamplers sample = torch.cat([condition_latent, sample], dim=2) # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor` forward_upsample_size = False upsample_size = None if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]): logger.info("Forward upsample size to force interpolation output size.") forward_upsample_size = True # prepare attention_mask if attention_mask is not None: attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0 attention_mask = attention_mask.unsqueeze(1) # 1. time timesteps = timestep if not torch.is_tensor(timesteps): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) is_mps = sample.device.type == "mps" if isinstance(timestep, float): dtype = torch.float32 if is_mps else torch.float64 else: dtype = torch.int32 if is_mps else torch.int64 timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device) elif len(timesteps.shape) == 0: timesteps = timesteps[None].to(sample.device) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML num_frames = sample.shape[2] timesteps = timesteps.expand(sample.shape[0]) t_emb = self.time_proj(timesteps) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might actually be running in fp16. so we need to cast here. # there might be better ways to encapsulate this. t_emb = t_emb.to(dtype=self.dtype) if self.motion_strength and motion is not None: timestep_cond = self.motion_proj(motion).to(dtype=self.dtype) emb = self.time_embedding(t_emb, timestep_cond) #emb += self.motion_embedding(m_emb) else: emb = self.time_embedding(t_emb, timestep_cond) emb = emb.repeat_interleave(repeats=num_frames, dim=0) encoder_hidden_states = encoder_hidden_states.repeat_interleave(repeats=num_frames, dim=0) # 2. pre-process if self.motion_mask and mask is not None: mask = repeat(mask , 'b 1 1 h w -> (t b) 1 f h w', t=sample.shape[0]//mask.shape[0], f=sample.shape[2]) sample = torch.cat([mask, sample], dim=1) sample = sample.permute(0, 2, 1, 3, 4).reshape((sample.shape[0] * num_frames, -1) + sample.shape[3:]) sample = self.conv_in2(sample) else: sample = sample.permute(0, 2, 1, 3, 4).reshape((sample.shape[0] * num_frames, -1) + sample.shape[3:]) sample = self.conv_in(sample) if num_frames > 1: if self.gradient_checkpointing:
# Copyright 2023 Alibaba DAMO-VILAB and The HuggingFace Team. All rights reserved. # Copyright 2023 The ModelScope Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): """ Args: sample (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`): Hidden states conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: torch.FloatTensor class UNet3DConditionModel(ModelMixin, ConfigMixin): r""" UNet3DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep and returns sample shaped output. This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library implements for all the models (such as downloading or saving, etc.) Parameters: sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`): Height and width of input/output sample. in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample. out_channels (`int`, *optional*, defaults to 4): The number of channels in the output. down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`): The tuple of downsample blocks to use. up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D",)`): The tuple of upsample blocks to use. block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): The tuple of output channels for each block. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution. mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block. act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization. If `None`, it will skip the normalization and activation layers in post-processing norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization. cross_attention_dim (`int`, *optional*, defaults to 1280): The dimension of the cross attention features. attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads. """ _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, down_block_types: Tuple[str] = ( "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D", ), up_block_types: Tuple[str] = ("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D"), block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: Optional[int] = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1024, attention_head_dim: Union[int, Tuple[int]] = 64, motion_mask = False, motion_strength = False, ): super().__init__() self.motion_mask = motion_mask self.motion_strength = motion_strength print(f"motion mask {self.motion_mask}, motion_strength {self.motion_strength}") self.sample_size = sample_size self.gradient_checkpointing = False # Check inputs if len(down_block_types) != len(up_block_types): raise ValueError( f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}." ) if len(block_out_channels) != len(down_block_types): raise ValueError( f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}." ) if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types): raise ValueError( f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}." ) # input conv_in_kernel = 3 conv_out_kernel = 3 conv_in_padding = (conv_in_kernel - 1) // 2 self.conv_in = nn.Conv2d( in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding ) self.conv_in2 = nn.Conv2d( 5, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding ) # time time_embed_dim = block_out_channels[0] * 4 self.time_proj = Timesteps(block_out_channels[0], True, 0) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding( timestep_input_dim, time_embed_dim, act_fn=act_fn, cond_proj_dim=block_out_channels[0], ) self.motion_proj = Timesteps(block_out_channels[0], True, 0) self.motion_embedding = nn.Sequential( nn.Linear(timestep_input_dim, time_embed_dim), nn.SiLU(), nn.Linear(time_embed_dim, time_embed_dim)) nn.init.zeros_(self.motion_embedding[-1].weight) nn.init.zeros_(self.motion_embedding[-1].bias) self.transformer_in = TransformerTemporalModel( num_attention_heads=8, attention_head_dim=attention_head_dim, in_channels=block_out_channels[0], num_layers=1, ) # class embedding self.down_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block, in_channels=input_channel, out_channels=output_channel, temb_channels=time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=False, ) self.down_blocks.append(down_block) # mid self.mid_block = UNetMidBlock3DCrossAttn( in_channels=block_out_channels[-1], temb_channels=time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[-1], resnet_groups=norm_num_groups, dual_cross_attention=False, ) # count how many layers upsample the images self.num_upsamplers = 0 # up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_attention_head_dim = list(reversed(attention_head_dim)) output_channel = reversed_block_out_channels[0] for i, up_block_type in enumerate(up_block_types): is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False up_block = get_up_block( up_block_type, num_layers=layers_per_block + 1, in_channels=input_channel, out_channels=output_channel, prev_output_channel=prev_output_channel, temb_channels=time_embed_dim, add_upsample=add_upsample, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=reversed_attention_head_dim[i], dual_cross_attention=False, ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out if norm_num_groups is not None: self.conv_norm_out = nn.GroupNorm( num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps ) self.conv_act = nn.SiLU() else: self.conv_norm_out = None self.conv_act = None conv_out_padding = (conv_out_kernel - 1) // 2 self.conv_out = nn.Conv2d( block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding ) def set_attention_slice(self, slice_size): r""" Enable sliced attention computation. When this option is enabled, the attention module will split the input tensor in slices, to compute attention in several steps. This is useful to save some memory in exchange for a small speed decrease. Args: slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim` must be a multiple of `slice_size`. """ sliceable_head_dims = [] def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module): if hasattr(module, "set_attention_slice"): sliceable_head_dims.append(module.sliceable_head_dim) for child in module.children(): fn_recursive_retrieve_slicable_dims(child) # retrieve number of attention layers for module in self.children(): fn_recursive_retrieve_slicable_dims(module) num_slicable_layers = len(sliceable_head_dims) if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory slice_size = [dim // 2 for dim in sliceable_head_dims] elif slice_size == "max": # make smallest slice possible slice_size = num_slicable_layers * [1] slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size if len(slice_size) != len(sliceable_head_dims): raise ValueError( f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different" f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}." ) for i in range(len(slice_size)): size = slice_size[i] dim = sliceable_head_dims[i] if size is not None and size > dim: raise ValueError(f"size {size} has to be smaller or equal to {dim}.") # Recursively walk through all the children. # Any children which exposes the set_attention_slice method # gets the message def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]): if hasattr(module, "set_attention_slice"): module.set_attention_slice(slice_size.pop()) for child in module.children(): fn_recursive_set_attention_slice(child, slice_size) reversed_slice_size = list(reversed(slice_size)) for module in self.children(): fn_recursive_set_attention_slice(module, reversed_slice_size) def _set_gradient_checkpointing(self, value=False): self.gradient_checkpointing = value self.mid_block.gradient_checkpointing = value for module in self.down_blocks + self.up_blocks: if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)): module.gradient_checkpointing = value def forward( self, sample: torch.FloatTensor, timestep: Union[torch.Tensor, float, int], encoder_hidden_states: torch.Tensor, condition_latent: torch.Tensor, mask: torch.Tensor, class_labels: Optional[torch.Tensor] = None, timestep_cond: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, cross_attention_kwargs: Optional[Dict[str, Any]] = None, down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None, mid_block_additional_residual: Optional[torch.Tensor] = None, motion = None, return_dict: bool = True, ) -> Union[UNet3DConditionOutput, Tuple]: r""" Args: sample (`torch.FloatTensor`): (batch, num_frames, channel, height, width) noisy inputs tensor timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`models.unet_2d_condition.UNet3DConditionOutput`] instead of a plain tuple. cross_attention_kwargs (`dict`, *optional*): A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under `self.processor` in [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py). Returns: [`~models.unet_2d_condition.UNet3DConditionOutput`] or `tuple`: [`~models.unet_2d_condition.UNet3DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is the sample tensor. """ # By default samples have to be AT least a multiple of the overall upsampling factor. # The overall upsampling factor is equal to 2 ** (# num of upsampling layears). # However, the upsampling interpolation output size can be forced to fit any upsampling size # on the fly if necessary. default_overall_up_factor = 2**self.num_upsamplers sample = torch.cat([condition_latent, sample], dim=2) # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor` forward_upsample_size = False upsample_size = None if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]): logger.info("Forward upsample size to force interpolation output size.") forward_upsample_size = True # prepare attention_mask if attention_mask is not None: attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0 attention_mask = attention_mask.unsqueeze(1) # 1. time timesteps = timestep if not torch.is_tensor(timesteps): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) is_mps = sample.device.type == "mps" if isinstance(timestep, float): dtype = torch.float32 if is_mps else torch.float64 else: dtype = torch.int32 if is_mps else torch.int64 timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device) elif len(timesteps.shape) == 0: timesteps = timesteps[None].to(sample.device) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML num_frames = sample.shape[2] timesteps = timesteps.expand(sample.shape[0]) t_emb = self.time_proj(timesteps) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might actually be running in fp16. so we need to cast here. # there might be better ways to encapsulate this. t_emb = t_emb.to(dtype=self.dtype) if self.motion_strength and motion is not None: timestep_cond = self.motion_proj(motion).to(dtype=self.dtype) emb = self.time_embedding(t_emb, timestep_cond) #emb += self.motion_embedding(m_emb) else: emb = self.time_embedding(t_emb, timestep_cond) emb = emb.repeat_interleave(repeats=num_frames, dim=0) encoder_hidden_states = encoder_hidden_states.repeat_interleave(repeats=num_frames, dim=0) # 2. pre-process if self.motion_mask and mask is not None: mask = repeat(mask , 'b 1 1 h w -> (t b) 1 f h w', t=sample.shape[0]//mask.shape[0], f=sample.shape[2]) sample = torch.cat([mask, sample], dim=1) sample = sample.permute(0, 2, 1, 3, 4).reshape((sample.shape[0] * num_frames, -1) + sample.shape[3:]) sample = self.conv_in2(sample) else: sample = sample.permute(0, 2, 1, 3, 4).reshape((sample.shape[0] * num_frames, -1) + sample.shape[3:]) sample = self.conv_in(sample) if num_frames > 1: if self.gradient_checkpointing:
sample = transformer_g_c(self.transformer_in, sample, num_frames)
7
2023-12-07 08:26:29+00:00
12k
octo-models/octo
scripts/finetune.py
[ { "identifier": "make_single_dataset", "path": "octo/data/dataset.py", "snippet": "def make_single_dataset(\n dataset_kwargs: dict,\n *,\n train: bool,\n traj_transform_kwargs: dict = {},\n frame_transform_kwargs: dict = {},\n) -> dl.DLataset:\n \"\"\"Creates a single dataset from kwar...
import datetime import imp import os import flax import jax import optax import tensorflow as tf import tqdm import wandb from functools import partial from absl import app, flags, logging from flax.traverse_util import flatten_dict from jax.sharding import Mesh, NamedSharding, PartitionSpec from ml_collections import config_flags, ConfigDict from octo.data.dataset import make_single_dataset from octo.model.octo_model import OctoModel from octo.utils.jax_utils import initialize_compilation_cache from octo.utils.spec import ModuleSpec from octo.utils.train_callbacks import ( RolloutVisualizationCallback, SaveCallback, ValidationCallback, VisualizationCallback, ) from octo.utils.train_utils import ( check_config_diff, create_optimizer, format_name_with_config, merge_params, process_text, Timer, TrainState, ) from jax_smi import initialise_tracking # type: ignore
10,530
), f"Batch size ({FLAGS.config.batch_size}) must be divisible by the number of devices ({len(devices)})" assert ( FLAGS.config.viz_kwargs.eval_batch_size % len(devices) == 0 ), f"Eval batch size ({FLAGS.config.viz_kwargs.eval_batch_size}) must be divisible by the number of devices ({len(devices)})" # create a 1D mesh with a single axis named "batch" mesh = Mesh(jax.devices(), axis_names="batch") # Our batches will be data-parallel sharded -- each device will get a slice of the batch dp_sharding = NamedSharding(mesh, PartitionSpec("batch")) # Our model will be replicated across devices (we are only doing data parallelism, not model parallelism) replicated_sharding = NamedSharding(mesh, PartitionSpec()) # prevent tensorflow from using GPU memory since it's only used for data loading tf.config.set_visible_devices([], "GPU") ######### # # Setup WandB # ######### name = format_name_with_config( FLAGS.name, FLAGS.config.to_dict(), ) wandb_id = "{name}_{time}".format( name=name, time=datetime.datetime.now().strftime("%Y%m%d_%H%M%S"), ) wandb.init( config=FLAGS.config.to_dict(), id=wandb_id, name=name, mode="disabled" if FLAGS.debug else None, **FLAGS.config.wandb, ) ######### # # Load Pretrained model + optionally modify config # ######### pretrained_model = OctoModel.load_pretrained( FLAGS.config.pretrained_path, step=FLAGS.config.pretrained_step, ) flat_config = flax.traverse_util.flatten_dict( pretrained_model.config, keep_empty_nodes=True ) for d_key in flax.traverse_util.flatten_dict( FLAGS.config.get("config_delete_keys", ConfigDict()).to_dict() ): for c_key in list(flat_config.keys()): if ".".join(c_key).startswith(".".join(d_key)): del flat_config[c_key] config = ConfigDict(flax.traverse_util.unflatten_dict(flat_config)) config.update(FLAGS.config.get("update_config", ConfigDict())) config = config.to_dict() check_config_diff(config, pretrained_model.config) ######### # # Setup Data Loader # ######### # create text processor if config["text_processor"] is None: text_processor = None else: text_processor = ModuleSpec.instantiate(config["text_processor"])() def process_batch(batch): batch = process_text(batch, text_processor) del batch["dataset_name"] return batch # load standardize_fn from `path/to/file.py:fn_name` format if ( standardize_fn := FLAGS.config["dataset_kwargs"].get("standardize_fn", None) ) is not None: path, name = standardize_fn.split(":") # imp is deprecated, but it's also what ml_collections uses standardize_fn = getattr(imp.load_source("standardize_fn", path), name) del FLAGS.config["dataset_kwargs"]["standardize_fn"] FLAGS.config["dataset_kwargs"]["standardize_fn"] = standardize_fn dataset = make_single_dataset( FLAGS.config.dataset_kwargs, traj_transform_kwargs=FLAGS.config.traj_transform_kwargs, frame_transform_kwargs=FLAGS.config.frame_transform_kwargs, train=True, ) train_data_iter = ( dataset.repeat() .unbatch() .shuffle(FLAGS.config.shuffle_buffer_size) .batch(FLAGS.config.batch_size) .iterator() ) train_data_iter = map(process_batch, train_data_iter) example_batch = next(train_data_iter) ######### # # Load Pretrained Model # ######### rng = jax.random.PRNGKey(FLAGS.config.seed) rng, init_rng = jax.random.split(rng) model = OctoModel.from_config( config, example_batch, text_processor, rng=init_rng, dataset_statistics=dataset.dataset_statistics, )
try: initialise_tracking() except ImportError: pass FLAGS = flags.FLAGS flags.DEFINE_string("name", "experiment", "Experiment name.") flags.DEFINE_bool("debug", False, "Debug config (no wandb logging)") default_config_file = os.path.join( os.path.dirname(__file__), "configs/finetune_config.py" ) config_flags.DEFINE_config_file( "config", default_config_file, "File path to the training hyperparameter configuration.", lock_config=False, ) def main(_): initialize_compilation_cache() devices = jax.devices() logging.info( f""" Octo Finetuning Script ====================== Pretrained model: {FLAGS.config.pretrained_path} Finetuning Dataset: {FLAGS.config.dataset_kwargs.name} Data dir: {FLAGS.config.dataset_kwargs.data_dir} Task Modality: {FLAGS.config.modality} Finetuning Mode: {FLAGS.config.finetuning_mode} # Devices: {jax.device_count()} Batch size: {FLAGS.config.batch_size} ({FLAGS.config.batch_size // len(devices) } per device) # Steps: {FLAGS.config.num_steps} """ ) ######### # # Setup Jax Data Parallelism # ######### assert ( FLAGS.config.batch_size % len(devices) == 0 ), f"Batch size ({FLAGS.config.batch_size}) must be divisible by the number of devices ({len(devices)})" assert ( FLAGS.config.viz_kwargs.eval_batch_size % len(devices) == 0 ), f"Eval batch size ({FLAGS.config.viz_kwargs.eval_batch_size}) must be divisible by the number of devices ({len(devices)})" # create a 1D mesh with a single axis named "batch" mesh = Mesh(jax.devices(), axis_names="batch") # Our batches will be data-parallel sharded -- each device will get a slice of the batch dp_sharding = NamedSharding(mesh, PartitionSpec("batch")) # Our model will be replicated across devices (we are only doing data parallelism, not model parallelism) replicated_sharding = NamedSharding(mesh, PartitionSpec()) # prevent tensorflow from using GPU memory since it's only used for data loading tf.config.set_visible_devices([], "GPU") ######### # # Setup WandB # ######### name = format_name_with_config( FLAGS.name, FLAGS.config.to_dict(), ) wandb_id = "{name}_{time}".format( name=name, time=datetime.datetime.now().strftime("%Y%m%d_%H%M%S"), ) wandb.init( config=FLAGS.config.to_dict(), id=wandb_id, name=name, mode="disabled" if FLAGS.debug else None, **FLAGS.config.wandb, ) ######### # # Load Pretrained model + optionally modify config # ######### pretrained_model = OctoModel.load_pretrained( FLAGS.config.pretrained_path, step=FLAGS.config.pretrained_step, ) flat_config = flax.traverse_util.flatten_dict( pretrained_model.config, keep_empty_nodes=True ) for d_key in flax.traverse_util.flatten_dict( FLAGS.config.get("config_delete_keys", ConfigDict()).to_dict() ): for c_key in list(flat_config.keys()): if ".".join(c_key).startswith(".".join(d_key)): del flat_config[c_key] config = ConfigDict(flax.traverse_util.unflatten_dict(flat_config)) config.update(FLAGS.config.get("update_config", ConfigDict())) config = config.to_dict() check_config_diff(config, pretrained_model.config) ######### # # Setup Data Loader # ######### # create text processor if config["text_processor"] is None: text_processor = None else: text_processor = ModuleSpec.instantiate(config["text_processor"])() def process_batch(batch): batch = process_text(batch, text_processor) del batch["dataset_name"] return batch # load standardize_fn from `path/to/file.py:fn_name` format if ( standardize_fn := FLAGS.config["dataset_kwargs"].get("standardize_fn", None) ) is not None: path, name = standardize_fn.split(":") # imp is deprecated, but it's also what ml_collections uses standardize_fn = getattr(imp.load_source("standardize_fn", path), name) del FLAGS.config["dataset_kwargs"]["standardize_fn"] FLAGS.config["dataset_kwargs"]["standardize_fn"] = standardize_fn dataset = make_single_dataset( FLAGS.config.dataset_kwargs, traj_transform_kwargs=FLAGS.config.traj_transform_kwargs, frame_transform_kwargs=FLAGS.config.frame_transform_kwargs, train=True, ) train_data_iter = ( dataset.repeat() .unbatch() .shuffle(FLAGS.config.shuffle_buffer_size) .batch(FLAGS.config.batch_size) .iterator() ) train_data_iter = map(process_batch, train_data_iter) example_batch = next(train_data_iter) ######### # # Load Pretrained Model # ######### rng = jax.random.PRNGKey(FLAGS.config.seed) rng, init_rng = jax.random.split(rng) model = OctoModel.from_config( config, example_batch, text_processor, rng=init_rng, dataset_statistics=dataset.dataset_statistics, )
merged_params = merge_params(model.params, pretrained_model.params)
11
2023-12-13 09:58:56+00:00
12k
LinShan-Bin/OccNeRF
networks/occupancy_decoder.py
[ { "identifier": "geom", "path": "utils/geom.py", "snippet": "def eye_4x4(B, device='cuda'):\ndef safe_inverse(a): #parallel version\ndef safe_inverse_single(a):\ndef apply_4x4(RT, xyz):\ndef get_camM_T_camXs(origin_T_camXs, ind=0):\ndef split_rt_single(rt):\ndef split_rt(rt):\ndef merge_rt(r, t):\ndef x...
import pdb import time import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from torch_efficient_distloss import eff_distloss, eff_distloss_native from utils import geom from utils import vox from utils import basic from utils import render from ._3DCNN import S3DCNN
7,266
group_num = xyz.shape[1] // group_size xyz_sem = xyz[:, :group_size * group_num].reshape(xyz.shape[0], group_num, group_size, 3).mean(dim=2) else: xyz_sem = None if avail_mask is not None: if self.opt.contracted_coord: ind_norm = self.norm_func(xyz) avail_mask = self.effective_points_mask(ind_norm) ind_norm = ind_norm[avail_mask] if xyz_sem is not None: avail_mask_sem = avail_mask[:, :group_size * group_num].reshape(avail_mask.shape[0], group_num, group_size).any(dim=-1) ind_norm_sem = self.norm_func(xyz_sem[avail_mask_sem]) else: xyz_masked = xyz[avail_mask] ind_norm = self.norm_func(xyz_masked) if xyz_sem is not None: avail_mask_sem = avail_mask[:, :group_size * group_num].reshape(avail_mask.shape[0], group_num, group_size).any(dim=-1) ind_norm_sem = self.norm_func(xyz_sem[avail_mask_sem]) else: ind_norm = self.norm_func(xyz) if xyz_sem is not None: ind_norm_sem = self.norm_func(xyz_sem) avail_mask_sem = None ind_norm = ind_norm.flip((-1,)) # value range: [-1, 1] shape = ind_norm.shape[:-1] ind_norm = ind_norm.reshape(1, 1, 1, -1, 3) if xyz_sem is None: grid = grids[0] # BCXYZ # torch.Size([1, C, 256, 256, 16]) ret_lst = F.grid_sample(grid, ind_norm, mode='bilinear', align_corners=align_corners).reshape(grid.shape[1], -1).T.reshape(*shape, grid.shape[1]) if self.use_semantic: semantic, feats = ret_lst[..., :self.semantic_classes], ret_lst[..., -1] return feats, avail_mask, semantic else: return ret_lst.squeeze(), avail_mask else: ind_norm_sem = ind_norm_sem.flip((-1,)) shape_sem = ind_norm_sem.shape[:-1] ind_norm_sem = ind_norm_sem.reshape(1, 1, 1, -1, 3) grid_sem = grids[0][:, :self.semantic_classes] # BCXYZ # torch.Size([1, semantic_classes, H, W, Z]) grid_geo = grids[0][:, -1:] # BCXYZ # torch.Size([1, 1, H, W, Z]) ret_sem = F.grid_sample(grid_sem, ind_norm_sem, mode='bilinear', align_corners=align_corners).reshape(grid_sem.shape[1], -1).T.reshape(*shape_sem, grid_sem.shape[1]) ret_geo = F.grid_sample(grid_geo, ind_norm, mode='bilinear', align_corners=align_corners).reshape(grid_geo.shape[1], -1).T.reshape(*shape, grid_geo.shape[1]) return ret_geo.squeeze(), avail_mask, ret_sem, avail_mask_sem, group_num, group_size def sample_ray(self, rays_o, rays_d, is_train): '''Sample query points on rays''' Zval = self.Zval.to(rays_o) if is_train: Zval = Zval.repeat(rays_d.shape[-2], 1) Zval += (torch.rand_like(Zval[:, [0]]) * 0.2 - 0.1) * self.stepsize_log * self.voxel_size Zval = Zval.clamp(min=0.0) Zval = Zval + self.near rays_pts = rays_o[..., None, :] + rays_d[..., None, :] * Zval[..., None] rays_pts_depth = (rays_o[..., None, :] - rays_pts).norm(dim=-1) if self.opt.contracted_coord: # contracted coordiante has infinite perception range mask_outbbox = torch.zeros_like(rays_pts[..., 0]).bool() else: mask_outbbox = ((self.xyz_min > rays_pts) | (rays_pts > self.xyz_max)).any(dim=-1) return rays_pts, mask_outbbox, Zval, rays_pts_depth def effective_points_mask(self, points): '''Mask out points that are too close to each other in the contracted coordinate''' dist = torch.diff(points, dim=-2, prepend=torch.zeros_like(points[..., :1, :])).abs() xyz_thresh = 0.4 / torch.tensor([self.X, self.Y, self.Z]).to(points) mask = (dist > xyz_thresh).bool().any(dim=-1) return mask def activate_density(self, density, dists): return 1 - torch.exp(-F.relu(density) * dists) def get_density(self, rays_o, rays_d, Voxel_feat, is_train, inputs): dtype = torch.float16 if self.opt.use_fp16 else torch.float32 device = rays_o.device rays_o, rays_d, Voxel_feat = rays_o.to(dtype), rays_d.to(dtype), Voxel_feat.to(dtype) reg_loss = {} eps_time = time.time() with torch.no_grad(): rays_o_i = rays_o[0, ...].flatten(0, 2) # HXWX3 rays_d_i = rays_d[0, ...].flatten(0, 2) # HXWX3 rays_pts, mask_outbbox, z_vals, rays_pts_depth = self.sample_ray(rays_o_i, rays_d_i, is_train=is_train) dists = rays_pts_depth[..., 1:] - rays_pts_depth[..., :-1] # [num pixels, num points - 1] dists = torch.cat([dists, 1e4 * torch.ones_like(dists[..., :1])], dim=-1) # [num pixels, num points] sample_ret = self.grid_sampler(rays_pts, Voxel_feat, avail_mask=~mask_outbbox) if self.use_semantic: if self.opt.semantic_sample_ratio < 1.0: geo_feats, mask, semantic, mask_sem, group_num, group_size = sample_ret else: geo_feats, mask, semantic = sample_ret else: geo_feats, mask = sample_ret if self.opt.render_type == 'prob': weights = torch.zeros_like(rays_pts[..., 0]) weights[:, -1] = 1 geo_feats = torch.sigmoid(geo_feats) if self.opt.last_free: geo_feats = 1.0 - geo_feats # the last channel is the probability of being free weights[mask] = geo_feats # accumulate weights = weights.cumsum(dim=1).clamp(max=1) alphainv_fin = weights[..., -1] weights = weights.diff(dim=1, prepend=torch.zeros((rays_pts.shape[:1])).unsqueeze(1).to(device=device, dtype=dtype)) depth = (weights * z_vals).sum(-1) rgb_marched = 0 elif self.opt.render_type == 'density': alpha = torch.zeros_like(rays_pts[..., 0]) # [num pixels, num points] alpha[mask] = self.activate_density(geo_feats, dists[mask])
# Copyright Niantic 2019. Patent Pending. All rights reserved. # # This software is licensed under the terms of the Monodepth2 licence # which allows for non-commercial use only, the full terms of which are made # available in the LICENSE file. from __future__ import absolute_import, division, print_function class VolumeDecoder(nn.Module): def __init__(self, opt): super(VolumeDecoder, self).__init__() self.opt = opt self.use_semantic = self.opt.use_semantic self.semantic_classes = self.opt.semantic_classes self.batch = self.opt.batch_size // self.opt.cam_N self.near = self.opt.min_depth self.far = self.opt.max_depth self.register_buffer('xyz_min', torch.from_numpy( np.array([self.opt.real_size[0], self.opt.real_size[2], self.opt.real_size[4]]))) self.register_buffer('xyz_max', torch.from_numpy( np.array([self.opt.real_size[1], self.opt.real_size[3], self.opt.real_size[5]]))) self.ZMAX = self.opt.real_size[1] self.Z = self.opt.voxels_size[0] self.Y = self.opt.voxels_size[1] self.X = self.opt.voxels_size[2] self.Z_final = self.Z self.Y_final = self.Y self.X_final = self.X self.stepsize = self.opt.stepsize # voxel self.num_voxels = self.Z_final * self.Y_final * self.X_final self.stepsize_log = self.stepsize self.interval = self.stepsize if self.opt.contracted_coord: # Sampling strategy for contracted coordinate contracted_rate = self.opt.contracted_ratio num_id_voxels = int(self.num_voxels * (contracted_rate)**3) self.voxel_size = ((self.xyz_max - self.xyz_min).prod() / num_id_voxels).pow(1 / 3) diagonal = (self.xyz_max - self.xyz_min).pow(2).sum().pow(1 / 2) self.N_samples = int(diagonal / 2 / self.stepsize / self.voxel_size / contracted_rate) if self.opt.infinite_range: # depth_roi = [-self.far] * 3 + [self.far] * 3 zval_roi = [-diagonal] * 3 + [diagonal] * 3 fc = 1 - 0.5 / self.X # avoid NaN zs_contracted = torch.linspace(0.0, fc, steps=self.N_samples) zs_world = vox.contracted2world( zs_contracted[None, :, None].repeat(1, 1, 3), # pc_range_roi=depth_roi, pc_range_roi=zval_roi, ratio=self.opt.contracted_ratio)[:, :, 0] else: zs_world = torch.linspace(0.0, self.N_samples - 1, steps=self.N_samples)[None] * self.stepsize * self.voxel_size self.register_buffer('Zval', zs_world) pc_range_roi = self.xyz_min.tolist() + self.xyz_max.tolist() self.norm_func = lambda xyz: vox.world2contracted(xyz, pc_range_roi=pc_range_roi, ratio=self.opt.contracted_ratio) else: self.N_samples = int(np.linalg.norm(np.array([self.Z_final // 2, self.Y_final // 2, self.X_final // 2]) + 1) / self.stepsize) + 1 self.voxel_size = ((self.xyz_max - self.xyz_min).prod() / self.num_voxels).pow(1 / 3) zs_world = torch.linspace(0.0, self.N_samples - 1, steps=self.N_samples)[None] * self.stepsize * self.voxel_size self.register_buffer('Zval', zs_world) self.norm_func = lambda xyz: (xyz - self.xyz_min.to(xyz)) / (self.xyz_max.to(xyz) - self.xyz_min.to(xyz)) * 2.0 - 1.0 length_pose_encoding = 3 if self.opt.position == 'embedding': input_channel = self.opt.input_channel self.pos_embedding = torch.nn.Parameter(torch.ones( [1, input_channel, self.opt.voxels_size[1], self.opt.voxels_size[2], self.opt.voxels_size[0]])) elif self.opt.position == 'embedding1': input_channel = self.opt.input_channel xyz_in_channels = 1 + 3 embedding_width = 192 embedding_depth = 5 self.embeddingnet = nn.Sequential( nn.Linear(xyz_in_channels, embedding_width), nn.ReLU(inplace=True), *[nn.Sequential(nn.Linear(embedding_width, embedding_width), nn.ReLU(inplace=True)) for _ in range(embedding_depth - 2)], nn.Linear(embedding_width, self.opt.input_channel),) nn.init.constant_(self.embeddingnet[-1].bias, 0) self.pos_embedding1 = None self.pos_embedding_save = torch.nn.Parameter(torch.zeros([1, input_channel, self.opt.voxels_size[1], self.opt.voxels_size[2], self.opt.voxels_size[0]]), requires_grad= False) else: self.pos_embedding = None self.pos_embedding1 = None input_channel = self.opt.input_channel scene_centroid_x = 0.0 scene_centroid_y = 0.0 scene_centroid_z = 0.0 scene_centroid = np.array([scene_centroid_x, scene_centroid_y, scene_centroid_z]).reshape([1, 3]) self.register_buffer('scene_centroid', torch.from_numpy(scene_centroid).float()) self.bounds = (self.opt.real_size[0], self.opt.real_size[1], self.opt.real_size[2], self.opt.real_size[3], self.opt.real_size[4], self.opt.real_size[5]) # bounds = (-40, 40, -40, 40, -1, 5.4) self.vox_util = vox.Vox_util( self.Z, self.Y, self.X, scene_centroid=self.scene_centroid, bounds=self.bounds, position = self.opt.position, length_pose_encoding = length_pose_encoding, opt = self.opt, assert_cube=False) if self.opt.position != 'No' and self.opt.position != 'embedding': self.meta_data = self.vox_util.get_meta_data(cam_center=torch.Tensor([[1.2475, 0.0673, 1.5356]]), camB_T_camA=None).to('cuda') activate_fun = nn.ReLU(inplace=True) if self.opt.aggregation == '3dcnn': out_channel = self.opt.out_channel self._3DCNN = S3DCNN(input_planes=input_channel, out_planes=out_channel, planes=self.opt.con_channel, activate_fun=activate_fun, opt=opt) else: print('please define the aggregation') exit() def feature2vox_simple(self, features, pix_T_cams, cam0_T_camXs, __p, __u): pix_T_cams_ = pix_T_cams camXs_T_cam0_ = geom.safe_inverse(cam0_T_camXs) _, C, Hf, Wf = features.shape sy = Hf / float(self.opt.height) sx = Wf / float(self.opt.width) # unproject image feature to 3d grid featpix_T_cams_ = geom.scale_intrinsics(pix_T_cams_, sx, sy) # pix_T_cams_ shape: [6,4,4] feature down sample -> featpix_T_cams_ feat_mems_ = self.vox_util.unproject_image_to_mem( features, basic.matmul2(featpix_T_cams_, camXs_T_cam0_), camXs_T_cam0_, self.Z, self.Y, self.X) # feat_mems_ shape: torch.Size([6, 128, 200, 8, 200]) feat_mems = __u(feat_mems_) # B, S, C, Z, Y, X # torch.Size([1, 6, 128, 200, 8, 200]) mask_mems = (torch.abs(feat_mems) > 0).float() feat_mem = basic.reduce_masked_mean(feat_mems, mask_mems, dim=1) # B, C, Z, Y, X feat_mem = feat_mem.permute(0, 1, 4, 3, 2) # [0, ...].unsqueeze(0) # ZYX -> XYZ return feat_mem def grid_sampler(self, xyz, *grids, align_corners=True, avail_mask=None, vis=False): '''Wrapper for the interp operation''' # pdb.set_trace() if self.opt.semantic_sample_ratio < 1.0 and self.use_semantic and not vis: group_size = int(1.0 / self.opt.semantic_sample_ratio) group_num = xyz.shape[1] // group_size xyz_sem = xyz[:, :group_size * group_num].reshape(xyz.shape[0], group_num, group_size, 3).mean(dim=2) else: xyz_sem = None if avail_mask is not None: if self.opt.contracted_coord: ind_norm = self.norm_func(xyz) avail_mask = self.effective_points_mask(ind_norm) ind_norm = ind_norm[avail_mask] if xyz_sem is not None: avail_mask_sem = avail_mask[:, :group_size * group_num].reshape(avail_mask.shape[0], group_num, group_size).any(dim=-1) ind_norm_sem = self.norm_func(xyz_sem[avail_mask_sem]) else: xyz_masked = xyz[avail_mask] ind_norm = self.norm_func(xyz_masked) if xyz_sem is not None: avail_mask_sem = avail_mask[:, :group_size * group_num].reshape(avail_mask.shape[0], group_num, group_size).any(dim=-1) ind_norm_sem = self.norm_func(xyz_sem[avail_mask_sem]) else: ind_norm = self.norm_func(xyz) if xyz_sem is not None: ind_norm_sem = self.norm_func(xyz_sem) avail_mask_sem = None ind_norm = ind_norm.flip((-1,)) # value range: [-1, 1] shape = ind_norm.shape[:-1] ind_norm = ind_norm.reshape(1, 1, 1, -1, 3) if xyz_sem is None: grid = grids[0] # BCXYZ # torch.Size([1, C, 256, 256, 16]) ret_lst = F.grid_sample(grid, ind_norm, mode='bilinear', align_corners=align_corners).reshape(grid.shape[1], -1).T.reshape(*shape, grid.shape[1]) if self.use_semantic: semantic, feats = ret_lst[..., :self.semantic_classes], ret_lst[..., -1] return feats, avail_mask, semantic else: return ret_lst.squeeze(), avail_mask else: ind_norm_sem = ind_norm_sem.flip((-1,)) shape_sem = ind_norm_sem.shape[:-1] ind_norm_sem = ind_norm_sem.reshape(1, 1, 1, -1, 3) grid_sem = grids[0][:, :self.semantic_classes] # BCXYZ # torch.Size([1, semantic_classes, H, W, Z]) grid_geo = grids[0][:, -1:] # BCXYZ # torch.Size([1, 1, H, W, Z]) ret_sem = F.grid_sample(grid_sem, ind_norm_sem, mode='bilinear', align_corners=align_corners).reshape(grid_sem.shape[1], -1).T.reshape(*shape_sem, grid_sem.shape[1]) ret_geo = F.grid_sample(grid_geo, ind_norm, mode='bilinear', align_corners=align_corners).reshape(grid_geo.shape[1], -1).T.reshape(*shape, grid_geo.shape[1]) return ret_geo.squeeze(), avail_mask, ret_sem, avail_mask_sem, group_num, group_size def sample_ray(self, rays_o, rays_d, is_train): '''Sample query points on rays''' Zval = self.Zval.to(rays_o) if is_train: Zval = Zval.repeat(rays_d.shape[-2], 1) Zval += (torch.rand_like(Zval[:, [0]]) * 0.2 - 0.1) * self.stepsize_log * self.voxel_size Zval = Zval.clamp(min=0.0) Zval = Zval + self.near rays_pts = rays_o[..., None, :] + rays_d[..., None, :] * Zval[..., None] rays_pts_depth = (rays_o[..., None, :] - rays_pts).norm(dim=-1) if self.opt.contracted_coord: # contracted coordiante has infinite perception range mask_outbbox = torch.zeros_like(rays_pts[..., 0]).bool() else: mask_outbbox = ((self.xyz_min > rays_pts) | (rays_pts > self.xyz_max)).any(dim=-1) return rays_pts, mask_outbbox, Zval, rays_pts_depth def effective_points_mask(self, points): '''Mask out points that are too close to each other in the contracted coordinate''' dist = torch.diff(points, dim=-2, prepend=torch.zeros_like(points[..., :1, :])).abs() xyz_thresh = 0.4 / torch.tensor([self.X, self.Y, self.Z]).to(points) mask = (dist > xyz_thresh).bool().any(dim=-1) return mask def activate_density(self, density, dists): return 1 - torch.exp(-F.relu(density) * dists) def get_density(self, rays_o, rays_d, Voxel_feat, is_train, inputs): dtype = torch.float16 if self.opt.use_fp16 else torch.float32 device = rays_o.device rays_o, rays_d, Voxel_feat = rays_o.to(dtype), rays_d.to(dtype), Voxel_feat.to(dtype) reg_loss = {} eps_time = time.time() with torch.no_grad(): rays_o_i = rays_o[0, ...].flatten(0, 2) # HXWX3 rays_d_i = rays_d[0, ...].flatten(0, 2) # HXWX3 rays_pts, mask_outbbox, z_vals, rays_pts_depth = self.sample_ray(rays_o_i, rays_d_i, is_train=is_train) dists = rays_pts_depth[..., 1:] - rays_pts_depth[..., :-1] # [num pixels, num points - 1] dists = torch.cat([dists, 1e4 * torch.ones_like(dists[..., :1])], dim=-1) # [num pixels, num points] sample_ret = self.grid_sampler(rays_pts, Voxel_feat, avail_mask=~mask_outbbox) if self.use_semantic: if self.opt.semantic_sample_ratio < 1.0: geo_feats, mask, semantic, mask_sem, group_num, group_size = sample_ret else: geo_feats, mask, semantic = sample_ret else: geo_feats, mask = sample_ret if self.opt.render_type == 'prob': weights = torch.zeros_like(rays_pts[..., 0]) weights[:, -1] = 1 geo_feats = torch.sigmoid(geo_feats) if self.opt.last_free: geo_feats = 1.0 - geo_feats # the last channel is the probability of being free weights[mask] = geo_feats # accumulate weights = weights.cumsum(dim=1).clamp(max=1) alphainv_fin = weights[..., -1] weights = weights.diff(dim=1, prepend=torch.zeros((rays_pts.shape[:1])).unsqueeze(1).to(device=device, dtype=dtype)) depth = (weights * z_vals).sum(-1) rgb_marched = 0 elif self.opt.render_type == 'density': alpha = torch.zeros_like(rays_pts[..., 0]) # [num pixels, num points] alpha[mask] = self.activate_density(geo_feats, dists[mask])
weights, alphainv_cum = render.get_ray_marching_ray(alpha)
3
2023-12-14 15:00:21+00:00
12k
Kevin-thu/DiffMorpher
app.py
[ { "identifier": "DiffMorpherPipeline", "path": "model.py", "snippet": "class DiffMorpherPipeline(StableDiffusionPipeline):\n\n def __init__(self,\n vae: AutoencoderKL,\n text_encoder: CLIPTextModel,\n tokenizer: CLIPTokenizer,\n unet: UN...
import os import torch import numpy as np import cv2 import gradio as gr from PIL import Image from datetime import datetime from model import DiffMorpherPipeline from utils.lora_utils import train_lora
7,250
LENGTH=450 def train_lora_interface( image, prompt, model_path, output_path, lora_steps, lora_rank, lora_lr, num ): os.makedirs(output_path, exist_ok=True) train_lora(image, prompt, output_path, model_path, lora_steps=lora_steps, lora_lr=lora_lr, lora_rank=lora_rank, weight_name=f"lora_{num}.ckpt", progress=gr.Progress()) return f"Train LoRA {'A' if num == 0 else 'B'} Done!" def run_diffmorpher( image_0, image_1, prompt_0, prompt_1, model_path, lora_mode, lamb, use_adain, use_reschedule, num_frames, fps, save_inter, load_lora_path_0, load_lora_path_1, output_path ): run_id = datetime.now().strftime("%H%M") + "_" + datetime.now().strftime("%Y%m%d") os.makedirs(output_path, exist_ok=True)
LENGTH=450 def train_lora_interface( image, prompt, model_path, output_path, lora_steps, lora_rank, lora_lr, num ): os.makedirs(output_path, exist_ok=True) train_lora(image, prompt, output_path, model_path, lora_steps=lora_steps, lora_lr=lora_lr, lora_rank=lora_rank, weight_name=f"lora_{num}.ckpt", progress=gr.Progress()) return f"Train LoRA {'A' if num == 0 else 'B'} Done!" def run_diffmorpher( image_0, image_1, prompt_0, prompt_1, model_path, lora_mode, lamb, use_adain, use_reschedule, num_frames, fps, save_inter, load_lora_path_0, load_lora_path_1, output_path ): run_id = datetime.now().strftime("%H%M") + "_" + datetime.now().strftime("%Y%m%d") os.makedirs(output_path, exist_ok=True)
morpher_pipeline = DiffMorpherPipeline.from_pretrained(model_path, torch_dtype=torch.float32).to("cuda")
0
2023-12-11 15:19:07+00:00
12k
modelscope/richdreamer
threestudio/systems/base.py
[ { "identifier": "Exporter", "path": "threestudio/models/exporters/base.py", "snippet": "class Exporter(BaseObject):\n @dataclass\n class Config(BaseObject.Config):\n save_video: bool = False\n\n cfg: Config\n\n def configure(\n self,\n geometry: BaseImplicitGeometry,\n ...
import os import pytorch_lightning as pl import torch.nn.functional as F import threestudio from dataclasses import dataclass, field from threestudio.models.exporters.base import Exporter, ExporterOutput from threestudio.systems.utils import parse_optimizer, parse_scheduler from threestudio.utils.base import (Updateable, update_end_if_possible, update_if_possible,) from threestudio.utils.config import parse_structured from threestudio.utils.misc import C, cleanup, get_device, load_module_weights from threestudio.utils.saving import SaverMixin from threestudio.utils.typing import * from threestudio.utils.config import load_config, parse_structured
9,625
class BaseSystem(pl.LightningModule, Updateable, SaverMixin): @dataclass class Config: loggers: dict = field(default_factory=dict) loss: dict = field(default_factory=dict) optimizer: dict = field(default_factory=dict) scheduler: Optional[dict] = None weights: Optional[str] = None weights_ignore_modules: Optional[List[str]] = None cleanup_after_validation_step: bool = False cleanup_after_test_step: bool = False cfg: Config def __init__(self, cfg, resumed=False) -> None: super().__init__() self.cfg = parse_structured(self.Config, cfg) self._save_dir: Optional[str] = None self._resumed: bool = resumed self._resumed_eval: bool = False self._resumed_eval_status: dict = {"global_step": 0, "current_epoch": 0} if "loggers" in cfg: self.create_loggers(cfg.loggers) self.configure() if self.cfg.weights is not None: self.load_weights(self.cfg.weights, self.cfg.weights_ignore_modules) self.post_configure() def load_weights(self, weights: str, ignore_modules: Optional[List[str]] = None): state_dict, epoch, global_step = load_module_weights( weights, ignore_modules=ignore_modules, map_location="cpu" ) self.load_state_dict(state_dict, strict=False) # restore step-dependent states self.do_update_step(epoch, global_step, on_load_weights=True) def set_resume_status(self, current_epoch: int, global_step: int): # restore correct epoch and global step in eval self._resumed_eval = True self._resumed_eval_status["current_epoch"] = current_epoch self._resumed_eval_status["global_step"] = global_step @property def resumed(self): # whether from resumed checkpoint return self._resumed @property def true_global_step(self): if self._resumed_eval: return self._resumed_eval_status["global_step"] else: return self.global_step @property def true_current_epoch(self): if self._resumed_eval: return self._resumed_eval_status["current_epoch"] else: return self.current_epoch def configure(self) -> None: pass def post_configure(self) -> None: """ executed after weights are loaded """ pass def C(self, value: Any) -> float: return C(value, self.true_current_epoch, self.true_global_step) def configure_optimizers(self):
class BaseSystem(pl.LightningModule, Updateable, SaverMixin): @dataclass class Config: loggers: dict = field(default_factory=dict) loss: dict = field(default_factory=dict) optimizer: dict = field(default_factory=dict) scheduler: Optional[dict] = None weights: Optional[str] = None weights_ignore_modules: Optional[List[str]] = None cleanup_after_validation_step: bool = False cleanup_after_test_step: bool = False cfg: Config def __init__(self, cfg, resumed=False) -> None: super().__init__() self.cfg = parse_structured(self.Config, cfg) self._save_dir: Optional[str] = None self._resumed: bool = resumed self._resumed_eval: bool = False self._resumed_eval_status: dict = {"global_step": 0, "current_epoch": 0} if "loggers" in cfg: self.create_loggers(cfg.loggers) self.configure() if self.cfg.weights is not None: self.load_weights(self.cfg.weights, self.cfg.weights_ignore_modules) self.post_configure() def load_weights(self, weights: str, ignore_modules: Optional[List[str]] = None): state_dict, epoch, global_step = load_module_weights( weights, ignore_modules=ignore_modules, map_location="cpu" ) self.load_state_dict(state_dict, strict=False) # restore step-dependent states self.do_update_step(epoch, global_step, on_load_weights=True) def set_resume_status(self, current_epoch: int, global_step: int): # restore correct epoch and global step in eval self._resumed_eval = True self._resumed_eval_status["current_epoch"] = current_epoch self._resumed_eval_status["global_step"] = global_step @property def resumed(self): # whether from resumed checkpoint return self._resumed @property def true_global_step(self): if self._resumed_eval: return self._resumed_eval_status["global_step"] else: return self.global_step @property def true_current_epoch(self): if self._resumed_eval: return self._resumed_eval_status["current_epoch"] else: return self.current_epoch def configure(self) -> None: pass def post_configure(self) -> None: """ executed after weights are loaded """ pass def C(self, value: Any) -> float: return C(value, self.true_current_epoch, self.true_global_step) def configure_optimizers(self):
optim = parse_optimizer(self.cfg.optimizer, self)
2
2023-12-06 07:53:11+00:00
12k
rehg-lab/RAVE
annotator/oneformer/detectron2/modeling/roi_heads/fast_rcnn.py
[ { "identifier": "configurable", "path": "annotator/oneformer/detectron2/config/config.py", "snippet": "def configurable(init_func=None, *, from_config=None):\r\n \"\"\"\r\n Decorate a function or a class's __init__ method so that it can be called\r\n with a :class:`CfgNode` object using a :func...
import logging import torch from typing import Callable, Dict, List, Optional, Tuple, Union from torch import nn from torch.nn import functional as F from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.data.detection_utils import get_fed_loss_cls_weights from annotator.oneformer.detectron2.layers import ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple from annotator.oneformer.detectron2.modeling.box_regression import Box2BoxTransform, _dense_box_regression_loss from annotator.oneformer.detectron2.structures import Boxes, Instances from annotator.oneformer.detectron2.utils.events import get_event_storage
9,977
filter_mask = scores > score_thresh # R x K # R' x 2. First column contains indices of the R predictions; # Second column contains indices of classes. filter_inds = filter_mask.nonzero() if num_bbox_reg_classes == 1: boxes = boxes[filter_inds[:, 0], 0] else: boxes = boxes[filter_mask] scores = scores[filter_mask] # 2. Apply NMS for each class independently. keep = batched_nms(boxes, scores, filter_inds[:, 1], nms_thresh) if topk_per_image >= 0: keep = keep[:topk_per_image] boxes, scores, filter_inds = boxes[keep], scores[keep], filter_inds[keep] result = Instances(image_shape) result.pred_boxes = Boxes(boxes) result.scores = scores result.pred_classes = filter_inds[:, 1] return result, filter_inds[:, 0] class FastRCNNOutputLayers(nn.Module): """ Two linear layers for predicting Fast R-CNN outputs: 1. proposal-to-detection box regression deltas 2. classification scores """ @configurable def __init__( self, input_shape: ShapeSpec, *, box2box_transform, num_classes: int, test_score_thresh: float = 0.0, test_nms_thresh: float = 0.5, test_topk_per_image: int = 100, cls_agnostic_bbox_reg: bool = False, smooth_l1_beta: float = 0.0, box_reg_loss_type: str = "smooth_l1", loss_weight: Union[float, Dict[str, float]] = 1.0, use_fed_loss: bool = False, use_sigmoid_ce: bool = False, get_fed_loss_cls_weights: Optional[Callable] = None, fed_loss_num_classes: int = 50, ): """ NOTE: this interface is experimental. Args: input_shape (ShapeSpec): shape of the input feature to this module box2box_transform (Box2BoxTransform or Box2BoxTransformRotated): num_classes (int): number of foreground classes test_score_thresh (float): threshold to filter predictions results. test_nms_thresh (float): NMS threshold for prediction results. test_topk_per_image (int): number of top predictions to produce per image. cls_agnostic_bbox_reg (bool): whether to use class agnostic for bbox regression smooth_l1_beta (float): transition point from L1 to L2 loss. Only used if `box_reg_loss_type` is "smooth_l1" box_reg_loss_type (str): Box regression loss type. One of: "smooth_l1", "giou", "diou", "ciou" loss_weight (float|dict): weights to use for losses. Can be single float for weighting all losses, or a dict of individual weightings. Valid dict keys are: * "loss_cls": applied to classification loss * "loss_box_reg": applied to box regression loss use_fed_loss (bool): whether to use federated loss which samples additional negative classes to calculate the loss use_sigmoid_ce (bool): whether to calculate the loss using weighted average of binary cross entropy with logits. This could be used together with federated loss get_fed_loss_cls_weights (Callable): a callable which takes dataset name and frequency weight power, and returns the probabilities to sample negative classes for federated loss. The implementation can be found in detectron2/data/detection_utils.py fed_loss_num_classes (int): number of federated classes to keep in total """ super().__init__() if isinstance(input_shape, int): # some backward compatibility input_shape = ShapeSpec(channels=input_shape) self.num_classes = num_classes input_size = input_shape.channels * (input_shape.width or 1) * (input_shape.height or 1) # prediction layer for num_classes foreground classes and one background class (hence + 1) self.cls_score = nn.Linear(input_size, num_classes + 1) num_bbox_reg_classes = 1 if cls_agnostic_bbox_reg else num_classes box_dim = len(box2box_transform.weights) self.bbox_pred = nn.Linear(input_size, num_bbox_reg_classes * box_dim) nn.init.normal_(self.cls_score.weight, std=0.01) nn.init.normal_(self.bbox_pred.weight, std=0.001) for l in [self.cls_score, self.bbox_pred]: nn.init.constant_(l.bias, 0) self.box2box_transform = box2box_transform self.smooth_l1_beta = smooth_l1_beta self.test_score_thresh = test_score_thresh self.test_nms_thresh = test_nms_thresh self.test_topk_per_image = test_topk_per_image self.box_reg_loss_type = box_reg_loss_type if isinstance(loss_weight, float): loss_weight = {"loss_cls": loss_weight, "loss_box_reg": loss_weight} self.loss_weight = loss_weight self.use_fed_loss = use_fed_loss self.use_sigmoid_ce = use_sigmoid_ce self.fed_loss_num_classes = fed_loss_num_classes if self.use_fed_loss: assert self.use_sigmoid_ce, "Please use sigmoid cross entropy loss with federated loss" fed_loss_cls_weights = get_fed_loss_cls_weights() assert ( len(fed_loss_cls_weights) == self.num_classes ), "Please check the provided fed_loss_cls_weights. Their size should match num_classes" self.register_buffer("fed_loss_cls_weights", fed_loss_cls_weights) @classmethod def from_config(cls, cfg, input_shape): return { "input_shape": input_shape,
# Copyright (c) Facebook, Inc. and its affiliates. __all__ = ["fast_rcnn_inference", "FastRCNNOutputLayers"] logger = logging.getLogger(__name__) """ Shape shorthand in this module: N: number of images in the minibatch R: number of ROIs, combined over all images, in the minibatch Ri: number of ROIs in image i K: number of foreground classes. E.g.,there are 80 foreground classes in COCO. Naming convention: deltas: refers to the 4-d (dx, dy, dw, dh) deltas that parameterize the box2box transform (see :class:`box_regression.Box2BoxTransform`). pred_class_logits: predicted class scores in [-inf, +inf]; use softmax(pred_class_logits) to estimate P(class). gt_classes: ground-truth classification labels in [0, K], where [0, K) represent foreground object classes and K represents the background class. pred_proposal_deltas: predicted box2box transform deltas for transforming proposals to detection box predictions. gt_proposal_deltas: ground-truth box2box transform deltas """ def fast_rcnn_inference( boxes: List[torch.Tensor], scores: List[torch.Tensor], image_shapes: List[Tuple[int, int]], score_thresh: float, nms_thresh: float, topk_per_image: int, ): """ Call `fast_rcnn_inference_single_image` for all images. Args: boxes (list[Tensor]): A list of Tensors of predicted class-specific or class-agnostic boxes for each image. Element i has shape (Ri, K * 4) if doing class-specific regression, or (Ri, 4) if doing class-agnostic regression, where Ri is the number of predicted objects for image i. This is compatible with the output of :meth:`FastRCNNOutputLayers.predict_boxes`. scores (list[Tensor]): A list of Tensors of predicted class scores for each image. Element i has shape (Ri, K + 1), where Ri is the number of predicted objects for image i. Compatible with the output of :meth:`FastRCNNOutputLayers.predict_probs`. image_shapes (list[tuple]): A list of (width, height) tuples for each image in the batch. score_thresh (float): Only return detections with a confidence score exceeding this threshold. nms_thresh (float): The threshold to use for box non-maximum suppression. Value in [0, 1]. topk_per_image (int): The number of top scoring detections to return. Set < 0 to return all detections. Returns: instances: (list[Instances]): A list of N instances, one for each image in the batch, that stores the topk most confidence detections. kept_indices: (list[Tensor]): A list of 1D tensor of length of N, each element indicates the corresponding boxes/scores index in [0, Ri) from the input, for image i. """ result_per_image = [ fast_rcnn_inference_single_image( boxes_per_image, scores_per_image, image_shape, score_thresh, nms_thresh, topk_per_image ) for scores_per_image, boxes_per_image, image_shape in zip(scores, boxes, image_shapes) ] return [x[0] for x in result_per_image], [x[1] for x in result_per_image] def _log_classification_stats(pred_logits, gt_classes, prefix="fast_rcnn"): """ Log the classification metrics to EventStorage. Args: pred_logits: Rx(K+1) logits. The last column is for background class. gt_classes: R labels """ num_instances = gt_classes.numel() if num_instances == 0: return pred_classes = pred_logits.argmax(dim=1) bg_class_ind = pred_logits.shape[1] - 1 fg_inds = (gt_classes >= 0) & (gt_classes < bg_class_ind) num_fg = fg_inds.nonzero().numel() fg_gt_classes = gt_classes[fg_inds] fg_pred_classes = pred_classes[fg_inds] num_false_negative = (fg_pred_classes == bg_class_ind).nonzero().numel() num_accurate = (pred_classes == gt_classes).nonzero().numel() fg_num_accurate = (fg_pred_classes == fg_gt_classes).nonzero().numel() storage = get_event_storage() storage.put_scalar(f"{prefix}/cls_accuracy", num_accurate / num_instances) if num_fg > 0: storage.put_scalar(f"{prefix}/fg_cls_accuracy", fg_num_accurate / num_fg) storage.put_scalar(f"{prefix}/false_negative", num_false_negative / num_fg) def fast_rcnn_inference_single_image( boxes, scores, image_shape: Tuple[int, int], score_thresh: float, nms_thresh: float, topk_per_image: int, ): """ Single-image inference. Return bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS). Args: Same as `fast_rcnn_inference`, but with boxes, scores, and image shapes per image. Returns: Same as `fast_rcnn_inference`, but for only one image. """ valid_mask = torch.isfinite(boxes).all(dim=1) & torch.isfinite(scores).all(dim=1) if not valid_mask.all(): boxes = boxes[valid_mask] scores = scores[valid_mask] scores = scores[:, :-1] num_bbox_reg_classes = boxes.shape[1] // 4 # Convert to Boxes to use the `clip` function ... boxes = Boxes(boxes.reshape(-1, 4)) boxes.clip(image_shape) boxes = boxes.tensor.view(-1, num_bbox_reg_classes, 4) # R x C x 4 # 1. Filter results based on detection scores. It can make NMS more efficient # by filtering out low-confidence detections. filter_mask = scores > score_thresh # R x K # R' x 2. First column contains indices of the R predictions; # Second column contains indices of classes. filter_inds = filter_mask.nonzero() if num_bbox_reg_classes == 1: boxes = boxes[filter_inds[:, 0], 0] else: boxes = boxes[filter_mask] scores = scores[filter_mask] # 2. Apply NMS for each class independently. keep = batched_nms(boxes, scores, filter_inds[:, 1], nms_thresh) if topk_per_image >= 0: keep = keep[:topk_per_image] boxes, scores, filter_inds = boxes[keep], scores[keep], filter_inds[keep] result = Instances(image_shape) result.pred_boxes = Boxes(boxes) result.scores = scores result.pred_classes = filter_inds[:, 1] return result, filter_inds[:, 0] class FastRCNNOutputLayers(nn.Module): """ Two linear layers for predicting Fast R-CNN outputs: 1. proposal-to-detection box regression deltas 2. classification scores """ @configurable def __init__( self, input_shape: ShapeSpec, *, box2box_transform, num_classes: int, test_score_thresh: float = 0.0, test_nms_thresh: float = 0.5, test_topk_per_image: int = 100, cls_agnostic_bbox_reg: bool = False, smooth_l1_beta: float = 0.0, box_reg_loss_type: str = "smooth_l1", loss_weight: Union[float, Dict[str, float]] = 1.0, use_fed_loss: bool = False, use_sigmoid_ce: bool = False, get_fed_loss_cls_weights: Optional[Callable] = None, fed_loss_num_classes: int = 50, ): """ NOTE: this interface is experimental. Args: input_shape (ShapeSpec): shape of the input feature to this module box2box_transform (Box2BoxTransform or Box2BoxTransformRotated): num_classes (int): number of foreground classes test_score_thresh (float): threshold to filter predictions results. test_nms_thresh (float): NMS threshold for prediction results. test_topk_per_image (int): number of top predictions to produce per image. cls_agnostic_bbox_reg (bool): whether to use class agnostic for bbox regression smooth_l1_beta (float): transition point from L1 to L2 loss. Only used if `box_reg_loss_type` is "smooth_l1" box_reg_loss_type (str): Box regression loss type. One of: "smooth_l1", "giou", "diou", "ciou" loss_weight (float|dict): weights to use for losses. Can be single float for weighting all losses, or a dict of individual weightings. Valid dict keys are: * "loss_cls": applied to classification loss * "loss_box_reg": applied to box regression loss use_fed_loss (bool): whether to use federated loss which samples additional negative classes to calculate the loss use_sigmoid_ce (bool): whether to calculate the loss using weighted average of binary cross entropy with logits. This could be used together with federated loss get_fed_loss_cls_weights (Callable): a callable which takes dataset name and frequency weight power, and returns the probabilities to sample negative classes for federated loss. The implementation can be found in detectron2/data/detection_utils.py fed_loss_num_classes (int): number of federated classes to keep in total """ super().__init__() if isinstance(input_shape, int): # some backward compatibility input_shape = ShapeSpec(channels=input_shape) self.num_classes = num_classes input_size = input_shape.channels * (input_shape.width or 1) * (input_shape.height or 1) # prediction layer for num_classes foreground classes and one background class (hence + 1) self.cls_score = nn.Linear(input_size, num_classes + 1) num_bbox_reg_classes = 1 if cls_agnostic_bbox_reg else num_classes box_dim = len(box2box_transform.weights) self.bbox_pred = nn.Linear(input_size, num_bbox_reg_classes * box_dim) nn.init.normal_(self.cls_score.weight, std=0.01) nn.init.normal_(self.bbox_pred.weight, std=0.001) for l in [self.cls_score, self.bbox_pred]: nn.init.constant_(l.bias, 0) self.box2box_transform = box2box_transform self.smooth_l1_beta = smooth_l1_beta self.test_score_thresh = test_score_thresh self.test_nms_thresh = test_nms_thresh self.test_topk_per_image = test_topk_per_image self.box_reg_loss_type = box_reg_loss_type if isinstance(loss_weight, float): loss_weight = {"loss_cls": loss_weight, "loss_box_reg": loss_weight} self.loss_weight = loss_weight self.use_fed_loss = use_fed_loss self.use_sigmoid_ce = use_sigmoid_ce self.fed_loss_num_classes = fed_loss_num_classes if self.use_fed_loss: assert self.use_sigmoid_ce, "Please use sigmoid cross entropy loss with federated loss" fed_loss_cls_weights = get_fed_loss_cls_weights() assert ( len(fed_loss_cls_weights) == self.num_classes ), "Please check the provided fed_loss_cls_weights. Their size should match num_classes" self.register_buffer("fed_loss_cls_weights", fed_loss_cls_weights) @classmethod def from_config(cls, cfg, input_shape): return { "input_shape": input_shape,
"box2box_transform": Box2BoxTransform(weights=cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS),
5
2023-12-05 02:51:53+00:00
12k
DiffusionLight/DiffusionLight
inpaint.py
[ { "identifier": "BallInpainter", "path": "relighting/inpainter.py", "snippet": "class BallInpainter():\n def __init__(self, pipeline, sd_arch, control_generator, disable_water_mask=True):\n self.pipeline = pipeline\n self.sd_arch = sd_arch\n self.control_generator = control_gener...
import torch import argparse import numpy as np import torch.distributed as dist import os import json import relighting.dist_utils as dist_util import time from PIL import Image from tqdm.auto import tqdm from relighting.inpainter import BallInpainter from relighting.mask_utils import MaskGenerator from relighting.ball_processor import ( get_ideal_normal_ball, crop_ball ) from relighting.dataset import GeneralLoader from relighting.utils import name2hash from relighting.argument import ( SD_MODELS, CONTROLNET_MODELS, VAE_MODELS )
7,760
# get list of all EVs ev_list = [float(x) for x in args.ev.split(",")] interpolants = [ev / args.max_negative_ev for ev in ev_list] print("EV : ", ev_list) print("EV : ", interpolants) # calculate prompt embeddings prompt_normal = args.prompt prompt_dark = args.prompt_dark prompt_embeds_normal, _, pooled_prompt_embeds_normal, _ = pipe.pipeline.encode_prompt(prompt_normal) prompt_embeds_dark, _, pooled_prompt_embeds_dark, _ = pipe.pipeline.encode_prompt(prompt_dark) # interpolate embeddings interpolate_embeds = [] for t in interpolants: int_prompt_embeds = prompt_embeds_normal + t * (prompt_embeds_dark - prompt_embeds_normal) int_pooled_prompt_embeds = pooled_prompt_embeds_normal + t * (pooled_prompt_embeds_dark - pooled_prompt_embeds_normal) interpolate_embeds.append((int_prompt_embeds, int_pooled_prompt_embeds)) return dict(zip(ev_list, interpolate_embeds)) def main(): # load arguments args = create_argparser().parse_args() # get local rank if args.is_cpu: device = torch.device("cpu") torch_dtype = torch.float32 else: device = dist_util.dev() torch_dtype = torch.float16 # so, we need ball_dilate >= 16 (2*vae_scale_factor) to make our mask shape = (272, 272) assert args.ball_dilate % 2 == 0 # ball dilation should be symmetric # create controlnet pipeline if args.model_option in ["sdxl", "sdxl_fast"] and args.use_controlnet: model, controlnet = SD_MODELS[args.model_option], CONTROLNET_MODELS[args.model_option] pipe = BallInpainter.from_sdxl( model=model, controlnet=controlnet, device=device, torch_dtype = torch_dtype, offload = args.offload ) elif args.model_option in ["sdxl", "sdxl_fast"] and not args.use_controlnet: model = SD_MODELS[args.model_option] pipe = BallInpainter.from_sdxl( model=model, controlnet=None, device=device, torch_dtype = torch_dtype, offload = args.offload ) elif args.use_controlnet: model, controlnet = SD_MODELS[args.model_option], CONTROLNET_MODELS[args.model_option] pipe = BallInpainter.from_sd( model=model, controlnet=controlnet, device=device, torch_dtype = torch_dtype, offload = args.offload ) else: model = SD_MODELS[args.model_option] pipe = BallInpainter.from_sd( model=model, controlnet=None, device=device, torch_dtype = torch_dtype, offload = args.offload ) if args.lora_scale > 0 and args.lora_path is None: raise ValueError("lora scale is not 0 but lora path is not set") if (args.lora_path is not None) and (args.use_lora): print(f"using lora path {args.lora_path}") print(f"using lora scale {args.lora_scale}") pipe.pipeline.load_lora_weights(args.lora_path) pipe.pipeline.fuse_lora(lora_scale=args.lora_scale) # fuse lora weight w' = w + \alpha \Delta w enabled_lora = True else: enabled_lora = False if args.use_torch_compile: try: print("compiling unet model") start_time = time.time() pipe.pipeline.unet = torch.compile(pipe.pipeline.unet, mode="reduce-overhead", fullgraph=True) print("Model compilation time: ", time.time() - start_time) except: pass # default height for sdxl is 1024, if not set, we set default height. if args.model_option == "sdxl" and args.img_height == 0 and args.img_width == 0: args.img_height = 1024 args.img_width = 1024 # load dataset dataset = GeneralLoader( root=args.dataset, resolution=(args.img_width, args.img_height), force_square=args.force_square, return_dict=True, random_shuffle=args.random_loader, process_id=args.idx, process_total=args.total, limit_input=args.limit_input, ) # interpolate embedding embedding_dict = interpolate_embedding(pipe, args) # prepare mask and normal ball
# inpaint the ball on an image # this one is design for general image that does not require special location to place # cross import from inpaint_multi-illum.py def create_argparser(): parser = argparse.ArgumentParser() parser.add_argument("--dataset", type=str, required=True ,help='directory that contain the image') #dataset name or directory parser.add_argument("--ball_size", type=int, default=256, help="size of the ball in pixel") parser.add_argument("--ball_dilate", type=int, default=20, help="How much pixel to dilate the ball to make a sharper edge") parser.add_argument("--prompt", type=str, default="a perfect mirrored reflective chrome ball sphere") parser.add_argument("--prompt_dark", type=str, default="a perfect black dark mirrored reflective chrome ball sphere") parser.add_argument("--negative_prompt", type=str, default="matte, diffuse, flat, dull") parser.add_argument("--model_option", default="sdxl", help='selecting fancy model option (sd15_old, sd15_new, sd21, sdxl)') # [sd15_old, sd15_new, or sd21] parser.add_argument("--output_dir", required=True, type=str, help="output directory") parser.add_argument("--img_height", type=int, default=1024, help="Dataset Image Height") parser.add_argument("--img_width", type=int, default=1024, help="Dataset Image Width") # some good seed 0, 37, 71, 125, 140, 196, 307, 434, 485, 575 | 9021, 9166, 9560, 9814, but default auto is for fairness parser.add_argument("--seed", default="auto", type=str, help="Seed: right now we use single seed instead to reduce the time, (Auto will use hash file name to generate seed)") parser.add_argument("--denoising_step", default=30, type=int, help="number of denoising step of diffusion model") parser.add_argument("--control_scale", default=0.5, type=float, help="controlnet conditioning scale") parser.add_argument('--no_controlnet', dest='use_controlnet', action='store_false', help='by default we using controlnet, we have option to disable to see the different') parser.set_defaults(use_controlnet=True) parser.add_argument('--no_force_square', dest='force_square', action='store_false', help='SDXL is trained for square image, we prefered the square input. but you use this option to disable reshape') parser.set_defaults(force_square=True) parser.add_argument('--no_random_loader', dest='random_loader', action='store_false', help="by default, we random how dataset load. This make us able to peak into the trend of result without waiting entire dataset. but can disable if prefereed") parser.set_defaults(random_loader=True) parser.add_argument('--cpu', dest='is_cpu', action='store_true', help="using CPU inference instead of GPU inference") parser.set_defaults(is_cpu=False) parser.add_argument('--offload', dest='offload', action='store_false', help="to enable diffusers cpu offload") parser.set_defaults(offload=False) parser.add_argument("--limit_input", default=0, type=int, help="limit number of image to process to n image (0 = no limit), useful for run smallset") # LoRA stuff parser.add_argument('--no_lora', dest='use_lora', action='store_false', help='by default we using lora, we have option to disable to see the different') parser.set_defaults(use_lora=True) parser.add_argument("--lora_path", default="models/ThisIsTheFinal-lora-hdr-continuous-largeT@900/0_-5/checkpoint-2500", type=str, help="LoRA Checkpoint path") parser.add_argument("--lora_scale", default=0.75, type=float, help="LoRA scale factor") # speed optimization stuff parser.add_argument('--no_torch_compile', dest='use_torch_compile', action='store_false', help='by default we using torch compile for faster processing speed. disable it if your environemnt is lower than pytorch2.0') parser.set_defaults(use_torch_compile=True) # algorithm + iterative stuff parser.add_argument("--algorithm", type=str, default="iterative", choices=["iterative", "normal"], help="Selecting between iterative or normal (single pass inpaint) algorithm") parser.add_argument("--agg_mode", default="median", type=str) parser.add_argument("--strength", default=0.8, type=float) parser.add_argument("--num_iteration", default=2, type=int) parser.add_argument("--ball_per_iteration", default=30, type=int) parser.add_argument('--no_save_intermediate', dest='save_intermediate', action='store_false') parser.set_defaults(save_intermediate=True) parser.add_argument("--cache_dir", default="./temp_inpaint_iterative", type=str, help="cache directory for iterative inpaint") # pararelle processing parser.add_argument("--idx", default=0, type=int, help="index of the current process, useful for running on multiple node") parser.add_argument("--total", default=1, type=int, help="total number of process") # for HDR stuff parser.add_argument("--max_negative_ev", default=-5, type=int, help="maximum negative EV for lora") parser.add_argument("--ev", default="0,-2.5,-5", type=str, help="EV: list of EV to generate") return parser def get_ball_location(image_data, args): if 'boundary' in image_data: # support predefined boundary if need x = image_data["boundary"]["x"] y = image_data["boundary"]["y"] r = image_data["boundary"]["size"] # support ball dilation half_dilate = args.ball_dilate // 2 # check if not left out-of-bound if x - half_dilate < 0: x += half_dilate if y - half_dilate < 0: y += half_dilate # check if not right out-of-bound if x + r + half_dilate > args.img_width: x -= half_dilate if y + r + half_dilate > args.img_height: y -= half_dilate else: # we use top-left corner notation x, y, r = ((args.img_width // 2) - (args.ball_size // 2), (args.img_height // 2) - (args.ball_size // 2), args.ball_size) return x, y, r def interpolate_embedding(pipe, args): print("interpolate embedding...") # get list of all EVs ev_list = [float(x) for x in args.ev.split(",")] interpolants = [ev / args.max_negative_ev for ev in ev_list] print("EV : ", ev_list) print("EV : ", interpolants) # calculate prompt embeddings prompt_normal = args.prompt prompt_dark = args.prompt_dark prompt_embeds_normal, _, pooled_prompt_embeds_normal, _ = pipe.pipeline.encode_prompt(prompt_normal) prompt_embeds_dark, _, pooled_prompt_embeds_dark, _ = pipe.pipeline.encode_prompt(prompt_dark) # interpolate embeddings interpolate_embeds = [] for t in interpolants: int_prompt_embeds = prompt_embeds_normal + t * (prompt_embeds_dark - prompt_embeds_normal) int_pooled_prompt_embeds = pooled_prompt_embeds_normal + t * (pooled_prompt_embeds_dark - pooled_prompt_embeds_normal) interpolate_embeds.append((int_prompt_embeds, int_pooled_prompt_embeds)) return dict(zip(ev_list, interpolate_embeds)) def main(): # load arguments args = create_argparser().parse_args() # get local rank if args.is_cpu: device = torch.device("cpu") torch_dtype = torch.float32 else: device = dist_util.dev() torch_dtype = torch.float16 # so, we need ball_dilate >= 16 (2*vae_scale_factor) to make our mask shape = (272, 272) assert args.ball_dilate % 2 == 0 # ball dilation should be symmetric # create controlnet pipeline if args.model_option in ["sdxl", "sdxl_fast"] and args.use_controlnet: model, controlnet = SD_MODELS[args.model_option], CONTROLNET_MODELS[args.model_option] pipe = BallInpainter.from_sdxl( model=model, controlnet=controlnet, device=device, torch_dtype = torch_dtype, offload = args.offload ) elif args.model_option in ["sdxl", "sdxl_fast"] and not args.use_controlnet: model = SD_MODELS[args.model_option] pipe = BallInpainter.from_sdxl( model=model, controlnet=None, device=device, torch_dtype = torch_dtype, offload = args.offload ) elif args.use_controlnet: model, controlnet = SD_MODELS[args.model_option], CONTROLNET_MODELS[args.model_option] pipe = BallInpainter.from_sd( model=model, controlnet=controlnet, device=device, torch_dtype = torch_dtype, offload = args.offload ) else: model = SD_MODELS[args.model_option] pipe = BallInpainter.from_sd( model=model, controlnet=None, device=device, torch_dtype = torch_dtype, offload = args.offload ) if args.lora_scale > 0 and args.lora_path is None: raise ValueError("lora scale is not 0 but lora path is not set") if (args.lora_path is not None) and (args.use_lora): print(f"using lora path {args.lora_path}") print(f"using lora scale {args.lora_scale}") pipe.pipeline.load_lora_weights(args.lora_path) pipe.pipeline.fuse_lora(lora_scale=args.lora_scale) # fuse lora weight w' = w + \alpha \Delta w enabled_lora = True else: enabled_lora = False if args.use_torch_compile: try: print("compiling unet model") start_time = time.time() pipe.pipeline.unet = torch.compile(pipe.pipeline.unet, mode="reduce-overhead", fullgraph=True) print("Model compilation time: ", time.time() - start_time) except: pass # default height for sdxl is 1024, if not set, we set default height. if args.model_option == "sdxl" and args.img_height == 0 and args.img_width == 0: args.img_height = 1024 args.img_width = 1024 # load dataset dataset = GeneralLoader( root=args.dataset, resolution=(args.img_width, args.img_height), force_square=args.force_square, return_dict=True, random_shuffle=args.random_loader, process_id=args.idx, process_total=args.total, limit_input=args.limit_input, ) # interpolate embedding embedding_dict = interpolate_embedding(pipe, args) # prepare mask and normal ball
mask_generator = MaskGenerator()
1
2023-12-07 14:03:31+00:00
12k
eliphatfs/zerorf
zerorf.py
[ { "identifier": "MultiSceneNeRF", "path": "lib/models/autoencoders/multiscene_nerf.py", "snippet": "class MultiSceneNeRF(BaseNeRF):\n\n def __init__(self,\n *args,\n cache_size=0, # cache in RAM, top priority\n cache_16bit=False,\n num_...
import sys import shutil import os import cv2 import tqdm import json import numpy import wandb import torch import torch_redstone as rst import einops from sklearn.cluster import KMeans from lib.models.autoencoders import MultiSceneNeRF from mmgen.models import build_model, build_module from lib.core.optimizer import build_optimizers from lib.core.ssdnerf_gui import OrbitCamera from lib.datasets.nerf_synthetic import NerfSynthetic from lib.datasets.oppo import OppoDataset from PIL import Image from opt import config_parser from pprint import pprint
7,522
_, b, h, w, c = images.shape x, y = w / 2, h / 2 focal_length = y / numpy.tan(meta['fovy'] / 2) intrinsics = numpy.array([[focal_length, focal_length, x, y]] * args.n_views) work_dir = "results/%s" % args.proj_name os.makedirs(work_dir, exist_ok=True) os.chdir(work_dir) if not args.load_image: if args.dataset == "nerf_syn": model_scale = dict(chair=2.1, drums=2.3, ficus=2.3, hotdog=3.0, lego=2.4, materials=2.4, mic=2.5, ship=2.75) world_scale = 2 / model_scale[args.obj] dataset = NerfSynthetic([f"{args.data_dir}/{args.obj}/transforms_train.json"], rgba=True, world_scale=world_scale) val = NerfSynthetic([f"{args.data_dir}/{args.obj}/transforms_val.json"], world_scale=world_scale) test = NerfSynthetic([f"{args.data_dir}/{args.obj}/transforms_test.json"], world_scale=world_scale) entry = dataset[0] selected_idxs = kmeans_downsample(entry['cond_poses'][..., :3, 3], args.n_views) elif args.dataset == "oi": world_scale = 5.0 dataset = OppoDataset(f"{args.data_dir}/{args.obj}/output", split='train', world_scale=world_scale, rgba=True) val = OppoDataset(f"{args.data_dir}/{args.obj}/output", split='test', world_scale=world_scale) test = OppoDataset(f"{args.data_dir}/{args.obj}/output", split='test', world_scale=world_scale) entry = dataset[0] if args.n_views == 6: selected_idxs = [10, 3, 19, 22, 17, 35] elif args.n_views == 4: selected_idxs = [10, 33, 35, 6] else: selected_idxs = kmeans_downsample(entry['cond_poses'][..., :3, 3], args.n_views) data_entry = dict( cond_imgs=torch.tensor(entry['cond_imgs'][selected_idxs][None]).float().to(device), cond_poses=torch.tensor(entry['cond_poses'])[selected_idxs][None].float().to(device), cond_intrinsics=torch.tensor(entry['cond_intrinsics'])[selected_idxs][None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) entry = val[0] val_entry = dict( test_imgs=torch.tensor(entry['cond_imgs'][:args.n_val][None]).float().to(device), test_poses=torch.tensor(entry['cond_poses'][:args.n_val])[None].float().to(device), test_intrinsics=torch.tensor(entry['cond_intrinsics'][:args.n_val])[None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) entry = test[0] test_entry = dict( test_imgs=torch.tensor(entry['cond_imgs'][:][None]).float().to(device), test_poses=torch.tensor(entry['cond_poses'][:])[None].float().to(device), test_intrinsics=torch.tensor(entry['cond_intrinsics'][:])[None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) else: data_entry = dict( cond_imgs=images, cond_poses=torch.tensor(poses)[None].float().to(device) * 0.9, cond_intrinsics=torch.tensor(intrinsics)[None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) selected_idxs = list(range(args.n_views)) pic_h = data_entry['cond_imgs'].shape[-3] pic_w = data_entry['cond_imgs'].shape[-2] if args.load_image: args.model_res = 4 pic_h = pic_w = 320 cam = OrbitCamera('render', pic_w, pic_h, 3.2, 48) decoder_1 = dict( type='TensorialDecoder', preprocessor=dict( type='TensorialGenerator', in_ch=args.model_ch, out_ch=16, noise_res=args.model_res, tensor_config=( ['xy', 'z', 'yz', 'x', 'zx', 'y'] ) ), subreduce=1 if args.load_image else 2, reduce='cat', separate_density_and_color=False, sh_coef_only=False, sdf_mode=False, max_steps=1024 if not args.load_image else 320, n_images=args.n_views, image_h=pic_h, image_w=pic_w, has_time_dynamics=False, visualize_mesh=True ) decoder_2 = dict( type='FreqFactorizedDecoder', preprocessor=dict( type='TensorialGenerator', in_ch=args.model_ch, out_ch=16, noise_res=args.model_res, tensor_config=['xyz', 'xyz'] ), subreduce=1, reduce='cat', separate_density_and_color=False, sh_coef_only=False, sdf_mode=False, max_steps=1024 if not args.load_image else 640, n_images=args.n_views, image_h=pic_h, image_w=pic_w, has_time_dynamics=False, freq_bands=[None, 0.4], visualize_mesh=True ) patch_reg_loss = build_module(dict( type='MaskedTVLoss', power=1.5, loss_weight=0.00 ))
sys.path.append('.') torch.backends.cuda.matmul.allow_tf32 = True def kmeans_downsample(points, n_points_to_sample): kmeans = KMeans(n_points_to_sample).fit(points) return ((points - kmeans.cluster_centers_[..., None, :]) ** 2).sum(-1).argmin(-1).tolist() args = config_parser() pprint(args) model_scaling_factor = 16 device = args.device BLENDER_TO_OPENCV_MATRIX = numpy.array([ [1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1] ], dtype=numpy.float32) code_size = (3, args.model_ch, args.model_res, args.model_res) rst.seed(args.seed) poses = [] intrinsics = [] if args.load_image: image = numpy.array(Image.open(args.load_image)).astype(numpy.float32) / 255.0 image = torch.tensor(image).cuda() images = einops.rearrange(image, '(ph h) (pw w) c -> (ph pw) h w c', ph=3, pw=2)[None] meta = json.load(open(os.path.join(os.path.dirname(__file__), "meta.json"))) poses = numpy.array([ (numpy.array(frame['transform_matrix']) @ BLENDER_TO_OPENCV_MATRIX) * 2 for frame in meta['sample_0']['view_frames'] ]) _, b, h, w, c = images.shape x, y = w / 2, h / 2 focal_length = y / numpy.tan(meta['fovy'] / 2) intrinsics = numpy.array([[focal_length, focal_length, x, y]] * args.n_views) work_dir = "results/%s" % args.proj_name os.makedirs(work_dir, exist_ok=True) os.chdir(work_dir) if not args.load_image: if args.dataset == "nerf_syn": model_scale = dict(chair=2.1, drums=2.3, ficus=2.3, hotdog=3.0, lego=2.4, materials=2.4, mic=2.5, ship=2.75) world_scale = 2 / model_scale[args.obj] dataset = NerfSynthetic([f"{args.data_dir}/{args.obj}/transforms_train.json"], rgba=True, world_scale=world_scale) val = NerfSynthetic([f"{args.data_dir}/{args.obj}/transforms_val.json"], world_scale=world_scale) test = NerfSynthetic([f"{args.data_dir}/{args.obj}/transforms_test.json"], world_scale=world_scale) entry = dataset[0] selected_idxs = kmeans_downsample(entry['cond_poses'][..., :3, 3], args.n_views) elif args.dataset == "oi": world_scale = 5.0 dataset = OppoDataset(f"{args.data_dir}/{args.obj}/output", split='train', world_scale=world_scale, rgba=True) val = OppoDataset(f"{args.data_dir}/{args.obj}/output", split='test', world_scale=world_scale) test = OppoDataset(f"{args.data_dir}/{args.obj}/output", split='test', world_scale=world_scale) entry = dataset[0] if args.n_views == 6: selected_idxs = [10, 3, 19, 22, 17, 35] elif args.n_views == 4: selected_idxs = [10, 33, 35, 6] else: selected_idxs = kmeans_downsample(entry['cond_poses'][..., :3, 3], args.n_views) data_entry = dict( cond_imgs=torch.tensor(entry['cond_imgs'][selected_idxs][None]).float().to(device), cond_poses=torch.tensor(entry['cond_poses'])[selected_idxs][None].float().to(device), cond_intrinsics=torch.tensor(entry['cond_intrinsics'])[selected_idxs][None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) entry = val[0] val_entry = dict( test_imgs=torch.tensor(entry['cond_imgs'][:args.n_val][None]).float().to(device), test_poses=torch.tensor(entry['cond_poses'][:args.n_val])[None].float().to(device), test_intrinsics=torch.tensor(entry['cond_intrinsics'][:args.n_val])[None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) entry = test[0] test_entry = dict( test_imgs=torch.tensor(entry['cond_imgs'][:][None]).float().to(device), test_poses=torch.tensor(entry['cond_poses'][:])[None].float().to(device), test_intrinsics=torch.tensor(entry['cond_intrinsics'][:])[None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) else: data_entry = dict( cond_imgs=images, cond_poses=torch.tensor(poses)[None].float().to(device) * 0.9, cond_intrinsics=torch.tensor(intrinsics)[None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) selected_idxs = list(range(args.n_views)) pic_h = data_entry['cond_imgs'].shape[-3] pic_w = data_entry['cond_imgs'].shape[-2] if args.load_image: args.model_res = 4 pic_h = pic_w = 320 cam = OrbitCamera('render', pic_w, pic_h, 3.2, 48) decoder_1 = dict( type='TensorialDecoder', preprocessor=dict( type='TensorialGenerator', in_ch=args.model_ch, out_ch=16, noise_res=args.model_res, tensor_config=( ['xy', 'z', 'yz', 'x', 'zx', 'y'] ) ), subreduce=1 if args.load_image else 2, reduce='cat', separate_density_and_color=False, sh_coef_only=False, sdf_mode=False, max_steps=1024 if not args.load_image else 320, n_images=args.n_views, image_h=pic_h, image_w=pic_w, has_time_dynamics=False, visualize_mesh=True ) decoder_2 = dict( type='FreqFactorizedDecoder', preprocessor=dict( type='TensorialGenerator', in_ch=args.model_ch, out_ch=16, noise_res=args.model_res, tensor_config=['xyz', 'xyz'] ), subreduce=1, reduce='cat', separate_density_and_color=False, sh_coef_only=False, sdf_mode=False, max_steps=1024 if not args.load_image else 640, n_images=args.n_views, image_h=pic_h, image_w=pic_w, has_time_dynamics=False, freq_bands=[None, 0.4], visualize_mesh=True ) patch_reg_loss = build_module(dict( type='MaskedTVLoss', power=1.5, loss_weight=0.00 ))
nerf: MultiSceneNeRF = build_model(dict(
0
2023-12-14 03:29:28+00:00
12k
u2seg/U2Seg
detectron2/data/datasets/builtin.py
[ { "identifier": "DatasetCatalog", "path": "detectron2/data/catalog.py", "snippet": "class _DatasetCatalog(UserDict):\nclass Metadata(types.SimpleNamespace):\nclass _MetadataCatalog(UserDict):\n def register(self, name, func):\n def get(self, name):\n def list(self) -> List[str]:\n def remove...
import os from detectron2.data import DatasetCatalog, MetadataCatalog from .builtin_meta import ADE20K_SEM_SEG_CATEGORIES, _get_builtin_metadata from .cityscapes import load_cityscapes_instances, load_cityscapes_semantic from .cityscapes_panoptic import register_all_cityscapes_panoptic from .coco import load_sem_seg, register_coco_instances from .coco_panoptic import register_coco_panoptic, register_coco_panoptic_separated from .lvis import get_lvis_instances_meta, register_lvis_instances from .pascal_voc import register_pascal_voc
9,656
instances_json, ) # ==== Predefined datasets and splits for LVIS ========== _PREDEFINED_SPLITS_LVIS = { "lvis_v1": { "lvis_v1_train": ("coco/", "lvis/lvis_v1_train.json"), "lvis_v1_val": ("coco/", "lvis/lvis_v1_val.json"), "lvis_v1_test_dev": ("coco/", "lvis/lvis_v1_image_info_test_dev.json"), "lvis_v1_test_challenge": ("coco/", "lvis/lvis_v1_image_info_test_challenge.json"), }, "lvis_v0.5": { "lvis_v0.5_train": ("coco/", "lvis/lvis_v0.5_train.json"), "lvis_v0.5_val": ("coco/", "lvis/lvis_v0.5_val.json"), "lvis_v0.5_val_rand_100": ("coco/", "lvis/lvis_v0.5_val_rand_100.json"), "lvis_v0.5_test": ("coco/", "lvis/lvis_v0.5_image_info_test.json"), }, "lvis_v0.5_cocofied": { "lvis_v0.5_train_cocofied": ("coco/", "lvis/lvis_v0.5_train_cocofied.json"), "lvis_v0.5_val_cocofied": ("coco/", "lvis/lvis_v0.5_val_cocofied.json"), }, } def register_all_lvis(root): for dataset_name, splits_per_dataset in _PREDEFINED_SPLITS_LVIS.items(): for key, (image_root, json_file) in splits_per_dataset.items(): register_lvis_instances( key, get_lvis_instances_meta(dataset_name), os.path.join(root, json_file) if "://" not in json_file else json_file, os.path.join(root, image_root), ) # ==== Predefined splits for raw cityscapes images =========== _RAW_CITYSCAPES_SPLITS = { "cityscapes_fine_{task}_train": ("cityscapes/leftImg8bit/train/", "cityscapes/gtFine/train/"), "cityscapes_fine_{task}_val": ("cityscapes/leftImg8bit/val/", "cityscapes/gtFine/val/"), "cityscapes_fine_{task}_test": ("cityscapes/leftImg8bit/test/", "cityscapes/gtFine/test/"), } def register_all_cityscapes(root): for key, (image_dir, gt_dir) in _RAW_CITYSCAPES_SPLITS.items(): meta = _get_builtin_metadata("cityscapes") image_dir = os.path.join(root, image_dir) gt_dir = os.path.join(root, gt_dir) inst_key = key.format(task="instance_seg") DatasetCatalog.register( inst_key, lambda x=image_dir, y=gt_dir: load_cityscapes_instances( x, y, from_json=True, to_polygons=True ), ) MetadataCatalog.get(inst_key).set( image_dir=image_dir, gt_dir=gt_dir, evaluator_type="cityscapes_instance", **meta ) sem_key = key.format(task="sem_seg") DatasetCatalog.register( sem_key, lambda x=image_dir, y=gt_dir: load_cityscapes_semantic(x, y) ) MetadataCatalog.get(sem_key).set( image_dir=image_dir, gt_dir=gt_dir, evaluator_type="cityscapes_sem_seg", ignore_label=255, **meta, ) # ==== Predefined splits for PASCAL VOC =========== def register_all_pascal_voc(root): SPLITS = [ ("voc_2007_trainval", "VOC2007", "trainval"), ("voc_2007_train", "VOC2007", "train"), ("voc_2007_val", "VOC2007", "val"), ("voc_2007_test", "VOC2007", "test"), ("voc_2012_trainval", "VOC2012", "trainval"), ("voc_2012_train", "VOC2012", "train"), ("voc_2012_val", "VOC2012", "val"), ] for name, dirname, split in SPLITS: year = 2007 if "2007" in name else 2012 register_pascal_voc(name, os.path.join(root, dirname), split, year) MetadataCatalog.get(name).evaluator_type = "pascal_voc" def register_all_ade20k(root): root = os.path.join(root, "ADEChallengeData2016") for name, dirname in [("train", "training"), ("val", "validation")]: image_dir = os.path.join(root, "images", dirname) gt_dir = os.path.join(root, "annotations_detectron2", dirname) name = f"ade20k_sem_seg_{name}" DatasetCatalog.register( name, lambda x=image_dir, y=gt_dir: load_sem_seg(y, x, gt_ext="png", image_ext="jpg") ) MetadataCatalog.get(name).set( stuff_classes=ADE20K_SEM_SEG_CATEGORIES[:], image_root=image_dir, sem_seg_root=gt_dir, evaluator_type="sem_seg", ignore_label=255, ) # True for open source; # Internally at fb, we register them elsewhere if __name__.endswith(".builtin"): # Assume pre-defined datasets live in `./datasets`. _root = "datasets" # _root = os.path.expanduser(os.getenv("DETECTRON2_DATASETS", "datasets")) register_all_coco(_root) register_all_lvis(_root) register_all_cityscapes(_root)
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. """ This file registers pre-defined datasets at hard-coded paths, and their metadata. We hard-code metadata for common datasets. This will enable: 1. Consistency check when loading the datasets 2. Use models on these standard datasets directly and run demos, without having to download the dataset annotations We hard-code some paths to the dataset that's assumed to exist in "./datasets/". Users SHOULD NOT use this file to create new dataset / metadata for new dataset. To add new dataset, refer to the tutorial "docs/DATASETS.md". """ # ==== Predefined datasets and splits for COCO ========== cluster_num = os.getenv('CLUSTER_NUM', '800') _PREDEFINED_SPLITS_COCO_SEMI = {} _PREDEFINED_SPLITS_COCO_SEMI["coco_semi"] = { # we use seed 42 to be consistent with previous works on SSL detection and segmentation "coco_semi_1perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/1perc_instances_train2017.json"), "coco_semi_2perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/2perc_instances_train2017.json"), "coco_semi_5perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/5perc_instances_train2017.json"), "coco_semi_10perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/10perc_instances_train2017.json"), "coco_semi_20perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/20perc_instances_train2017.json"), "coco_semi_30perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/30perc_instances_train2017.json"), "coco_semi_40perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/40perc_instances_train2017.json"), "coco_semi_50perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/50perc_instances_train2017.json"), } def register_all_coco_semi(root): for dataset_name, splits_per_dataset in _PREDEFINED_SPLITS_COCO_SEMI.items(): for key, (image_root, json_file) in splits_per_dataset.items(): # Assume pre-defined datasets live in `./datasets`. register_coco_instances( key, _get_builtin_metadata(dataset_name), os.path.join(root, json_file) if "://" not in json_file else json_file, os.path.join(root, image_root), ) _PREDEFINED_SPLITS_COCO = {} _PREDEFINED_SPLITS_COCO["coco"] = { "coco_2014_train": ("coco/train2014", "coco/annotations/instances_train2014.json"), "coco_2014_val": ("coco/val2014", "coco/annotations/instances_val2014.json"), "coco_2014_minival": ("coco/val2014", "coco/annotations/instances_minival2014.json"), "coco_2014_valminusminival": ( "coco/val2014", "coco/annotations/instances_valminusminival2014.json", ), "coco_2017_train": ("./coco/train2017", f"./prepare_ours/u2seg_annotations/ins_annotations/cocotrain_{cluster_num}.json"), "coco_2017_val": ("./coco/val2017", "./coco/annotations/instances_val2017.json"), "coco_2017_test": ("coco/test2017", "coco/annotations/image_info_test2017.json"), "coco_2017_test-dev": ("coco/test2017", "coco/annotations/image_info_test-dev2017.json"), "coco_2017_val_100": ("coco/val2017", "coco/annotations/instances_val2017_100.json"), } _PREDEFINED_SPLITS_COCO["coco_person"] = { "keypoints_coco_2014_train": ( "coco/train2014", "coco/annotations/person_keypoints_train2014.json", ), "keypoints_coco_2014_val": ("coco/val2014", "coco/annotations/person_keypoints_val2014.json"), "keypoints_coco_2014_minival": ( "coco/val2014", "coco/annotations/person_keypoints_minival2014.json", ), "keypoints_coco_2014_valminusminival": ( "coco/val2014", "coco/annotations/person_keypoints_valminusminival2014.json", ), "keypoints_coco_2017_train": ( "coco/train2017", "coco/annotations/person_keypoints_train2017.json", ), "keypoints_coco_2017_val": ("coco/val2017", "coco/annotations/person_keypoints_val2017.json"), "keypoints_coco_2017_val_100": ( "coco/val2017", "coco/annotations/person_keypoints_val2017_100.json", ), } _PREDEFINED_SPLITS_COCO_PANOPTIC = { "coco_2017_train_panoptic": ( # This is the original panoptic annotation directory f"./prepare_ours/u2seg_annotations/panoptic_annotations/cocotrain_{cluster_num}", # this should be .png format annotations f"./prepare_ours/u2seg_annotations/panoptic_annotations/cocotrain_{cluster_num}.json", #this should be .json file # This directory contains semantic annotations that are # converted from panoptic annotations. # It is used by PanopticFPN. # You can use the script at detectron2/datasets/prepare_panoptic_fpn.py # to create these directories. f"./prepare_ours/u2seg_annotations/panoptic_annotations/panoptic_stuff_cocotrain_{cluster_num}", ), "coco_2017_val_panoptic": ( "/home/niudt/u2seg_test/detectron2/datasets/datasets/coco/val2017", "/home/niudt/u2seg_test/detectron2/datasets/datasets/panoptic_anns/panoptic_val2017.json", "/home/niudt/u2seg_test/detectron2/datasets/datasets/panoptic_anns/panoptic_stuff_val2017", ), "coco_2017_val_100_panoptic": ( "coco/panoptic_val2017_100", "coco/annotations/panoptic_val2017_100.json", "coco/panoptic_stuff_val2017_100", ), } def register_all_coco(root): for dataset_name, splits_per_dataset in _PREDEFINED_SPLITS_COCO.items(): for key, (image_root, json_file) in splits_per_dataset.items(): # Assume pre-defined datasets live in `./datasets`. register_coco_instances( key, _get_builtin_metadata(dataset_name), os.path.join(root, json_file) if "://" not in json_file else json_file, os.path.join(root, image_root), ) for ( prefix, (panoptic_root, panoptic_json, semantic_root), ) in _PREDEFINED_SPLITS_COCO_PANOPTIC.items(): prefix_instances = prefix[: -len("_panoptic")] instances_meta = MetadataCatalog.get(prefix_instances) image_root, instances_json = instances_meta.image_root, instances_meta.json_file # The "separated" version of COCO panoptic segmentation dataset, # e.g. used by Panoptic FPN # import pdb # pdb.set_trace() register_coco_panoptic_separated( prefix, _get_builtin_metadata("coco_panoptic_separated"), image_root, os.path.join(root, panoptic_root), os.path.join(root, panoptic_json), os.path.join(root, semantic_root), instances_json, ) # The "standard" version of COCO panoptic segmentation dataset, # e.g. used by Panoptic-DeepLab register_coco_panoptic( prefix, _get_builtin_metadata("coco_panoptic_standard"), image_root, os.path.join(root, panoptic_root), os.path.join(root, panoptic_json), instances_json, ) # ==== Predefined datasets and splits for LVIS ========== _PREDEFINED_SPLITS_LVIS = { "lvis_v1": { "lvis_v1_train": ("coco/", "lvis/lvis_v1_train.json"), "lvis_v1_val": ("coco/", "lvis/lvis_v1_val.json"), "lvis_v1_test_dev": ("coco/", "lvis/lvis_v1_image_info_test_dev.json"), "lvis_v1_test_challenge": ("coco/", "lvis/lvis_v1_image_info_test_challenge.json"), }, "lvis_v0.5": { "lvis_v0.5_train": ("coco/", "lvis/lvis_v0.5_train.json"), "lvis_v0.5_val": ("coco/", "lvis/lvis_v0.5_val.json"), "lvis_v0.5_val_rand_100": ("coco/", "lvis/lvis_v0.5_val_rand_100.json"), "lvis_v0.5_test": ("coco/", "lvis/lvis_v0.5_image_info_test.json"), }, "lvis_v0.5_cocofied": { "lvis_v0.5_train_cocofied": ("coco/", "lvis/lvis_v0.5_train_cocofied.json"), "lvis_v0.5_val_cocofied": ("coco/", "lvis/lvis_v0.5_val_cocofied.json"), }, } def register_all_lvis(root): for dataset_name, splits_per_dataset in _PREDEFINED_SPLITS_LVIS.items(): for key, (image_root, json_file) in splits_per_dataset.items(): register_lvis_instances( key, get_lvis_instances_meta(dataset_name), os.path.join(root, json_file) if "://" not in json_file else json_file, os.path.join(root, image_root), ) # ==== Predefined splits for raw cityscapes images =========== _RAW_CITYSCAPES_SPLITS = { "cityscapes_fine_{task}_train": ("cityscapes/leftImg8bit/train/", "cityscapes/gtFine/train/"), "cityscapes_fine_{task}_val": ("cityscapes/leftImg8bit/val/", "cityscapes/gtFine/val/"), "cityscapes_fine_{task}_test": ("cityscapes/leftImg8bit/test/", "cityscapes/gtFine/test/"), } def register_all_cityscapes(root): for key, (image_dir, gt_dir) in _RAW_CITYSCAPES_SPLITS.items(): meta = _get_builtin_metadata("cityscapes") image_dir = os.path.join(root, image_dir) gt_dir = os.path.join(root, gt_dir) inst_key = key.format(task="instance_seg") DatasetCatalog.register( inst_key, lambda x=image_dir, y=gt_dir: load_cityscapes_instances( x, y, from_json=True, to_polygons=True ), ) MetadataCatalog.get(inst_key).set( image_dir=image_dir, gt_dir=gt_dir, evaluator_type="cityscapes_instance", **meta ) sem_key = key.format(task="sem_seg") DatasetCatalog.register( sem_key, lambda x=image_dir, y=gt_dir: load_cityscapes_semantic(x, y) ) MetadataCatalog.get(sem_key).set( image_dir=image_dir, gt_dir=gt_dir, evaluator_type="cityscapes_sem_seg", ignore_label=255, **meta, ) # ==== Predefined splits for PASCAL VOC =========== def register_all_pascal_voc(root): SPLITS = [ ("voc_2007_trainval", "VOC2007", "trainval"), ("voc_2007_train", "VOC2007", "train"), ("voc_2007_val", "VOC2007", "val"), ("voc_2007_test", "VOC2007", "test"), ("voc_2012_trainval", "VOC2012", "trainval"), ("voc_2012_train", "VOC2012", "train"), ("voc_2012_val", "VOC2012", "val"), ] for name, dirname, split in SPLITS: year = 2007 if "2007" in name else 2012 register_pascal_voc(name, os.path.join(root, dirname), split, year) MetadataCatalog.get(name).evaluator_type = "pascal_voc" def register_all_ade20k(root): root = os.path.join(root, "ADEChallengeData2016") for name, dirname in [("train", "training"), ("val", "validation")]: image_dir = os.path.join(root, "images", dirname) gt_dir = os.path.join(root, "annotations_detectron2", dirname) name = f"ade20k_sem_seg_{name}" DatasetCatalog.register( name, lambda x=image_dir, y=gt_dir: load_sem_seg(y, x, gt_ext="png", image_ext="jpg") ) MetadataCatalog.get(name).set( stuff_classes=ADE20K_SEM_SEG_CATEGORIES[:], image_root=image_dir, sem_seg_root=gt_dir, evaluator_type="sem_seg", ignore_label=255, ) # True for open source; # Internally at fb, we register them elsewhere if __name__.endswith(".builtin"): # Assume pre-defined datasets live in `./datasets`. _root = "datasets" # _root = os.path.expanduser(os.getenv("DETECTRON2_DATASETS", "datasets")) register_all_coco(_root) register_all_lvis(_root) register_all_cityscapes(_root)
register_all_cityscapes_panoptic(_root)
5
2023-12-05 01:13:31+00:00
12k
upfusion3d/upfusion
upsrt/model/model.py
[ { "identifier": "ResNetConv", "path": "upsrt/model/resnet.py", "snippet": "class ResNetConv(nn.Module):\n def __init__(self, n_blocks=3, use_feature_pyramid=False, num_patches_x=None, num_patches_y=None):\n super(ResNetConv, self).__init__()\n self.resnet = resnet18(pretrained=True)\n ...
import math import torch import torch.nn as nn from upsrt.model.resnet import ResNetConv from upsrt.model.transformer import ( TransformerEncoder, TransformerEncoderBlock, TransformerDecoder, TransformerDecoderBlock ) from upsrt.model.utils import plucker_dist, transform_rays from upsrt.renderer.rays import ( get_grid_rays, get_patch_rays, get_plucker_parameterization, get_random_query_pixel_rays, positional_encoding, get_grid_rays_gpu ) from pytorch3d.renderer.cameras import PerspectiveCameras from upsrt.utils.id_encoding import create_patch_id_encoding, create_camera_id_encoding
7,295
ATTN_TYPE = "xformers" class SceneEncoder(nn.Module): """ Takes set of patch-wise image and ray features as input and computes a set latent encoding for the scene """ def __init__(self, cfg): super(SceneEncoder, self).__init__() # Transformer architecture params self.transformer_dim = cfg.transformer_dim self.encoder_hidden_activation = 'gelu' self.encoder_n_attention_heads = 12 self.encoder_num_layers = cfg.num_encoder_layers self.transformer_encoder = TransformerEncoder( encoder_layer = TransformerEncoderBlock( attn_type=ATTN_TYPE, d_model=self.transformer_dim, nhead=self.encoder_n_attention_heads, activation=self.encoder_hidden_activation ), num_layers = self.encoder_num_layers ) def forward(self, scene_features): """ Args: scene_features: (b, n_inp, patch, transformer_dim) src_mask(torch.Tensor): FloatTensor (additive mask) of shape (b * n_heads, n_inp * patch, n_inp * patch) Returns: torch.Tensor: Tensor of shape (n_inp*patch, b, d_model) representing scene latent encoding """ b, n_inp, n_patch, _ = scene_features.shape encoder_input = torch.reshape(scene_features, (b, n_inp * n_patch, self.transformer_dim)) # (b, n_inp*patch, d_model) scene_encoding = self.transformer_encoder(encoder_input) # (b, n_inp*patch, d_model) return scene_encoding class RayDecoder(nn.Module): """ Decodes color value for each query pixel ray using a set latent encoding """ def __init__(self, cfg): super(RayDecoder, self).__init__() # Transformer architecture params self.transformer_dim = cfg.transformer_dim self.decoder_hidden_activation = 'gelu' self.decoder_n_attention_heads = 12 self.decoder_num_layers = cfg.num_decoder_layers self.transformer_decoder = TransformerDecoder(
ATTN_TYPE = "xformers" class SceneEncoder(nn.Module): """ Takes set of patch-wise image and ray features as input and computes a set latent encoding for the scene """ def __init__(self, cfg): super(SceneEncoder, self).__init__() # Transformer architecture params self.transformer_dim = cfg.transformer_dim self.encoder_hidden_activation = 'gelu' self.encoder_n_attention_heads = 12 self.encoder_num_layers = cfg.num_encoder_layers self.transformer_encoder = TransformerEncoder( encoder_layer = TransformerEncoderBlock( attn_type=ATTN_TYPE, d_model=self.transformer_dim, nhead=self.encoder_n_attention_heads, activation=self.encoder_hidden_activation ), num_layers = self.encoder_num_layers ) def forward(self, scene_features): """ Args: scene_features: (b, n_inp, patch, transformer_dim) src_mask(torch.Tensor): FloatTensor (additive mask) of shape (b * n_heads, n_inp * patch, n_inp * patch) Returns: torch.Tensor: Tensor of shape (n_inp*patch, b, d_model) representing scene latent encoding """ b, n_inp, n_patch, _ = scene_features.shape encoder_input = torch.reshape(scene_features, (b, n_inp * n_patch, self.transformer_dim)) # (b, n_inp*patch, d_model) scene_encoding = self.transformer_encoder(encoder_input) # (b, n_inp*patch, d_model) return scene_encoding class RayDecoder(nn.Module): """ Decodes color value for each query pixel ray using a set latent encoding """ def __init__(self, cfg): super(RayDecoder, self).__init__() # Transformer architecture params self.transformer_dim = cfg.transformer_dim self.decoder_hidden_activation = 'gelu' self.decoder_n_attention_heads = 12 self.decoder_num_layers = cfg.num_decoder_layers self.transformer_decoder = TransformerDecoder(
decoder_layer = TransformerDecoderBlock(
4
2023-12-12 00:49:11+00:00
12k
modelscope/normal-depth-diffusion
libs/omnidata_torch/lib/zoe/zoedepth/models/zoedepth/zoedepth_v1.py
[ { "identifier": "DepthModel", "path": "libs/omnidata_torch/lib/zoe/zoedepth/models/depth_model.py", "snippet": "class DepthModel(nn.Module):\n def __init__(self):\n super().__init__()\n self.device = 'cpu'\n \n def to(self, device) -> nn.Module:\n self.device = device\n ...
import itertools import torch import torch.nn as nn from ..depth_model import DepthModel from ..base_models.midas import MidasCore from ..layers.attractor import AttractorLayer, AttractorLayerUnnormed from ..layers.dist_layers import ConditionalLogBinomial from ..layers.localbins_layers import (Projector, SeedBinRegressor, SeedBinRegressorUnnormed) from ..model_io import load_state_from_resource
8,666
# MIT License # Copyright (c) 2022 Intelligent Systems Lab Org # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # File author: Shariq Farooq Bhat class ZoeDepth(DepthModel): def __init__(self, core, n_bins=64, bin_centers_type="softplus", bin_embedding_dim=128, min_depth=1e-3, max_depth=10, n_attractors=[16, 8, 4, 1], attractor_alpha=300, attractor_gamma=2, attractor_kind='sum', attractor_type='exp', min_temp=5, max_temp=50, train_midas=True, midas_lr_factor=10, encoder_lr_factor=10, pos_enc_lr_factor=10, inverse_midas=False, **kwargs): """ZoeDepth model. This is the version of ZoeDepth that has a single metric head Args: core (models.base_models.midas.MidasCore): The base midas model that is used for extraction of "relative" features n_bins (int, optional): Number of bin centers. Defaults to 64. bin_centers_type (str, optional): "normed" or "softplus". Activation type used for bin centers. For "normed" bin centers, linear normalization trick is applied. This results in bounded bin centers. For "softplus", softplus activation is used and thus are unbounded. Defaults to "softplus". bin_embedding_dim (int, optional): bin embedding dimension. Defaults to 128. min_depth (float, optional): Lower bound for normed bin centers. Defaults to 1e-3. max_depth (float, optional): Upper bound for normed bin centers. Defaults to 10. n_attractors (List[int], optional): Number of bin attractors at decoder layers. Defaults to [16, 8, 4, 1]. attractor_alpha (int, optional): Proportional attractor strength. Refer to models.layers.attractor for more details. Defaults to 300. attractor_gamma (int, optional): Exponential attractor strength. Refer to models.layers.attractor for more details. Defaults to 2. attractor_kind (str, optional): Attraction aggregation "sum" or "mean". Defaults to 'sum'. attractor_type (str, optional): Type of attractor to use; "inv" (Inverse attractor) or "exp" (Exponential attractor). Defaults to 'exp'. min_temp (int, optional): Lower bound for temperature of output probability distribution. Defaults to 5. max_temp (int, optional): Upper bound for temperature of output probability distribution. Defaults to 50. train_midas (bool, optional): Whether to train "core", the base midas model. Defaults to True. midas_lr_factor (int, optional): Learning rate reduction factor for base midas model except its encoder and positional encodings. Defaults to 10. encoder_lr_factor (int, optional): Learning rate reduction factor for the encoder in midas model. Defaults to 10. pos_enc_lr_factor (int, optional): Learning rate reduction factor for positional encodings in the base midas model. Defaults to 10. """ super().__init__() self.core = core self.max_depth = max_depth self.min_depth = min_depth self.min_temp = min_temp self.bin_centers_type = bin_centers_type self.midas_lr_factor = midas_lr_factor self.encoder_lr_factor = encoder_lr_factor self.pos_enc_lr_factor = pos_enc_lr_factor self.train_midas = train_midas self.inverse_midas = inverse_midas if self.encoder_lr_factor <= 0: self.core.freeze_encoder( freeze_rel_pos=self.pos_enc_lr_factor <= 0) N_MIDAS_OUT = 32 btlnck_features = self.core.output_channels[0] num_out_features = self.core.output_channels[1:] self.conv2 = nn.Conv2d(btlnck_features, btlnck_features, kernel_size=1, stride=1, padding=0) # btlnck conv if bin_centers_type == "normed": SeedBinRegressorLayer = SeedBinRegressor Attractor = AttractorLayer elif bin_centers_type == "softplus": SeedBinRegressorLayer = SeedBinRegressorUnnormed Attractor = AttractorLayerUnnormed elif bin_centers_type == "hybrid1": SeedBinRegressorLayer = SeedBinRegressor Attractor = AttractorLayerUnnormed elif bin_centers_type == "hybrid2": SeedBinRegressorLayer = SeedBinRegressorUnnormed Attractor = AttractorLayer else: raise ValueError( "bin_centers_type should be one of 'normed', 'softplus', 'hybrid1', 'hybrid2'") self.seed_bin_regressor = SeedBinRegressorLayer( btlnck_features, n_bins=n_bins, min_depth=min_depth, max_depth=max_depth) self.seed_projector = Projector(btlnck_features, bin_embedding_dim) self.projectors = nn.ModuleList([ Projector(num_out, bin_embedding_dim) for num_out in num_out_features ]) self.attractors = nn.ModuleList([ Attractor(bin_embedding_dim, n_bins, n_attractors=n_attractors[i], min_depth=min_depth, max_depth=max_depth, alpha=attractor_alpha, gamma=attractor_gamma, kind=attractor_kind, attractor_type=attractor_type) for i in range(len(num_out_features)) ]) last_in = N_MIDAS_OUT + 1 # +1 for relative depth # use log binomial instead of softmax
# MIT License # Copyright (c) 2022 Intelligent Systems Lab Org # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # File author: Shariq Farooq Bhat class ZoeDepth(DepthModel): def __init__(self, core, n_bins=64, bin_centers_type="softplus", bin_embedding_dim=128, min_depth=1e-3, max_depth=10, n_attractors=[16, 8, 4, 1], attractor_alpha=300, attractor_gamma=2, attractor_kind='sum', attractor_type='exp', min_temp=5, max_temp=50, train_midas=True, midas_lr_factor=10, encoder_lr_factor=10, pos_enc_lr_factor=10, inverse_midas=False, **kwargs): """ZoeDepth model. This is the version of ZoeDepth that has a single metric head Args: core (models.base_models.midas.MidasCore): The base midas model that is used for extraction of "relative" features n_bins (int, optional): Number of bin centers. Defaults to 64. bin_centers_type (str, optional): "normed" or "softplus". Activation type used for bin centers. For "normed" bin centers, linear normalization trick is applied. This results in bounded bin centers. For "softplus", softplus activation is used and thus are unbounded. Defaults to "softplus". bin_embedding_dim (int, optional): bin embedding dimension. Defaults to 128. min_depth (float, optional): Lower bound for normed bin centers. Defaults to 1e-3. max_depth (float, optional): Upper bound for normed bin centers. Defaults to 10. n_attractors (List[int], optional): Number of bin attractors at decoder layers. Defaults to [16, 8, 4, 1]. attractor_alpha (int, optional): Proportional attractor strength. Refer to models.layers.attractor for more details. Defaults to 300. attractor_gamma (int, optional): Exponential attractor strength. Refer to models.layers.attractor for more details. Defaults to 2. attractor_kind (str, optional): Attraction aggregation "sum" or "mean". Defaults to 'sum'. attractor_type (str, optional): Type of attractor to use; "inv" (Inverse attractor) or "exp" (Exponential attractor). Defaults to 'exp'. min_temp (int, optional): Lower bound for temperature of output probability distribution. Defaults to 5. max_temp (int, optional): Upper bound for temperature of output probability distribution. Defaults to 50. train_midas (bool, optional): Whether to train "core", the base midas model. Defaults to True. midas_lr_factor (int, optional): Learning rate reduction factor for base midas model except its encoder and positional encodings. Defaults to 10. encoder_lr_factor (int, optional): Learning rate reduction factor for the encoder in midas model. Defaults to 10. pos_enc_lr_factor (int, optional): Learning rate reduction factor for positional encodings in the base midas model. Defaults to 10. """ super().__init__() self.core = core self.max_depth = max_depth self.min_depth = min_depth self.min_temp = min_temp self.bin_centers_type = bin_centers_type self.midas_lr_factor = midas_lr_factor self.encoder_lr_factor = encoder_lr_factor self.pos_enc_lr_factor = pos_enc_lr_factor self.train_midas = train_midas self.inverse_midas = inverse_midas if self.encoder_lr_factor <= 0: self.core.freeze_encoder( freeze_rel_pos=self.pos_enc_lr_factor <= 0) N_MIDAS_OUT = 32 btlnck_features = self.core.output_channels[0] num_out_features = self.core.output_channels[1:] self.conv2 = nn.Conv2d(btlnck_features, btlnck_features, kernel_size=1, stride=1, padding=0) # btlnck conv if bin_centers_type == "normed": SeedBinRegressorLayer = SeedBinRegressor Attractor = AttractorLayer elif bin_centers_type == "softplus": SeedBinRegressorLayer = SeedBinRegressorUnnormed Attractor = AttractorLayerUnnormed elif bin_centers_type == "hybrid1": SeedBinRegressorLayer = SeedBinRegressor Attractor = AttractorLayerUnnormed elif bin_centers_type == "hybrid2": SeedBinRegressorLayer = SeedBinRegressorUnnormed Attractor = AttractorLayer else: raise ValueError( "bin_centers_type should be one of 'normed', 'softplus', 'hybrid1', 'hybrid2'") self.seed_bin_regressor = SeedBinRegressorLayer( btlnck_features, n_bins=n_bins, min_depth=min_depth, max_depth=max_depth) self.seed_projector = Projector(btlnck_features, bin_embedding_dim) self.projectors = nn.ModuleList([ Projector(num_out, bin_embedding_dim) for num_out in num_out_features ]) self.attractors = nn.ModuleList([ Attractor(bin_embedding_dim, n_bins, n_attractors=n_attractors[i], min_depth=min_depth, max_depth=max_depth, alpha=attractor_alpha, gamma=attractor_gamma, kind=attractor_kind, attractor_type=attractor_type) for i in range(len(num_out_features)) ]) last_in = N_MIDAS_OUT + 1 # +1 for relative depth # use log binomial instead of softmax
self.conditional_log_binomial = ConditionalLogBinomial(
4
2023-12-06 07:29:34+00:00
12k
FrozenBurning/PrimDiffusion
visualize.py
[ { "identifier": "RayMarcher", "path": "dva/ray_marcher.py", "snippet": "class RayMarcher(nn.Module):\n def __init__(\n self,\n image_height,\n image_width,\n volradius,\n fadescale=8.0,\n fadeexp=8.0,\n dt=1.0,\n ray_subsample_factor=1,\n ...
import os import sys import imageio import torch as th import numpy as np import random import logging from omegaconf import OmegaConf from dva.ray_marcher import RayMarcher, generate_colored_boxes from primdiffusion.dataset.renderpeople_crossid_dataset import RenderPeopleSViewDataset from dva.io import load_static_assets_crossid_smpl, load_from_config from dva.utils import to_device from dva.geom import make_postex, compute_tbn
7,799
) return preds_boxes["rgba_image"][:, :3].permute(0, 2, 3, 1) def set_random_seed(seed): r"""Set random seeds for everything. Args: seed (int): Random seed. by_rank (bool): """ print(f"Using random seed {seed}") random.seed(seed) np.random.seed(seed) th.manual_seed(seed) th.cuda.manual_seed(seed) th.cuda.manual_seed_all(seed) def to_video_out(input): ndarr = input[0].mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", th.uint8).numpy() return ndarr def main(config): use_ddim = config.ddim device = th.device("cuda:0") th.cuda.set_device(device) static_assets = load_static_assets_crossid_smpl(config) inference_output_dir = f"{config.output_dir}/primdiffusion_interm_visualization" checkpoint_path = config.checkpoint_path os.makedirs(inference_output_dir, exist_ok=True) video_path = os.path.join(inference_output_dir, 'videos') os.makedirs(video_path, exist_ok=True) OmegaConf.save(config, os.path.join(inference_output_dir, "config.yml")) logger.info(f"saving results to {inference_output_dir}") logger.info(f"starting inference with the config: {OmegaConf.to_yaml(config)}") model = load_from_config( config.model, assets=static_assets, ) print('loading checkpoint {}'.format(checkpoint_path)) state_dict = th.load(checkpoint_path, map_location='cpu') model.load_state_dict(state_dict['model_state_dict']) model = model.to(device) model.device = device model.eval() # computing values for the given viewpoints rm = RayMarcher( config.image_height, config.image_width, **config.rm, ).to(device) dataset = RenderPeopleSViewDataset( **config.data, cameras=config.cameras_train, cond_cameras=config.cameras_cond, sample_cameras=False, is_train=False, camera_id='00', ) sample_num = 1 seed_list = [1007,] dataset.gen_inf_cameras(num_views=5) for iter in range(1000): logger.info('Rendering iteration-{:04d}......'.format(iter)) set_random_seed(iter) batch = dataset.sample_cam_smpl() batch = to_device(batch, device) if use_ddim: log_every_t = 1 samples, z_denoise_row = model.sample_log(cond=None, batch_size = sample_num, ddim=True, ddim_steps=100, eta=0.0, log_every_t=log_every_t) z_denoise_row = z_denoise_row['x_inter'] else: log_every_t = 10 samples, z_denoise_row = model.sample_log(cond=None, batch_size = sample_num, ddim=False, ddim_steps=None, eta=0.0, log_every_t=log_every_t) samples = (samples / model.scaling_factor + 1) / 2. * 255. denoise_row = (th.stack(z_denoise_row) / model.scaling_factor + 1) / 2. * 255 prim_size = config.model.bodydecoder_config.prim_size n_prims_x = n_prims_y = int(config.model.bodydecoder_config.n_prims ** 0.5) # plot denoising row denoise_row = denoise_row.reshape(-1, sample_num, prim_size, 7, n_prims_y, prim_size, n_prims_x, prim_size).permute(0, 1, 4, 6, 3, 2, 5, 7).reshape(-1, sample_num, n_prims_y * n_prims_x, 7, prim_size, prim_size, prim_size) denoise_sample_deltascale = th.mean(denoise_row[:, :, :, 4:], dim=(-1, -2, -3)) / 255. * 20. denoise_sample_rgba = denoise_row[:, :, :, :4, :, :, :] num_steps = denoise_row.shape[0] for i in range(sample_num): batch = dataset.sample_cam_smpl() sam_cam = {} sam_cam.update(dataset.inf_cameras[dataset.subject_ids[0]]['camera0000']) for k, v in sam_cam.items(): if isinstance(v, np.ndarray): sam_cam[k] = v[None, ...] batch.update(sam_cam) batch = to_device(batch, device) B = 1 geom = model.bodydecoder.lbs_fn( poses = batch["poses"], shapes = batch["shapes"], Rh = batch["Rh"], Th = batch["Th"], v_template = model.bodydecoder.lbs_fn.v_template[np.newaxis], ) * 1000.0 prim_pos_mesh = ( make_postex(geom, model.bodydecoder.prim_vidx_img, model.bodydecoder.prim_bary_img) .permute(0, 2, 3, 1) .reshape(-1, model.bodydecoder.n_prims, 3) .detach() ) prim_scale_mesh = ( model.bodydecoder.prim_scale[np.newaxis, :, np.newaxis].expand(B, -1, 3).detach().clone() )
device = th.device("cuda") logger = logging.getLogger("visualize.py") def render_mvp_boxes(rm, batch, preds): with th.no_grad(): boxes_rgba = generate_colored_boxes( preds["prim_rgba"], preds["prim_rot"], ) preds_boxes = rm( prim_rgba=boxes_rgba, prim_pos=preds["prim_pos"], prim_scale=preds["prim_scale"], prim_rot=preds["prim_rot"], RT=batch["Rt"], K=batch["K"], ) return preds_boxes["rgba_image"][:, :3].permute(0, 2, 3, 1) def set_random_seed(seed): r"""Set random seeds for everything. Args: seed (int): Random seed. by_rank (bool): """ print(f"Using random seed {seed}") random.seed(seed) np.random.seed(seed) th.manual_seed(seed) th.cuda.manual_seed(seed) th.cuda.manual_seed_all(seed) def to_video_out(input): ndarr = input[0].mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", th.uint8).numpy() return ndarr def main(config): use_ddim = config.ddim device = th.device("cuda:0") th.cuda.set_device(device) static_assets = load_static_assets_crossid_smpl(config) inference_output_dir = f"{config.output_dir}/primdiffusion_interm_visualization" checkpoint_path = config.checkpoint_path os.makedirs(inference_output_dir, exist_ok=True) video_path = os.path.join(inference_output_dir, 'videos') os.makedirs(video_path, exist_ok=True) OmegaConf.save(config, os.path.join(inference_output_dir, "config.yml")) logger.info(f"saving results to {inference_output_dir}") logger.info(f"starting inference with the config: {OmegaConf.to_yaml(config)}") model = load_from_config( config.model, assets=static_assets, ) print('loading checkpoint {}'.format(checkpoint_path)) state_dict = th.load(checkpoint_path, map_location='cpu') model.load_state_dict(state_dict['model_state_dict']) model = model.to(device) model.device = device model.eval() # computing values for the given viewpoints rm = RayMarcher( config.image_height, config.image_width, **config.rm, ).to(device) dataset = RenderPeopleSViewDataset( **config.data, cameras=config.cameras_train, cond_cameras=config.cameras_cond, sample_cameras=False, is_train=False, camera_id='00', ) sample_num = 1 seed_list = [1007,] dataset.gen_inf_cameras(num_views=5) for iter in range(1000): logger.info('Rendering iteration-{:04d}......'.format(iter)) set_random_seed(iter) batch = dataset.sample_cam_smpl() batch = to_device(batch, device) if use_ddim: log_every_t = 1 samples, z_denoise_row = model.sample_log(cond=None, batch_size = sample_num, ddim=True, ddim_steps=100, eta=0.0, log_every_t=log_every_t) z_denoise_row = z_denoise_row['x_inter'] else: log_every_t = 10 samples, z_denoise_row = model.sample_log(cond=None, batch_size = sample_num, ddim=False, ddim_steps=None, eta=0.0, log_every_t=log_every_t) samples = (samples / model.scaling_factor + 1) / 2. * 255. denoise_row = (th.stack(z_denoise_row) / model.scaling_factor + 1) / 2. * 255 prim_size = config.model.bodydecoder_config.prim_size n_prims_x = n_prims_y = int(config.model.bodydecoder_config.n_prims ** 0.5) # plot denoising row denoise_row = denoise_row.reshape(-1, sample_num, prim_size, 7, n_prims_y, prim_size, n_prims_x, prim_size).permute(0, 1, 4, 6, 3, 2, 5, 7).reshape(-1, sample_num, n_prims_y * n_prims_x, 7, prim_size, prim_size, prim_size) denoise_sample_deltascale = th.mean(denoise_row[:, :, :, 4:], dim=(-1, -2, -3)) / 255. * 20. denoise_sample_rgba = denoise_row[:, :, :, :4, :, :, :] num_steps = denoise_row.shape[0] for i in range(sample_num): batch = dataset.sample_cam_smpl() sam_cam = {} sam_cam.update(dataset.inf_cameras[dataset.subject_ids[0]]['camera0000']) for k, v in sam_cam.items(): if isinstance(v, np.ndarray): sam_cam[k] = v[None, ...] batch.update(sam_cam) batch = to_device(batch, device) B = 1 geom = model.bodydecoder.lbs_fn( poses = batch["poses"], shapes = batch["shapes"], Rh = batch["Rh"], Th = batch["Th"], v_template = model.bodydecoder.lbs_fn.v_template[np.newaxis], ) * 1000.0 prim_pos_mesh = ( make_postex(geom, model.bodydecoder.prim_vidx_img, model.bodydecoder.prim_bary_img) .permute(0, 2, 3, 1) .reshape(-1, model.bodydecoder.n_prims, 3) .detach() ) prim_scale_mesh = ( model.bodydecoder.prim_scale[np.newaxis, :, np.newaxis].expand(B, -1, 3).detach().clone() )
tbn = compute_tbn(geom, model.bodydecoder.geo_fn.vt, model.bodydecoder.prim_vidx_img, model.bodydecoder.prim_vtidx_img)
7
2023-12-06 05:12:55+00:00
12k
ml-stat-Sustech/TorchCP
tests/test_classification.py
[ { "identifier": "ClassWisePredictor", "path": "torchcp/classification/predictors/classwise.py", "snippet": "class ClassWisePredictor(SplitPredictor):\n \"\"\"\n\n Applications of Class-Conditional Conformal Predictor in Multi-Class Classification (Shi et al., 2013)\n paper: https://ieeexplore.i...
import argparse import os import pickle import torch import torchvision import torchvision.datasets as dset import torchvision.transforms as trn from tqdm import tqdm from torchcp.classification.predictors import SplitPredictor, ClusterPredictor, ClassWisePredictor from torchcp.classification.scores import THR, APS, SAPS, RAPS, Margin from torchcp.classification.utils.metrics import Metrics from torchcp.utils import fix_randomness
7,327
# Copyright (c) 2023-present, SUSTech-ML. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # transform = trn.Compose([trn.Resize(256), trn.CenterCrop(224), trn.ToTensor(), trn.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) def test_imagenet_logits(): ####################################### # Loading ImageNet dataset and a pytorch model ####################################### fix_randomness(seed=0) model_name = 'ResNet101' fname = ".cache/" + model_name + ".pkl" if os.path.exists(fname): with open(fname, 'rb') as handle: dataset = pickle.load(handle) else: usr_dir = os.path.expanduser('~') data_dir = os.path.join(usr_dir, "data") dataset = dset.ImageFolder(data_dir + "/imagenet/val", transform) data_loader = torch.utils.data.DataLoader(dataset, batch_size=320, shuffle=False, pin_memory=True) # load model model = torchvision.models.resnet101(weights="IMAGENET1K_V1", progress=True) logits_list = [] labels_list = [] with torch.no_grad(): for examples in tqdm(data_loader): tmp_x, tmp_label = examples[0], examples[1] tmp_logits = model(tmp_x) logits_list.append(tmp_logits) labels_list.append(tmp_label) logits = torch.cat(logits_list) labels = torch.cat(labels_list) dataset = torch.utils.data.TensorDataset(logits, labels.long()) with open(fname, 'wb') as handle: pickle.dump(dataset, handle, protocol=pickle.HIGHEST_PROTOCOL) cal_data, val_data = torch.utils.data.random_split(dataset, [25000, 25000]) cal_logits = torch.stack([sample[0] for sample in cal_data]) cal_labels = torch.stack([sample[1] for sample in cal_data]) test_logits = torch.stack([sample[0] for sample in val_data]) test_labels = torch.stack([sample[1] for sample in val_data]) num_classes = 1000 ####################################### # A standard process of conformal prediction ####################################### alpha = 0.1 predictors = [SplitPredictor, ClassWisePredictor, ClusterPredictor]
# Copyright (c) 2023-present, SUSTech-ML. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # transform = trn.Compose([trn.Resize(256), trn.CenterCrop(224), trn.ToTensor(), trn.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) def test_imagenet_logits(): ####################################### # Loading ImageNet dataset and a pytorch model ####################################### fix_randomness(seed=0) model_name = 'ResNet101' fname = ".cache/" + model_name + ".pkl" if os.path.exists(fname): with open(fname, 'rb') as handle: dataset = pickle.load(handle) else: usr_dir = os.path.expanduser('~') data_dir = os.path.join(usr_dir, "data") dataset = dset.ImageFolder(data_dir + "/imagenet/val", transform) data_loader = torch.utils.data.DataLoader(dataset, batch_size=320, shuffle=False, pin_memory=True) # load model model = torchvision.models.resnet101(weights="IMAGENET1K_V1", progress=True) logits_list = [] labels_list = [] with torch.no_grad(): for examples in tqdm(data_loader): tmp_x, tmp_label = examples[0], examples[1] tmp_logits = model(tmp_x) logits_list.append(tmp_logits) labels_list.append(tmp_label) logits = torch.cat(logits_list) labels = torch.cat(labels_list) dataset = torch.utils.data.TensorDataset(logits, labels.long()) with open(fname, 'wb') as handle: pickle.dump(dataset, handle, protocol=pickle.HIGHEST_PROTOCOL) cal_data, val_data = torch.utils.data.random_split(dataset, [25000, 25000]) cal_logits = torch.stack([sample[0] for sample in cal_data]) cal_labels = torch.stack([sample[1] for sample in cal_data]) test_logits = torch.stack([sample[0] for sample in val_data]) test_labels = torch.stack([sample[1] for sample in val_data]) num_classes = 1000 ####################################### # A standard process of conformal prediction ####################################### alpha = 0.1 predictors = [SplitPredictor, ClassWisePredictor, ClusterPredictor]
score_functions = [THR(), APS(), RAPS(1, 0), SAPS(0.2), Margin()]
7
2023-12-06 09:08:41+00:00
12k
OpenDriveLab/LaneSegNet
projects/lanesegnet/models/modules/bevformer_constructer.py
[ { "identifier": "BEV_CONSTRUCTOR", "path": "projects/lanesegnet/utils/builder.py", "snippet": "BEV_CONSTRUCTOR = Registry('BEV Constructor')" }, { "identifier": "TemporalSelfAttention", "path": "projects/bevformer/modules/temporal_self_attention.py", "snippet": "class TemporalSelfAttenti...
import numpy as np import torch import torch.nn as nn from torch.nn.init import normal_ from torchvision.transforms.functional import rotate from mmcv.cnn import xavier_init from mmcv.cnn.bricks.transformer import build_transformer_layer_sequence, build_positional_encoding from mmcv.runner.base_module import BaseModule from ...utils.builder import BEV_CONSTRUCTOR from projects.bevformer.modules.temporal_self_attention import TemporalSelfAttention from projects.bevformer.modules.spatial_cross_attention import MSDeformableAttention3D from projects.bevformer.modules.decoder import CustomMSDeformableAttention
8,461
#---------------------------------------------------------------------------------------# # LaneSegNet: Map Learning with Lane Segment Perception for Autonomous Driving # # Source code: https://github.com/OpenDriveLab/LaneSegNet # # Copyright (c) OpenDriveLab. All rights reserved. # #---------------------------------------------------------------------------------------# @BEV_CONSTRUCTOR.register_module() class BEVFormerConstructer(BaseModule): """Implements the BEVFormer BEV Constructer. Args: as_two_stage (bool): Generate query from encoder features. Default: False. num_feature_levels (int): Number of feature maps from FPN: Default: 4. two_stage_num_proposals (int): Number of proposals when set `as_two_stage` as True. Default: 300. """ def __init__(self, num_feature_levels=4, num_cams=6, embed_dims=256, rotate_prev_bev=True, use_shift=True, use_can_bus=True, can_bus_norm=True, use_cams_embeds=True, pc_range=[-51.2, -51.2, -5.0, 51.2, 51.2, 3.0], bev_h=200, bev_w=200, rotate_center=[100, 100], encoder=None, positional_encoding=None, **kwargs): super(BEVFormerConstructer, self).__init__(**kwargs) self.embed_dims = embed_dims self.num_feature_levels = num_feature_levels self.num_cams = num_cams self.fp16_enabled = False self.rotate_prev_bev = rotate_prev_bev self.use_shift = use_shift self.use_can_bus = use_can_bus self.can_bus_norm = can_bus_norm self.use_cams_embeds = use_cams_embeds self.encoder = build_transformer_layer_sequence(encoder) self.positional_encoding = build_positional_encoding(positional_encoding) self.pc_range = pc_range self.real_w = self.pc_range[3] - self.pc_range[0] self.real_h = self.pc_range[4] - self.pc_range[1] self.bev_h = bev_h self.bev_w = bev_w self.rotate_center = rotate_center self.init_layers() def init_layers(self): self.bev_embedding = nn.Embedding( self.bev_h * self.bev_w, self.embed_dims) self.level_embeds = nn.Parameter(torch.Tensor( self.num_feature_levels, self.embed_dims)) self.cams_embeds = nn.Parameter( torch.Tensor(self.num_cams, self.embed_dims)) self.can_bus_mlp = nn.Sequential( nn.Linear(18, self.embed_dims // 2), nn.ReLU(inplace=True), nn.Linear(self.embed_dims // 2, self.embed_dims), nn.ReLU(inplace=True), ) if self.can_bus_norm: self.can_bus_mlp.add_module('norm', nn.LayerNorm(self.embed_dims)) def init_weights(self): """Initialize the transformer weights.""" for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) for m in self.modules(): if isinstance(m, MSDeformableAttention3D) or isinstance(m, TemporalSelfAttention) \
#---------------------------------------------------------------------------------------# # LaneSegNet: Map Learning with Lane Segment Perception for Autonomous Driving # # Source code: https://github.com/OpenDriveLab/LaneSegNet # # Copyright (c) OpenDriveLab. All rights reserved. # #---------------------------------------------------------------------------------------# @BEV_CONSTRUCTOR.register_module() class BEVFormerConstructer(BaseModule): """Implements the BEVFormer BEV Constructer. Args: as_two_stage (bool): Generate query from encoder features. Default: False. num_feature_levels (int): Number of feature maps from FPN: Default: 4. two_stage_num_proposals (int): Number of proposals when set `as_two_stage` as True. Default: 300. """ def __init__(self, num_feature_levels=4, num_cams=6, embed_dims=256, rotate_prev_bev=True, use_shift=True, use_can_bus=True, can_bus_norm=True, use_cams_embeds=True, pc_range=[-51.2, -51.2, -5.0, 51.2, 51.2, 3.0], bev_h=200, bev_w=200, rotate_center=[100, 100], encoder=None, positional_encoding=None, **kwargs): super(BEVFormerConstructer, self).__init__(**kwargs) self.embed_dims = embed_dims self.num_feature_levels = num_feature_levels self.num_cams = num_cams self.fp16_enabled = False self.rotate_prev_bev = rotate_prev_bev self.use_shift = use_shift self.use_can_bus = use_can_bus self.can_bus_norm = can_bus_norm self.use_cams_embeds = use_cams_embeds self.encoder = build_transformer_layer_sequence(encoder) self.positional_encoding = build_positional_encoding(positional_encoding) self.pc_range = pc_range self.real_w = self.pc_range[3] - self.pc_range[0] self.real_h = self.pc_range[4] - self.pc_range[1] self.bev_h = bev_h self.bev_w = bev_w self.rotate_center = rotate_center self.init_layers() def init_layers(self): self.bev_embedding = nn.Embedding( self.bev_h * self.bev_w, self.embed_dims) self.level_embeds = nn.Parameter(torch.Tensor( self.num_feature_levels, self.embed_dims)) self.cams_embeds = nn.Parameter( torch.Tensor(self.num_cams, self.embed_dims)) self.can_bus_mlp = nn.Sequential( nn.Linear(18, self.embed_dims // 2), nn.ReLU(inplace=True), nn.Linear(self.embed_dims // 2, self.embed_dims), nn.ReLU(inplace=True), ) if self.can_bus_norm: self.can_bus_mlp.add_module('norm', nn.LayerNorm(self.embed_dims)) def init_weights(self): """Initialize the transformer weights.""" for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) for m in self.modules(): if isinstance(m, MSDeformableAttention3D) or isinstance(m, TemporalSelfAttention) \
or isinstance(m, CustomMSDeformableAttention):
3
2023-12-06 07:13:48+00:00
12k
RobertCsordas/moe_attention
tasks/simple/language_model/enwik8_transformer.py
[ { "identifier": "TransformerLanguageModel", "path": "models/transformer_language_model.py", "snippet": "class TransformerLanguageModel(LoggingLayer, torch.nn.Module):\n def __init__(self, voc_size: int, embedding_size: Optional[int], state_size: int, dropout: float,\n tied_embedding: ...
import framework import torch import torch.nn import torch.utils.data import dataset import random from models import TransformerLanguageModel from ... import task, args from .transformer_lm_mixin import TransformerLMMixin from ..simple_task import SimpleTask from typing import Tuple, Any, Dict, List, Union from interfaces import LanguageModelInterface
9,940
@args def a(parser: framework.helpers.ArgumentParser): parser.add_argument("-lm.state_drop_probability", default=0.0) parser.add_argument("-lm.lstm_weight_drop", default=0.0) parser.add_argument("-lm.unroll", default=100) parser.add_argument("-lm.unroll_eval", default="none", parser=parser.int_or_none_parser) parser.add_argument("-lm.example_context", default=100) parser.add_argument("-lm.example_window", default=40) @task()
@args def a(parser: framework.helpers.ArgumentParser): parser.add_argument("-lm.state_drop_probability", default=0.0) parser.add_argument("-lm.lstm_weight_drop", default=0.0) parser.add_argument("-lm.unroll", default=100) parser.add_argument("-lm.unroll_eval", default="none", parser=parser.int_or_none_parser) parser.add_argument("-lm.example_context", default=100) parser.add_argument("-lm.example_window", default=40) @task()
class Enwik8Transformer(TransformerLMMixin, SimpleTask):
3
2023-12-13 08:45:02+00:00
12k
Q-Future/Q-Align
q_align/model/modeling_mplug_owl2.py
[ { "identifier": "MPLUGOwl2Config", "path": "q_align/model/configuration_mplug_owl2.py", "snippet": "class MPLUGOwl2Config(LlamaConfig):\n model_type = \"mplug_owl2\"\n def __init__(self, visual_config=None, **kwargs):\n if visual_config is None:\n self.visual_config = DEFAULT_VIS...
from abc import ABC, abstractmethod from typing import List, Optional, Tuple, Union from torch.nn import CrossEntropyLoss from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, CLIPImageProcessor, LlamaConfig, LlamaModel, LlamaForCausalLM from transformers.modeling_outputs import CausalLMOutputWithPast from .configuration_mplug_owl2 import MPLUGOwl2Config, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig from .visual_encoder import MplugOwlVisionModel, MplugOwlVisualAbstractorModel from .modeling_llama2 import replace_llama_modality_adaptive from icecream import ic from PIL import Image from icecream import ic import torch import torch.nn as nn import copy import os import sys
7,952
# Initialize weights and apply final processing self.post_init() def get_model(self): return self.model def score(self, images, task_: str = "quality", input_: str = "image", ): if not hasattr(self, "weight_tensor"): self.weight_tensor = torch.Tensor([5.,4.,3.,2.,1.]).half().to(self.device) prompt = "USER: How would you rate the {} of this {}?\n<|image|>\nASSISTANT: The {} of the {} is".format(task_, input_, input_, task_) if input_ == "image": images = [expand2square(img, tuple(int(x*255) for x in self.image_processor.image_mean)) for img in images] input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device) with torch.inference_mode(): image_tensor = self.image_processor.preprocess(images, return_tensors="pt")["pixel_values"].half().to(self.device) output_logits = self(input_ids.repeat(image_tensor.shape[0], 1), images=image_tensor)["logits"][:,-1, self.preferential_ids_] return torch.softmax(output_logits, -1) @ self.weight_tensor else: video = [[expand2square(frame, tuple(int(x*255) for x in self.image_processor.image_mean)) for frame in vid] for vid in images] input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device) with torch.inference_mode(): video_tensors = [self.image_processor.preprocess(vid, return_tensors="pt")["pixel_values"].half().to(self.model.device) for vid in video] output_logits = self(input_ids.repeat(len(video_tensors), 1), images=video_tensors)["logits"][:,-1, self.preferential_ids_] return torch.softmax(output_logits, -1) @ self.weight_tensor def forward( self, input_ids: torch.LongTensor = None, # modality_indicators: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, images: Optional[torch.FloatTensor] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, CausalLMOutputWithPast]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict input_ids, modality_indicators, attention_mask, past_key_values, inputs_embeds, labels = \ self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images) # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, modality_indicators=modality_indicators, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict ) hidden_states = outputs[0] logits = self.lm_head(hidden_states) loss = None if labels is not None: # Shift so that tokens < n predict n shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens loss_fct = CrossEntropyLoss() shift_logits = shift_logits.view(-1, self.config.vocab_size) shift_labels = shift_labels.view(-1) # Enable model/pipeline parallelism shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels) if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs ): if past_key_values: input_ids = input_ids[:, -1:] # if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and past_key_values is None: model_inputs = {"inputs_embeds": inputs_embeds} else: model_inputs = {"input_ids": input_ids} model_inputs.update( { "past_key_values": past_key_values, "use_cache": kwargs.get("use_cache"), "attention_mask": attention_mask, "images": kwargs.get("images", None), } ) return model_inputs AutoConfig.register("mplug_owl2", MPLUGOwl2Config) AutoModelForCausalLM.register(MPLUGOwl2Config, MPLUGOwl2LlamaForCausalLM)
# Copyright 2023 Haotian Liu & Qinghao Ye (Modified from LLaVA) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. dir_path = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, dir_path) IGNORE_INDEX = -100 IMAGE_TOKEN_INDEX = -200 DEFAULT_IMAGE_TOKEN = "<|image|>" def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None): prompt_chunks = [tokenizer(chunk).input_ids if len(chunk) > 0 else [] for chunk in prompt.split(DEFAULT_IMAGE_TOKEN)] def insert_separator(X, sep): return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1] input_ids = [] offset = 0 if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id: offset = 1 input_ids.append(prompt_chunks[0][0]) for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)): input_ids.extend(x[offset:]) if return_tensors is not None: if return_tensors == 'pt': return torch.tensor(input_ids, dtype=torch.long) raise ValueError(f'Unsupported tensor type: {return_tensors}') return input_ids def expand2square(pil_img, background_color): width, height = pil_img.size if width == height: return pil_img elif width > height: result = Image.new(pil_img.mode, (width, width), background_color) result.paste(pil_img, (0, (width - height) // 2)) return result else: result = Image.new(pil_img.mode, (height, height), background_color) result.paste(pil_img, ((height - width) // 2, 0)) return result class MPLUGOwl2MetaModel: def __init__(self, config): super(MPLUGOwl2MetaModel, self).__init__(config) self.vision_model = MplugOwlVisionModel( MplugOwlVisionConfig(**config.visual_config["visual_model"]) ) self.visual_abstractor = MplugOwlVisualAbstractorModel( MplugOwlVisualAbstractorConfig(**config.visual_config["visual_abstractor"]), config.hidden_size ) def get_vision_tower(self): vision_model = getattr(self, 'vision_model', None) if type(vision_model) is list: vision_model = vision_model[0] return vision_model def get_visual_abstractor(self): visual_abstractor = getattr(self, 'visual_abstractor', None) if type(visual_abstractor) is list: visual_abstractor = visual_abstractor[0] return visual_abstractor class MPLUGOwl2MetaForCausalLM(ABC): @abstractmethod def get_model(self): pass def encode_images(self, images): image_features = self.get_model().vision_model(images).last_hidden_state image_features = self.get_model().visual_abstractor(encoder_hidden_states=image_features).last_hidden_state return image_features def prepare_inputs_labels_for_multimodal( self, input_ids, attention_mask, past_key_values, labels, images ): if images is None or input_ids.shape[1] == 1: if past_key_values is not None and images is not None and input_ids.shape[1] == 1: attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device) multiway_indices = torch.zeros_like(input_ids).long().to(self.device) return input_ids, multiway_indices, attention_mask, past_key_values, None, labels if type(images) is list or images.ndim == 5: concat_images = torch.cat([image for image in images], dim=0) image_features = self.encode_images(concat_images) split_sizes = [image.shape[0] for image in images] image_features = torch.split(image_features, split_sizes, dim=0) image_features = [x.flatten(0, 1) for x in image_features] else: image_features = self.encode_images(images) new_input_embeds = [] new_modality_indicators = [] new_labels = [] if labels is not None else None cur_image_idx = 0 for batch_idx, cur_input_ids in enumerate(input_ids): if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0: # multimodal LLM, but the current sample is not multimodal # FIXME: this is a hacky fix, for deepspeed zero3 to work half_len = cur_input_ids.shape[0] // 2 cur_image_features = image_features[cur_image_idx] cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len]) cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:]) cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0], cur_input_embeds_2], dim=0) new_input_embeds.append(cur_input_embeds) cur_modality_indicators = torch.zeros(len(cur_input_embeds)).long().to(self.device) new_modality_indicators.append(cur_modality_indicators) if labels is not None: new_labels.append(labels[batch_idx]) cur_image_idx += 1 continue image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0] cur_new_input_embeds = [] cur_modality_indicators = [] if labels is not None: cur_labels = labels[batch_idx] cur_new_labels = [] assert cur_labels.shape == cur_input_ids.shape while image_token_indices.numel() > 0: cur_image_features = image_features[cur_image_idx] image_token_start = image_token_indices[0] cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start])) cur_new_input_embeds.append(cur_image_features) # Add modality indicator assert image_token_start == len(cur_input_ids[:image_token_start]) cur_modality_indicators.append(torch.zeros(len(cur_input_ids[:image_token_start])).long()) cur_modality_indicators.append(torch.ones(len(cur_image_features)).long()) if labels is not None: cur_new_labels.append(cur_labels[:image_token_start]) cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype)) cur_labels = cur_labels[image_token_start+1:] cur_image_idx += 1 cur_input_ids = cur_input_ids[image_token_start+1:] image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0] if cur_input_ids.numel() > 0: cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids)) cur_modality_indicators.append(torch.zeros(len(cur_input_ids)).long()) if labels is not None: cur_new_labels.append(cur_labels) cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds] cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0) new_input_embeds.append(cur_new_input_embeds) # Modality cur_modality_indicators = [x.to(device=self.device) for x in cur_modality_indicators] cur_modality_indicators = torch.cat(cur_modality_indicators, dim=0) new_modality_indicators.append(cur_modality_indicators) if labels is not None: cur_new_labels = torch.cat(cur_new_labels, dim=0) new_labels.append(cur_new_labels) if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds): max_len = max(x.shape[0] for x in new_input_embeds) # Embedding new_input_embeds_align = [] for cur_new_embed in new_input_embeds: cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0) new_input_embeds_align.append(cur_new_embed) new_input_embeds = torch.stack(new_input_embeds_align, dim=0) # Modality new_modality_indicators_align = [] for cur_modality_indicator in new_modality_indicators: cur_new_embed = torch.cat((cur_modality_indicator, torch.zeros(max_len - cur_modality_indicator.shape[0], dtype=cur_modality_indicator.dtype, device=cur_modality_indicator.device)), dim=0) new_modality_indicators_align.append(cur_new_embed) new_modality_indicators = torch.stack(new_modality_indicators_align, dim=0) # Label if labels is not None: new_labels_align = [] _new_labels = new_labels for cur_new_label in new_labels: cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0) new_labels_align.append(cur_new_label) new_labels = torch.stack(new_labels_align, dim=0) # Attention Mask if attention_mask is not None: new_attention_mask = [] for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels): new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device) new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device) cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0) new_attention_mask.append(cur_new_attention_mask) attention_mask = torch.stack(new_attention_mask, dim=0) assert attention_mask.shape == new_labels.shape else: new_input_embeds = torch.stack(new_input_embeds, dim=0) new_modality_indicators = torch.stack(new_modality_indicators, dim=0) if labels is not None: new_labels = torch.stack(new_labels, dim=0) if attention_mask is not None: new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device) attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1) assert attention_mask.shape == new_input_embeds.shape[:2] return None, new_modality_indicators, attention_mask, past_key_values, new_input_embeds, new_labels class MPLUGOwl2LlamaModel(MPLUGOwl2MetaModel, LlamaModel): config_class = MPLUGOwl2Config def __init__(self, config: MPLUGOwl2Config): super(MPLUGOwl2LlamaModel, self).__init__(config) class MPLUGOwl2LlamaForCausalLM(LlamaForCausalLM, MPLUGOwl2MetaForCausalLM): config_class = MPLUGOwl2Config def __init__(self, config): super(LlamaForCausalLM, self).__init__(config) self.model = MPLUGOwl2LlamaModel(config) self.tokenizer = AutoTokenizer.from_pretrained("q-future/one-align") self.image_processor = CLIPImageProcessor.from_pretrained("q-future/one-align") self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.preferential_ids_ = [id_[1] for id_ in self.tokenizer(["excellent","good","fair","poor","bad"])["input_ids"]] # Initialize weights and apply final processing self.post_init() def get_model(self): return self.model def score(self, images, task_: str = "quality", input_: str = "image", ): if not hasattr(self, "weight_tensor"): self.weight_tensor = torch.Tensor([5.,4.,3.,2.,1.]).half().to(self.device) prompt = "USER: How would you rate the {} of this {}?\n<|image|>\nASSISTANT: The {} of the {} is".format(task_, input_, input_, task_) if input_ == "image": images = [expand2square(img, tuple(int(x*255) for x in self.image_processor.image_mean)) for img in images] input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device) with torch.inference_mode(): image_tensor = self.image_processor.preprocess(images, return_tensors="pt")["pixel_values"].half().to(self.device) output_logits = self(input_ids.repeat(image_tensor.shape[0], 1), images=image_tensor)["logits"][:,-1, self.preferential_ids_] return torch.softmax(output_logits, -1) @ self.weight_tensor else: video = [[expand2square(frame, tuple(int(x*255) for x in self.image_processor.image_mean)) for frame in vid] for vid in images] input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device) with torch.inference_mode(): video_tensors = [self.image_processor.preprocess(vid, return_tensors="pt")["pixel_values"].half().to(self.model.device) for vid in video] output_logits = self(input_ids.repeat(len(video_tensors), 1), images=video_tensors)["logits"][:,-1, self.preferential_ids_] return torch.softmax(output_logits, -1) @ self.weight_tensor def forward( self, input_ids: torch.LongTensor = None, # modality_indicators: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, images: Optional[torch.FloatTensor] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, CausalLMOutputWithPast]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict input_ids, modality_indicators, attention_mask, past_key_values, inputs_embeds, labels = \ self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images) # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, modality_indicators=modality_indicators, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict ) hidden_states = outputs[0] logits = self.lm_head(hidden_states) loss = None if labels is not None: # Shift so that tokens < n predict n shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens loss_fct = CrossEntropyLoss() shift_logits = shift_logits.view(-1, self.config.vocab_size) shift_labels = shift_labels.view(-1) # Enable model/pipeline parallelism shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels) if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs ): if past_key_values: input_ids = input_ids[:, -1:] # if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and past_key_values is None: model_inputs = {"inputs_embeds": inputs_embeds} else: model_inputs = {"input_ids": input_ids} model_inputs.update( { "past_key_values": past_key_values, "use_cache": kwargs.get("use_cache"), "attention_mask": attention_mask, "images": kwargs.get("images", None), } ) return model_inputs AutoConfig.register("mplug_owl2", MPLUGOwl2Config) AutoModelForCausalLM.register(MPLUGOwl2Config, MPLUGOwl2LlamaForCausalLM)
replace_llama_modality_adaptive()
5
2023-12-14 03:36:30+00:00
12k
nox-410/tvm.tl
python/tvm/topi/hexagon/qnn/avg_pool2d.py
[ { "identifier": "get_layout_transform_fn", "path": "python/tvm/topi/hexagon/utils.py", "snippet": "def get_layout_transform_fn(layout):\n \"\"\"Return index map function as per the layout string\"\"\"\n if layout == \"nhwc-8h2w32c2w-2d\":\n return nhwc_8h2w32c2w_2d\n if layout == \"nhwc-...
import tvm from tvm import te from tvm import tir from ..utils import ( get_layout_transform_fn, get_fixed_point_value, is_scalar, get_const_int_value, get_const_float_value, ) from ...utils import get_const_tuple from ...nn.utils import get_pad_tuple from ...nn.pad import pad from ..compute_poolarea import compute_PoolArea
8,643
def qnn_avg_pool2d_NHWC( data: te.Tensor, kernel: list, stride: list, padding: list, dilation: list, count_include_pad: bool, oshape: list, odtype: str, # quantization params: input_scale: float, input_zero_point: int, output_scale: float, output_zero_point: int, ): """Compute for quantized avg_pool2d""" kh, kw = kernel rh = te.reduce_axis((0, kh), name="rh") rw = te.reduce_axis((0, kw), name="rw") temp_dtype = get_temp_dtype(kh, kw, odtype) sh, sw = stride dh, dw = dilation scale = input_scale / output_scale scale_fixed_point, rsh = get_fixed_point_value(scale, "int16") corr = (output_zero_point << rsh) - input_zero_point * scale_fixed_point dilated_kh = (kh - 1) * dh + 1 dilated_kw = (kw - 1) * dw + 1 # Compute Area pad_top, pad_left, pad_down, pad_right = get_pad_tuple( get_const_tuple(padding), (dilated_kh, dilated_kw) ) # DOPAD if pad_top != 0 or pad_down != 0 or pad_left != 0 or pad_right != 0: pad_before = (0, pad_top, pad_left, 0) pad_after = (0, pad_down, pad_right, 0) data_pad = pad(data, pad_before, pad_after, pad_value=input_zero_point, name="data_pad") else: # By definition when True, zero-padding will be included in the averaging calculation # This is equivalent to PoolArea = (kh * kw) count_include_pad = True data_pad = data Sum = te.compute( oshape, lambda b, h, w, c: te.sum( data_pad[b, h * sh + dh * rh, w * sw + dw * rw, c].astype(temp_dtype), axis=[rh, rw] ), name="pool_sum", ) if not count_include_pad: # Compute PoolArea using unpadded input tensor _, oh, ow, _ = oshape _, ih, iw, _ = data.shape PoolArea = te.compute( (oh, ow), lambda i, j: compute_PoolArea(i, j, ih, iw, kh, kw, sh, sw, dh, dw, pad_top, pad_left), name="pool_area", ) ScaleWithArea = te.compute( (oh, ow), lambda i, j: tir.if_then_else( tir.all(PoolArea[i, j] > 0), (scale_fixed_point // PoolArea[i, j]).astype("int32"), 0, ), name="scale_with_area", ) Avg = te.compute( oshape, lambda b, h, w, c: saturate( ((Sum[b, h, w, c] * ScaleWithArea[h, w]) + corr + (1 << (rsh - 1))) >> rsh, odtype ).astype(odtype), name="pool_avg", ) else: ScaleWithArea = scale_fixed_point // (kh * kw) Avg = te.compute( oshape, lambda b, h, w, c: saturate( ((Sum[b, h, w, c] * ScaleWithArea) + corr + (1 << (rsh - 1))) >> rsh, odtype ).astype(odtype), name="pool_avg", ) return Avg def qnn_avg_pool2d_wrapper_compute_NCHW( data: te.Tensor, kernel: list, stride: list, padding: list, dilation: list, count_include_pad: bool, oshape: list, odtype: str, # quantization params: input_scale: float, input_zero_point: int, output_scale: float, output_zero_point: int, ): """Extract qnn params""" if ( is_scalar(input_scale) and is_scalar(output_scale) and is_scalar(input_zero_point) and is_scalar(output_zero_point) ):
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, unused-argument, too-many-locals """ Compute and schedule for quantized avg_pool2d op """ def saturate(x: te.Tensor, dtype: str): """Saturate value for the specified data type""" return te.max(te.min_value(dtype), te.min(x, te.max_value(dtype))) def get_temp_dtype(h, w, dtype): temp_dtype = "int16" if h * w < 256 else "int32" if dtype in ("uint8", "int8"): return temp_dtype else: raise RuntimeError(f"Unsupported output dtype, {odtype}'") def qnn_avg_pool2d_NCHW( data: te.Tensor, kernel: list, stride: list, padding: list, dilation: list, count_include_pad: bool, oshape: list, odtype: str, # quantization params: input_scale: float, input_zero_point: int, output_scale: float, output_zero_point: int, ): """Compute for quantized avg_pool2d""" kh, kw = kernel rh = te.reduce_axis((0, kh), name="rh") rw = te.reduce_axis((0, kw), name="rw") temp_dtype = get_temp_dtype(kh, kw, odtype) sh, sw = stride dh, dw = dilation scale = input_scale / output_scale scale_fixed_point, rsh = get_fixed_point_value(scale, "int16") corr = (output_zero_point << rsh) - input_zero_point * scale_fixed_point dilated_kh = (kh - 1) * dh + 1 dilated_kw = (kw - 1) * dw + 1 pad_top, pad_left, pad_down, pad_right = get_pad_tuple( get_const_tuple(padding), (dilated_kh, dilated_kw) ) # DOPAD if pad_top != 0 or pad_down != 0 or pad_left != 0 or pad_right != 0: pad_before = (0, 0, pad_top, pad_left) pad_after = (0, 0, pad_down, pad_right) data_pad = pad(data, pad_before, pad_after, pad_value=input_zero_point, name="data_pad") else: # By definition when True, zero-padding will be included in the averaging calculation # This is equivalent to PoolArea = (kh * kw) count_include_pad = True data_pad = data Sum = te.compute( oshape, lambda b, c, h, w: te.sum( data_pad[b, c, h * sh + dh * rh, w * sw + dw * rw].astype(temp_dtype), axis=[rh, rw] ), name="pool_sum", ) if not count_include_pad: # Compute PoolArea using unpadded input tensor _, _, oh, ow = oshape _, _, ih, iw = data.shape PoolArea = te.compute( (oh, ow), lambda i, j: compute_PoolArea(i, j, ih, iw, kh, kw, sh, sw, dh, dw, pad_top, pad_left), name="pool_area", ) ScaleWithArea = te.compute( (oh, ow), lambda i, j: (scale_fixed_point // PoolArea[i, j]).astype("int32"), name="scale_with_area", ) Avg = te.compute( oshape, lambda b, c, h, w: saturate( ((Sum[b, c, h, w] * ScaleWithArea[h, w]) + corr + (1 << (rsh - 1))) >> rsh, odtype ).astype(odtype), name="pool_avg", ) else: ScaleWithArea = scale_fixed_point // (kh * kw) Avg = te.compute( oshape, lambda b, c, h, w: saturate( ((Sum[b, c, h, w] * ScaleWithArea) + corr + (1 << (rsh - 1))) >> rsh, odtype ).astype(odtype), name="pool_avg", ) return Avg def qnn_avg_pool2d_NHWC( data: te.Tensor, kernel: list, stride: list, padding: list, dilation: list, count_include_pad: bool, oshape: list, odtype: str, # quantization params: input_scale: float, input_zero_point: int, output_scale: float, output_zero_point: int, ): """Compute for quantized avg_pool2d""" kh, kw = kernel rh = te.reduce_axis((0, kh), name="rh") rw = te.reduce_axis((0, kw), name="rw") temp_dtype = get_temp_dtype(kh, kw, odtype) sh, sw = stride dh, dw = dilation scale = input_scale / output_scale scale_fixed_point, rsh = get_fixed_point_value(scale, "int16") corr = (output_zero_point << rsh) - input_zero_point * scale_fixed_point dilated_kh = (kh - 1) * dh + 1 dilated_kw = (kw - 1) * dw + 1 # Compute Area pad_top, pad_left, pad_down, pad_right = get_pad_tuple( get_const_tuple(padding), (dilated_kh, dilated_kw) ) # DOPAD if pad_top != 0 or pad_down != 0 or pad_left != 0 or pad_right != 0: pad_before = (0, pad_top, pad_left, 0) pad_after = (0, pad_down, pad_right, 0) data_pad = pad(data, pad_before, pad_after, pad_value=input_zero_point, name="data_pad") else: # By definition when True, zero-padding will be included in the averaging calculation # This is equivalent to PoolArea = (kh * kw) count_include_pad = True data_pad = data Sum = te.compute( oshape, lambda b, h, w, c: te.sum( data_pad[b, h * sh + dh * rh, w * sw + dw * rw, c].astype(temp_dtype), axis=[rh, rw] ), name="pool_sum", ) if not count_include_pad: # Compute PoolArea using unpadded input tensor _, oh, ow, _ = oshape _, ih, iw, _ = data.shape PoolArea = te.compute( (oh, ow), lambda i, j: compute_PoolArea(i, j, ih, iw, kh, kw, sh, sw, dh, dw, pad_top, pad_left), name="pool_area", ) ScaleWithArea = te.compute( (oh, ow), lambda i, j: tir.if_then_else( tir.all(PoolArea[i, j] > 0), (scale_fixed_point // PoolArea[i, j]).astype("int32"), 0, ), name="scale_with_area", ) Avg = te.compute( oshape, lambda b, h, w, c: saturate( ((Sum[b, h, w, c] * ScaleWithArea[h, w]) + corr + (1 << (rsh - 1))) >> rsh, odtype ).astype(odtype), name="pool_avg", ) else: ScaleWithArea = scale_fixed_point // (kh * kw) Avg = te.compute( oshape, lambda b, h, w, c: saturate( ((Sum[b, h, w, c] * ScaleWithArea) + corr + (1 << (rsh - 1))) >> rsh, odtype ).astype(odtype), name="pool_avg", ) return Avg def qnn_avg_pool2d_wrapper_compute_NCHW( data: te.Tensor, kernel: list, stride: list, padding: list, dilation: list, count_include_pad: bool, oshape: list, odtype: str, # quantization params: input_scale: float, input_zero_point: int, output_scale: float, output_zero_point: int, ): """Extract qnn params""" if ( is_scalar(input_scale) and is_scalar(output_scale) and is_scalar(input_zero_point) and is_scalar(output_zero_point) ):
iscale = get_const_float_value(input_scale)
4
2023-12-14 02:37:47+00:00
12k
yolain/ComfyUI-Easy-Use
py/easyNodes.py
[ { "identifier": "advanced_encode", "path": "py/adv_encode.py", "snippet": "def advanced_encode(clip, text, token_normalization, weight_interpretation, w_max=1.0, clip_balance=.5,\n apply_to_pooled=True):\n tokenized = clip.tokenize(text, return_word_ids=True)\n if isinstance(cli...
import sys import os import re import json import time import math import torch import psutil import random import datetime import comfy.sd import comfy.utils import numpy as np import folder_paths import comfy.samplers import comfy.controlnet import latent_preview import comfy.model_base import comfy.model_management from pathlib import Path from comfy.sd import CLIP, VAE from comfy.cli_args import args from urllib.request import urlopen from collections import defaultdict from PIL.PngImagePlugin import PngInfo from PIL import Image, ImageDraw, ImageFont from comfy.model_patcher import ModelPatcher from comfy_extras.chainner_models import model_loading from typing import Dict, List, Optional, Tuple, Union, Any from .adv_encode import advanced_encode, advanced_encode_XL from server import PromptServer from nodes import VAELoader, MAX_RESOLUTION, RepeatLatentBatch, NODE_CLASS_MAPPINGS as ALL_NODE_CLASS_MAPPINGS, ConditioningSetMask from comfy_extras.nodes_mask import LatentCompositeMasked from .config import BASE_RESOLUTIONS from .log import log_node_info, log_node_error, log_node_warn, log_node_success from .wildcards import process_with_loras, get_wildcard_list from comfy_extras.nodes_stable3d import camera_embeddings from .gradual_latent_hires_fix import sample_dpmpp_2s_ancestral, sample_dpmpp_2m_sde, sample_lcm, sample_euler_ancestral from .dynthres_core import DynThresh
10,499
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID"}, } RETURN_TYPES = ("PIPE_LINE", ) RETURN_NAMES = ("pipe",) OUTPUT_NODE = True FUNCTION = "settings" CATEGORY = "EasyUse/PreSampling" def settings(self, pipe, steps, cfg, sampler_name, scheduler, start_at_step, end_at_step, add_noise, seed_num, image_to_latent=None, latent=None, prompt=None, extra_pnginfo=None, my_unique_id=None): # if my_unique_id: # workflow = extra_pnginfo["workflow"] # node = next((x for x in workflow["nodes"] if str(x["id"]) == my_unique_id), None) # if node: # seed_num = prompt[my_unique_id]['inputs']['seed_num'] if 'seed_num' in prompt[my_unique_id][ # 'inputs'] else 0 # length = len(node["widgets_values"]) # node["widgets_values"][length - 2] = seed_num # 图生图转换 vae = pipe["vae"] batch_size = pipe["loader_settings"]["batch_size"] if "batch_size" in pipe["loader_settings"] else 1 if image_to_latent is not None: samples = {"samples": vae.encode(image_to_latent)} samples = RepeatLatentBatch().repeat(samples, batch_size)[0] images = image_to_latent elif latent is not None: samples = RepeatLatentBatch().repeat(latent, batch_size)[0] images = pipe["images"] else: samples = pipe["samples"] images = pipe["images"] new_pipe = { "model": pipe['model'], "positive": pipe['positive'], "negative": pipe['negative'], "vae": pipe['vae'], "clip": pipe['clip'], "samples": samples, "images": images, "seed": seed_num, "loader_settings": { **pipe["loader_settings"], "steps": steps, "cfg": cfg, "sampler_name": sampler_name, "scheduler": scheduler, "start_step": start_at_step, "last_step": end_at_step, "denoise": 1.0, "add_noise": add_noise } } del pipe return {"ui": {"value": [seed_num]}, "result": (new_pipe,)} # 预采样设置(SDTurbo) class sdTurboSettings: def __init__(self): pass @classmethod def INPUT_TYPES(cls): return {"required": { "pipe": ("PIPE_LINE",), "steps": ("INT", {"default": 1, "min": 1, "max": 10}), "cfg": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0}), "sampler_name": (comfy.samplers.SAMPLER_NAMES,), "eta": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01, "round": False}), "s_noise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01, "round": False}), "upscale_ratio": ("FLOAT", {"default": 2.0, "min": 0.0, "max": 16.0, "step": 0.01, "round": False}), "start_step": ("INT", {"default": 5, "min": 0, "max": 1000, "step": 1}), "end_step": ("INT", {"default": 15, "min": 0, "max": 1000, "step": 1}), "upscale_n_step": ("INT", {"default": 3, "min": 0, "max": 1000, "step": 1}), "unsharp_kernel_size": ("INT", {"default": 3, "min": 1, "max": 21, "step": 1}), "unsharp_sigma": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 10.0, "step": 0.01, "round": False}), "unsharp_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.01, "round": False}), "seed_num": ("INT", {"default": 0, "min": 0, "max": 1125899906842624}), }, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID"}, } RETURN_TYPES = ("PIPE_LINE",) RETURN_NAMES = ("pipe",) OUTPUT_NODE = True FUNCTION = "settings" CATEGORY = "EasyUse/PreSampling" def settings(self, pipe, steps, cfg, sampler_name, eta, s_noise, upscale_ratio, start_step, end_step, upscale_n_step, unsharp_kernel_size, unsharp_sigma, unsharp_strength, seed_num, prompt=None, extra_pnginfo=None, my_unique_id=None): model = pipe['model'] # sigma timesteps = torch.flip(torch.arange(1, 11) * 100 - 1, (0,))[:steps] sigmas = model.model.model_sampling.sigma(timesteps) sigmas = torch.cat([sigmas, sigmas.new_zeros([1])]) #sampler sample_function = None extra_options = { "eta": eta, "s_noise": s_noise, "upscale_ratio": upscale_ratio, "start_step": start_step, "end_step": end_step, "upscale_n_step": upscale_n_step, "unsharp_kernel_size": unsharp_kernel_size, "unsharp_sigma": unsharp_sigma, "unsharp_strength": unsharp_strength, } if sampler_name == "euler_ancestral": sample_function = sample_euler_ancestral elif sampler_name == "dpmpp_2s_ancestral":
# 加载器 class easyLoader: def __init__(self): self.loaded_objects = { "ckpt": defaultdict(tuple), # {ckpt_name: (model, ...)} "clip": defaultdict(tuple), "clip_vision": defaultdict(tuple), "bvae": defaultdict(tuple), "vae": defaultdict(object), "lora": defaultdict(dict), # {lora_name: {UID: (model_lora, clip_lora)}} } self.memory_threshold = self.determine_memory_threshold(0.7) def clean_values(self, values: str): original_values = values.split("; ") cleaned_values = [] for value in original_values: cleaned_value = value.strip(';').strip() if cleaned_value == "": continue try: cleaned_value = int(cleaned_value) except ValueError: try: cleaned_value = float(cleaned_value) except ValueError: pass cleaned_values.append(cleaned_value) return cleaned_values def clear_unused_objects(self, desired_names: set, object_type: str): keys = set(self.loaded_objects[object_type].keys()) for key in keys - desired_names: del self.loaded_objects[object_type][key] def get_input_value(self, entry, key): val = entry["inputs"][key] return val if isinstance(val, str) else val[0] def process_pipe_loader(self, entry, desired_ckpt_names, desired_vae_names, desired_lora_names, desired_lora_settings, num_loras=3, suffix=""): for idx in range(1, num_loras + 1): lora_name_key = f"{suffix}lora{idx}_name" desired_lora_names.add(self.get_input_value(entry, lora_name_key)) setting = f'{self.get_input_value(entry, lora_name_key)};{entry["inputs"][f"{suffix}lora{idx}_model_strength"]};{entry["inputs"][f"{suffix}lora{idx}_clip_strength"]}' desired_lora_settings.add(setting) desired_ckpt_names.add(self.get_input_value(entry, f"{suffix}ckpt_name")) desired_vae_names.add(self.get_input_value(entry, f"{suffix}vae_name")) def update_loaded_objects(self, prompt): desired_ckpt_names = set() desired_vae_names = set() desired_lora_names = set() desired_lora_settings = set() for entry in prompt.values(): class_type = entry["class_type"] if class_type == "easy a1111Loader" or class_type == "easy comfyLoader": lora_name = self.get_input_value(entry, "lora_name") desired_lora_names.add(lora_name) setting = f'{lora_name};{entry["inputs"]["lora_model_strength"]};{entry["inputs"]["lora_clip_strength"]}' desired_lora_settings.add(setting) desired_ckpt_names.add(self.get_input_value(entry, "ckpt_name")) desired_vae_names.add(self.get_input_value(entry, "vae_name")) elif class_type == "easy zero123Loader" or class_type == 'easy svdLoader': desired_ckpt_names.add(self.get_input_value(entry, "ckpt_name")) desired_vae_names.add(self.get_input_value(entry, "vae_name")) elif class_type == "easy XYInputs: ModelMergeBlocks": desired_ckpt_names.add(self.get_input_value(entry, "ckpt_name_1")) desired_ckpt_names.add(self.get_input_value(entry, "ckpt_name_2")) vae_use = self.get_input_value(entry, "vae_use") if vae_use != 'Use Model 1' and vae_use != 'Use Model 2': desired_vae_names.add(vae_use) object_types = ["ckpt", "clip", "bvae", "vae", "lora"] for object_type in object_types: desired_names = desired_ckpt_names if object_type in ["ckpt", "clip", "bvae"] else desired_vae_names if object_type == "vae" else desired_lora_names self.clear_unused_objects(desired_names, object_type) def add_to_cache(self, obj_type, key, value): """ Add an item to the cache with the current timestamp. """ timestamped_value = (value, time.time()) self.loaded_objects[obj_type][key] = timestamped_value def determine_memory_threshold(self, percentage=0.8): """ Determines the memory threshold as a percentage of the total available memory. Args: - percentage (float): The fraction of total memory to use as the threshold. Should be a value between 0 and 1. Default is 0.8 (80%). Returns: - memory_threshold (int): Memory threshold in bytes. """ total_memory = psutil.virtual_memory().total memory_threshold = total_memory * percentage return memory_threshold def get_memory_usage(self): """ Returns the memory usage of the current process in bytes. """ process = psutil.Process(os.getpid()) return process.memory_info().rss def eviction_based_on_memory(self): """ Evicts objects from cache based on memory usage and priority. """ current_memory = self.get_memory_usage() if current_memory < self.memory_threshold: return eviction_order = ["vae", "lora", "bvae", "clip", "ckpt"] for obj_type in eviction_order: if current_memory < self.memory_threshold: break # Sort items based on age (using the timestamp) items = list(self.loaded_objects[obj_type].items()) items.sort(key=lambda x: x[1][1]) # Sorting by timestamp for item in items: if current_memory < self.memory_threshold: break del self.loaded_objects[obj_type][item[0]] current_memory = self.get_memory_usage() def load_checkpoint(self, ckpt_name, config_name=None, load_vision=False): cache_name = ckpt_name if config_name not in [None, "Default"]: cache_name = ckpt_name + "_" + config_name if cache_name in self.loaded_objects["ckpt"]: cache_out = self.loaded_objects["clip_vision"][cache_name][0] if load_vision else self.loaded_objects["clip"][cache_name][0] return self.loaded_objects["ckpt"][cache_name][0], cache_out, self.loaded_objects["bvae"][cache_name][0] ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name) output_clip = False if load_vision else True output_clipvision = True if load_vision else False if config_name not in [None, "Default"]: config_path = folder_paths.get_full_path("configs", config_name) loaded_ckpt = comfy.sd.load_checkpoint(config_path, ckpt_path, output_vae=True, output_clip=output_clip, output_clipvision=output_clipvision, embedding_directory=folder_paths.get_folder_paths("embeddings")) else: loaded_ckpt = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=output_clip, output_clipvision=output_clipvision, embedding_directory=folder_paths.get_folder_paths("embeddings")) self.add_to_cache("ckpt", cache_name, loaded_ckpt[0]) self.add_to_cache("bvae", cache_name, loaded_ckpt[2]) if load_vision: out = loaded_ckpt[3] self.add_to_cache("clip_vision", cache_name, out) else: out = loaded_ckpt[1] self.add_to_cache("clip", cache_name, loaded_ckpt[1]) self.eviction_based_on_memory() return loaded_ckpt[0], out, loaded_ckpt[2] def load_vae(self, vae_name): if vae_name in self.loaded_objects["vae"]: return self.loaded_objects["vae"][vae_name][0] vae_path = folder_paths.get_full_path("vae", vae_name) sd = comfy.utils.load_torch_file(vae_path) loaded_vae = comfy.sd.VAE(sd=sd) self.add_to_cache("vae", vae_name, loaded_vae) self.eviction_based_on_memory() return loaded_vae def load_lora(self, lora_name, model, clip, strength_model, strength_clip): model_hash = str(model)[44:-1] clip_hash = str(clip)[25:-1] unique_id = f'{model_hash};{clip_hash};{lora_name};{strength_model};{strength_clip}' if unique_id in self.loaded_objects["lora"] and unique_id in self.loaded_objects["lora"][lora_name]: return self.loaded_objects["lora"][unique_id][0] lora_path = folder_paths.get_full_path("loras", lora_name) lora = comfy.utils.load_torch_file(lora_path, safe_load=True) model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora, strength_model, strength_clip) self.add_to_cache("lora", unique_id, (model_lora, clip_lora)) self.eviction_based_on_memory() return model_lora, clip_lora # 采样器 class easySampler: def __init__(self): self.last_helds: dict[str, list] = { "results": [], "pipe_line": [], } @staticmethod def tensor2pil(image: torch.Tensor) -> Image.Image: """Convert a torch tensor to a PIL image.""" return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) @staticmethod def pil2tensor(image: Image.Image) -> torch.Tensor: """Convert a PIL image to a torch tensor.""" return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0) @staticmethod def enforce_mul_of_64(d): d = int(d) if d <= 7: d = 8 leftover = d % 8 # 8 is the number of pixels per byte if leftover != 0: # if the number of pixels is not a multiple of 8 if (leftover < 4): # if the number of pixels is less than 4 d -= leftover # remove the leftover pixels else: # if the number of pixels is more than 4 d += 8 - leftover # add the leftover pixels return int(d) @staticmethod def safe_split(to_split: str, delimiter: str) -> List[str]: """Split the input string and return a list of non-empty parts.""" parts = to_split.split(delimiter) parts = [part for part in parts if part not in ('', ' ', ' ')] while len(parts) < 2: parts.append('None') return parts def common_ksampler(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent, denoise=1.0, disable_noise=False, start_step=None, last_step=None, force_full_denoise=False, preview_latent=True, disable_pbar=False): device = comfy.model_management.get_torch_device() latent_image = latent["samples"] if disable_noise: noise = torch.zeros(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, device="cpu") else: batch_inds = latent["batch_index"] if "batch_index" in latent else None noise = comfy.sample.prepare_noise(latent_image, seed, batch_inds) noise_mask = None if "noise_mask" in latent: noise_mask = latent["noise_mask"] preview_format = "JPEG" if preview_format not in ["JPEG", "PNG"]: preview_format = "JPEG" previewer = False if preview_latent: previewer = latent_preview.get_previewer(device, model.model.latent_format) pbar = comfy.utils.ProgressBar(steps) def callback(step, x0, x, total_steps): preview_bytes = None if previewer: preview_bytes = previewer.decode_latent_to_preview_image(preview_format, x0) pbar.update_absolute(step + 1, total_steps, preview_bytes) samples = comfy.sample.sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise, disable_noise=disable_noise, start_step=start_step, last_step=last_step, force_full_denoise=force_full_denoise, noise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed) out = latent.copy() out["samples"] = samples return out def custom_ksampler(self, model, seed, steps, cfg, _sampler, sigmas, positive, negative, latent, disable_noise=False, preview_latent=True, disable_pbar=False): device = comfy.model_management.get_torch_device() latent_image = latent["samples"] if disable_noise: noise = torch.zeros(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, device="cpu") else: batch_inds = latent["batch_index"] if "batch_index" in latent else None noise = comfy.sample.prepare_noise(latent_image, seed, batch_inds) noise_mask = None if "noise_mask" in latent: noise_mask = latent["noise_mask"] preview_format = "JPEG" if preview_format not in ["JPEG", "PNG"]: preview_format = "JPEG" previewer = False if preview_latent: previewer = latent_preview.get_previewer(device, model.model.latent_format) pbar = comfy.utils.ProgressBar(steps) def callback(step, x0, x, total_steps): preview_bytes = None if previewer: preview_bytes = previewer.decode_latent_to_preview_image(preview_format, x0) pbar.update_absolute(step + 1, total_steps, preview_bytes) samples = comfy.sample.sample_custom(model, noise, cfg, _sampler, sigmas, positive, negative, latent_image, noise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed) out = latent.copy() out["samples"] = samples return out def get_value_by_id(self, key: str, my_unique_id: Any) -> Optional[Any]: """Retrieve value by its associated ID.""" try: for value, id_ in self.last_helds[key]: if id_ == my_unique_id: return value except KeyError: return None def update_value_by_id(self, key: str, my_unique_id: Any, new_value: Any) -> Union[bool, None]: """Update the value associated with a given ID. Return True if updated, False if appended, None if key doesn't exist.""" try: for i, (value, id_) in enumerate(self.last_helds[key]): if id_ == my_unique_id: self.last_helds[key][i] = (new_value, id_) return True self.last_helds[key].append((new_value, my_unique_id)) return False except KeyError: return False def upscale(self, samples, upscale_method, scale_by, crop): s = samples.copy() width = self.enforce_mul_of_64(round(samples["samples"].shape[3] * scale_by)) height = self.enforce_mul_of_64(round(samples["samples"].shape[2] * scale_by)) if (width > MAX_RESOLUTION): width = MAX_RESOLUTION if (height > MAX_RESOLUTION): height = MAX_RESOLUTION s["samples"] = comfy.utils.common_upscale(samples["samples"], width, height, upscale_method, crop) return (s,) def handle_upscale(self, samples: dict, upscale_method: str, factor: float, crop: bool) -> dict: """Upscale the samples if the upscale_method is not set to 'None'.""" if upscale_method != "None": samples = self.upscale(samples, upscale_method, factor, crop)[0] return samples def init_state(self, my_unique_id: Any, key: str, default: Any) -> Any: """Initialize the state by either fetching the stored value or setting a default.""" value = self.get_value_by_id(key, my_unique_id) if value is not None: return value return default def get_output(self, pipe: dict,) -> Tuple: """Return a tuple of various elements fetched from the input pipe dictionary.""" return ( pipe, pipe.get("images"), pipe.get("model"), pipe.get("positive"), pipe.get("negative"), pipe.get("samples"), pipe.get("vae"), pipe.get("clip"), pipe.get("seed"), ) def get_output_sdxl(self, sdxl_pipe: dict) -> Tuple: """Return a tuple of various elements fetched from the input sdxl_pipe dictionary.""" return ( sdxl_pipe, sdxl_pipe.get("model"), sdxl_pipe.get("positive"), sdxl_pipe.get("negative"), sdxl_pipe.get("vae"), sdxl_pipe.get("refiner_model"), sdxl_pipe.get("refiner_positive"), sdxl_pipe.get("refiner_negative"), sdxl_pipe.get("refiner_vae"), sdxl_pipe.get("samples"), sdxl_pipe.get("clip"), sdxl_pipe.get("images"), sdxl_pipe.get("seed") ) # XY图表 class easyXYPlot: def __init__(self, xyPlotData, save_prefix, image_output, prompt, extra_pnginfo, my_unique_id): self.x_node_type, self.x_type = easySampler.safe_split(xyPlotData.get("x_axis"), ': ') self.y_node_type, self.y_type = easySampler.safe_split(xyPlotData.get("y_axis"), ': ') self.x_values = xyPlotData.get("x_vals") if self.x_type != "None" else [] self.y_values = xyPlotData.get("y_vals") if self.y_type != "None" else [] self.grid_spacing = xyPlotData.get("grid_spacing") self.latent_id = 0 self.output_individuals = xyPlotData.get("output_individuals") self.x_label, self.y_label = [], [] self.max_width, self.max_height = 0, 0 self.latents_plot = [] self.image_list = [] self.num_cols = len(self.x_values) if len(self.x_values) > 0 else 1 self.num_rows = len(self.y_values) if len(self.y_values) > 0 else 1 self.total = self.num_cols * self.num_rows self.num = 0 self.save_prefix = save_prefix self.image_output = image_output self.prompt = prompt self.extra_pnginfo = extra_pnginfo self.my_unique_id = my_unique_id # Helper Functions @staticmethod def define_variable(plot_image_vars, value_type, value, index): plot_image_vars[value_type] = value if value_type in ["seed", "Seeds++ Batch"]: value_label = f"{value}" else: value_label = f"{value_type}: {value}" if "ControlNet" in value_type: if "," in value: line = value.split(',') value_label = f"{value_type}: {line[2]}" if value_type in ["ModelMergeBlocks"]: if ":" in value: line = value.split(':') value_label = f"{line[0]}" elif len(value) > 16: value_label = f"ModelMergeBlocks {index + 1}" else: value_label = f"MMB: {value}" if value_type in ["Positive Prompt S/R"]: value_label = f"pos prompt {index + 1}" if index>0 else f"pos prompt" if value_type in ["Negative Prompt S/R"]: value_label = f"neg prompt {index + 1}" if index>0 else f"neg prompt" if value_type in ["steps", "cfg", "denoise", "clip_skip", "lora_model_strength", "lora_clip_strength"]: value_label = f"{value_type}: {value}" if value_type == "positive": value_label = f"pos prompt {index + 1}" elif value_type == "negative": value_label = f"neg prompt {index + 1}" return plot_image_vars, value_label @staticmethod def get_font(font_size): return ImageFont.truetype(str(Path(os.path.join(Path(__file__).parent.parent, 'resources/OpenSans-Medium.ttf'))), font_size) @staticmethod def update_label(label, value, num_items): if len(label) < num_items: return [*label, value] return label @staticmethod def rearrange_tensors(latent, num_cols, num_rows): new_latent = [] for i in range(num_rows): for j in range(num_cols): index = j * num_rows + i new_latent.append(latent[index]) return new_latent def calculate_background_dimensions(self): border_size = int((self.max_width // 8) * 1.5) if self.y_type != "None" or self.x_type != "None" else 0 bg_width = self.num_cols * (self.max_width + self.grid_spacing) - self.grid_spacing + border_size * ( self.y_type != "None") bg_height = self.num_rows * (self.max_height + self.grid_spacing) - self.grid_spacing + border_size * ( self.x_type != "None") x_offset_initial = border_size if self.y_type != "None" else 0 y_offset = border_size if self.x_type != "None" else 0 return bg_width, bg_height, x_offset_initial, y_offset def adjust_font_size(self, text, initial_font_size, label_width): font = self.get_font(initial_font_size) text_width, _ = font.getsize(text) scaling_factor = 0.9 if text_width > (label_width * scaling_factor): return int(initial_font_size * (label_width / text_width) * scaling_factor) else: return initial_font_size def create_label(self, img, text, initial_font_size, is_x_label=True, max_font_size=70, min_font_size=10): label_width = img.width if is_x_label else img.height # Adjust font size font_size = self.adjust_font_size(text, initial_font_size, label_width) font_size = min(max_font_size, font_size) # Ensure font isn't too large font_size = max(min_font_size, font_size) # Ensure font isn't too small label_height = int(font_size * 1.5) if is_x_label else font_size label_bg = Image.new('RGBA', (label_width, label_height), color=(255, 255, 255, 0)) d = ImageDraw.Draw(label_bg) font = self.get_font(font_size) # Check if text will fit, if not insert ellipsis and reduce text if d.textsize(text, font=font)[0] > label_width: while d.textsize(text + '...', font=font)[0] > label_width and len(text) > 0: text = text[:-1] text = text + '...' # Compute text width and height for multi-line text text_lines = text.split('\n') text_widths, text_heights = zip(*[d.textsize(line, font=font) for line in text_lines]) max_text_width = max(text_widths) total_text_height = sum(text_heights) # Compute position for each line of text lines_positions = [] current_y = 0 for line, line_width, line_height in zip(text_lines, text_widths, text_heights): text_x = (label_width - line_width) // 2 text_y = current_y + (label_height - total_text_height) // 2 current_y += line_height lines_positions.append((line, (text_x, text_y))) # Draw each line of text for line, (text_x, text_y) in lines_positions: d.text((text_x, text_y), line, fill='black', font=font) return label_bg def sample_plot_image(self, plot_image_vars, samples, preview_latent, latents_plot, image_list, disable_noise, start_step, last_step, force_full_denoise, x_value=None, y_value=None): model, clip, vae, positive, negative, seed, steps, cfg = None, None, None, None, None, None, None, None sampler_name, scheduler, denoise = None, None, None # 高级用法 if plot_image_vars["x_node_type"] == "advanced" or plot_image_vars["y_node_type"] == "advanced": if self.x_type == "Seeds++ Batch" or self.y_type == "Seeds++ Batch": seed = int(x_value) if self.x_type == "Seeds++ Batch" else int(y_value) if self.x_type == "Steps" or self.y_type == "Steps": steps = int(x_value) if self.x_type == "Steps" else int(y_value) if self.x_type == "StartStep" or self.y_type == "StartStep": start_step = int(x_value) if self.x_type == "StartStep" else int(y_value) if self.x_type == "EndStep" or self.y_type == "EndStep": last_step = int(x_value) if self.x_type == "EndStep" else int(y_value) if self.x_type == "CFG Scale" or self.y_type == "CFG Scale": cfg = float(x_value) if self.x_type == "CFG Scale" else float(y_value) if self.x_type == "Sampler" or self.y_type == "Sampler" or self.y_type == "Sampler & Scheduler": sampler_name = float(x_value) if self.x_type == "Sampler" or self.x_type == "Sampler & Scheduler" else float(y_value) if self.x_type == "Scheduler" or self.y_type == "Scheduler" or self.y_type == "Sampler & Scheduler": scheduler = float(x_value) if self.x_type == "Scheduler" or self.x_type == "Sampler & Scheduler" else float(y_value) if self.x_type == "Denoise" or self.y_type == "Denoise": denoise = float(x_value) if self.x_type == "Denoise" else float(y_value) # 模型叠加 if self.x_type == "ModelMergeBlocks" or self.y_type == "ModelMergeBlocks": ckpt_name_1, ckpt_name_2 = plot_image_vars['models'] model1, clip1, vae1 = easyCache.load_checkpoint(ckpt_name_1) model2, clip2, vae2 = easyCache.load_checkpoint(ckpt_name_2) xy_values = x_value if self.x_type == "ModelMergeBlocks" else y_value if ":" in xy_values: xy_line = xy_values.split(':') xy_values = xy_line[1] xy_arrs = xy_values.split(',') # ModelMergeBlocks if len(xy_arrs) == 3: input, middle, out = xy_arrs kwargs = { "input": input, "middle": middle, "out": out } elif len(xy_arrs) == 30: kwargs = {} kwargs["time_embed."] = xy_arrs[0] kwargs["label_emb."] = xy_arrs[1] for i in range(12): kwargs["input_blocks.{}.".format(i)] = xy_arrs[2+i] for i in range(3): kwargs["middle_block.{}.".format(i)] = xy_arrs[14+i] for i in range(12): kwargs["output_blocks.{}.".format(i)] = xy_arrs[17+i] kwargs["out."] = xy_arrs[29] else: raise Exception("ModelMergeBlocks weight length error") default_ratio = next(iter(kwargs.values())) m = model1.clone() kp = model2.get_key_patches("diffusion_model.") for k in kp: ratio = float(default_ratio) k_unet = k[len("diffusion_model."):] last_arg_size = 0 for arg in kwargs: if k_unet.startswith(arg) and last_arg_size < len(arg): ratio = float(kwargs[arg]) last_arg_size = len(arg) m.add_patches({k: kp[k]}, 1.0 - ratio, ratio) vae_use = plot_image_vars['vae_use'] clip = clip2 if vae_use == 'Use Model 2' else clip1 if vae_use == 'Use Model 2': vae = vae2 elif vae_use == 'Use Model 1': vae = vae1 else: (vae,) = VAELoader().load_vae(vae_use) model = m # 如果存在lora_stack叠加lora optional_lora_stack = plot_image_vars['lora_stack'] if optional_lora_stack is not None and optional_lora_stack != []: for lora in optional_lora_stack: lora_name = lora["lora_name"] model = model if model is not None else lora["model"] clip = clip if clip is not None else lora["clip"] lora_model_strength = lora["lora_model_strength"] lora_clip_strength = lora["lora_clip_strength"] if "lbw" in lora: lbw = lora["lbw"] lbw_a = lora["lbw_a"] lbw_b = lora["lbw_b"] cls = ALL_NODE_CLASS_MAPPINGS['LoraLoaderBlockWeight //Inspire'] model, clip, _ = cls().doit(model, clip, lora_name, lora_model_strength, lora_clip_strength, False, 0, lbw_a, lbw_b, "", lbw) model, clip = easyCache.load_lora(lora_name, model, clip, lora_model_strength, lora_clip_strength) # 处理clip clip = clip.clone() if plot_image_vars['clip_skip'] != 0: clip.clip_layer(plot_image_vars['clip_skip']) # 提示词 if "Positive" in self.x_type or "Positive" in self.y_type: if self.x_type == 'Positive Prompt S/R' or self.y_type == 'Positive Prompt S/R': positive = x_value if self.x_type == "Positive Prompt S/R" else y_value if plot_image_vars['a1111_prompt_style']: if "smZ CLIPTextEncode" in ALL_NODE_CLASS_MAPPINGS: cls = ALL_NODE_CLASS_MAPPINGS['smZ CLIPTextEncode'] steps = plot_image_vars['steps'] clip = clip if clip is not None else plot_image_vars["clip"] positive, = cls().encode(clip, positive, "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) else: raise Exception( f"[ERROR] To use clip text encode same as webui, you need to install 'smzNodes'") else: clip = clip if clip is not None else plot_image_vars["clip"] positive, positive_pooled = advanced_encode(clip, positive, plot_image_vars['positive_token_normalization'], plot_image_vars[ 'positive_weight_interpretation'], w_max=1.0, apply_to_pooled="enable") positive = [[positive, {"pooled_output": positive_pooled}]] if "Negative" in self.x_type or "Negative" in self.y_type: if self.x_type == 'Negative Prompt S/R' or self.y_type == 'Negative Prompt S/R': negative = x_value if self.x_type == "Negative Prompt S/R" else y_value if plot_image_vars['a1111_prompt_style']: if "smZ CLIPTextEncode" in ALL_NODE_CLASS_MAPPINGS: cls = ALL_NODE_CLASS_MAPPINGS['smZ CLIPTextEncode'] steps = plot_image_vars['steps'] clip = clip if clip is not None else plot_image_vars["clip"] negative, = cls().encode(clip, negative, "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) else: raise Exception( f"[ERROR] To use clip text encode same as webui, you need to install 'smzNodes'") else: clip = clip if clip is not None else plot_image_vars["clip"] negative, negative_pooled = advanced_encode(clip, negative, plot_image_vars['negative_token_normalization'], plot_image_vars[ 'negative_weight_interpretation'], w_max=1.0, apply_to_pooled="enable") negative = [[negative, {"pooled_output": negative_pooled}]] # ControlNet if "ControlNet" in self.x_type or "ControlNet" in self.y_type: _pipe = { "model": model if model is not None else plot_image_vars["model"], "positive": positive if positive is not None else plot_image_vars["positive_cond"], "negative": negative if negative is not None else plot_image_vars["negative_cond"], "vae": vae if vae is not None else plot_image_vars['vae'], "clip": clip if clip is not None else plot_image_vars['clip'], "samples": None, "images": None, "loader_settings": {} } cnet = plot_image_vars["cnet"] if "cnet" in plot_image_vars else None if cnet: strength, start_percent, end_percent = x_value.split(',') if "ControlNet" in self.x_type else y_value.split(',') strength = float(strength) start_percent = float(start_percent) end_percent = float(end_percent) for index, item in enumerate(cnet): control_net_names = item[0] image = item[1] for idx, control_net_name in enumerate(control_net_names): # print(control_net_name) _pipe, = controlnetAdvanced().controlnetApply(_pipe, image, control_net_name, None, strength, start_percent, end_percent) positive = _pipe['positive'] negative = _pipe['negative'] del _pipe # 简单用法 if plot_image_vars["x_node_type"] == "loader" or plot_image_vars["y_node_type"] == "loader": model, clip, vae = easyCache.load_checkpoint(plot_image_vars['ckpt_name']) if plot_image_vars['lora_name'] != "None": model, clip = easyCache.load_lora(plot_image_vars['lora_name'], model, clip, plot_image_vars['lora_model_strength'], plot_image_vars['lora_clip_strength']) # Check for custom VAE if plot_image_vars['vae_name'] not in ["Baked-VAE", "Baked VAE"]: vae = easyCache.load_vae(plot_image_vars['vae_name']) # CLIP skip if not clip: raise Exception("No CLIP found") clip = clip.clone() clip.clip_layer(plot_image_vars['clip_skip']) if plot_image_vars['a1111_prompt_style']: if "smZ CLIPTextEncode" in ALL_NODE_CLASS_MAPPINGS: cls = ALL_NODE_CLASS_MAPPINGS['smZ CLIPTextEncode'] steps = plot_image_vars['steps'] positive, = cls().encode(clip, plot_image_vars['positive'], "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) negative, = cls().encode(clip, plot_image_vars['negative'], "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) else: raise Exception(f"[ERROR] To use clip text encode same as webui, you need to install 'smzNodes'") else: positive, positive_pooled = advanced_encode(clip, plot_image_vars['positive'], plot_image_vars['positive_token_normalization'], plot_image_vars['positive_weight_interpretation'], w_max=1.0, apply_to_pooled="enable") positive = [[positive, {"pooled_output": positive_pooled}]] negative, negative_pooled = advanced_encode(clip, plot_image_vars['negative'], plot_image_vars['negative_token_normalization'], plot_image_vars['negative_weight_interpretation'], w_max=1.0, apply_to_pooled="enable") negative = [[negative, {"pooled_output": negative_pooled}]] model = model if model is not None else plot_image_vars["model"] clip = clip if clip is not None else plot_image_vars["clip"] vae = vae if vae is not None else plot_image_vars["vae"] positive = positive if positive is not None else plot_image_vars["positive_cond"] negative = negative if negative is not None else plot_image_vars["negative_cond"] seed = seed if seed is not None else plot_image_vars["seed"] steps = steps if steps is not None else plot_image_vars["steps"] cfg = cfg if cfg is not None else plot_image_vars["cfg"] sampler_name = sampler_name if sampler_name is not None else plot_image_vars["sampler_name"] scheduler = scheduler if scheduler is not None else plot_image_vars["scheduler"] denoise = denoise if denoise is not None else plot_image_vars["denoise"] # Sample samples = sampler.common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, samples, denoise=denoise, disable_noise=disable_noise, preview_latent=preview_latent, start_step=start_step, last_step=last_step, force_full_denoise=force_full_denoise) # Decode images and store latent = samples["samples"] # Add the latent tensor to the tensors list latents_plot.append(latent) # Decode the image image = vae.decode(latent).cpu() if self.output_individuals in [True, "True"]: easy_save = easySave(self.my_unique_id, self.prompt, self.extra_pnginfo) easy_save.images(image, self.save_prefix, self.image_output, group_id=self.num) # Convert the image from tensor to PIL Image and add it to the list pil_image = easySampler.tensor2pil(image) image_list.append(pil_image) # Update max dimensions self.max_width = max(self.max_width, pil_image.width) self.max_height = max(self.max_height, pil_image.height) # Return the touched variables return image_list, self.max_width, self.max_height, latents_plot # Process Functions def validate_xy_plot(self): if self.x_type == 'None' and self.y_type == 'None': log_node_warn(f'easyKsampler[{self.my_unique_id}]','No Valid Plot Types - Reverting to default sampling...') return False else: return True def get_latent(self, samples): # Extract the 'samples' tensor from the dictionary latent_image_tensor = samples["samples"] # Split the tensor into individual image tensors image_tensors = torch.split(latent_image_tensor, 1, dim=0) # Create a list of dictionaries containing the individual image tensors latent_list = [{'samples': image} for image in image_tensors] # Set latent only to the first latent of batch if self.latent_id >= len(latent_list): log_node_warn(f'easy kSampler[{self.my_unique_id}]',f'The selected latent_id ({self.latent_id}) is out of range.') log_node_warn(f'easy kSampler[{self.my_unique_id}]', f'Automatically setting the latent_id to the last image in the list (index: {len(latent_list) - 1}).') self.latent_id = len(latent_list) - 1 return latent_list[self.latent_id] def get_labels_and_sample(self, plot_image_vars, latent_image, preview_latent, start_step, last_step, force_full_denoise, disable_noise): for x_index, x_value in enumerate(self.x_values): plot_image_vars, x_value_label = self.define_variable(plot_image_vars, self.x_type, x_value, x_index) self.x_label = self.update_label(self.x_label, x_value_label, len(self.x_values)) if self.y_type != 'None': for y_index, y_value in enumerate(self.y_values): plot_image_vars, y_value_label = self.define_variable(plot_image_vars, self.y_type, y_value, y_index) self.y_label = self.update_label(self.y_label, y_value_label, len(self.y_values)) # ttNl(f'{CC.GREY}X: {x_value_label}, Y: {y_value_label}').t( # f'Plot Values {self.num}/{self.total} ->').p() self.image_list, self.max_width, self.max_height, self.latents_plot = self.sample_plot_image( plot_image_vars, latent_image, preview_latent, self.latents_plot, self.image_list, disable_noise, start_step, last_step, force_full_denoise, x_value, y_value) self.num += 1 else: # ttNl(f'{CC.GREY}X: {x_value_label}').t(f'Plot Values {self.num}/{self.total} ->').p() self.image_list, self.max_width, self.max_height, self.latents_plot = self.sample_plot_image( plot_image_vars, latent_image, preview_latent, self.latents_plot, self.image_list, disable_noise, start_step, last_step, force_full_denoise, x_value) self.num += 1 # Rearrange latent array to match preview image grid self.latents_plot = self.rearrange_tensors(self.latents_plot, self.num_cols, self.num_rows) # Concatenate the tensors along the first dimension (dim=0) self.latents_plot = torch.cat(self.latents_plot, dim=0) return self.latents_plot def plot_images_and_labels(self): # Calculate the background dimensions bg_width, bg_height, x_offset_initial, y_offset = self.calculate_background_dimensions() # Create the white background image background = Image.new('RGBA', (int(bg_width), int(bg_height)), color=(255, 255, 255, 255)) output_image = [] for row_index in range(self.num_rows): x_offset = x_offset_initial for col_index in range(self.num_cols): index = col_index * self.num_rows + row_index img = self.image_list[index] output_image.append(sampler.pil2tensor(img)) background.paste(img, (x_offset, y_offset)) # Handle X label if row_index == 0 and self.x_type != "None": label_bg = self.create_label(img, self.x_label[col_index], int(48 * img.width / 512)) label_y = (y_offset - label_bg.height) // 2 background.alpha_composite(label_bg, (x_offset, label_y)) # Handle Y label if col_index == 0 and self.y_type != "None": label_bg = self.create_label(img, self.y_label[row_index], int(48 * img.height / 512), False) label_bg = label_bg.rotate(90, expand=True) label_x = (x_offset - label_bg.width) // 2 label_y = y_offset + (img.height - label_bg.height) // 2 background.alpha_composite(label_bg, (label_x, label_y)) x_offset += img.width + self.grid_spacing y_offset += img.height + self.grid_spacing return (sampler.pil2tensor(background), output_image) easyCache = easyLoader() sampler = easySampler() def check_link_to_clip(node_id, clip_id, visited=None, node=None): """Check if a given node links directly or indirectly to a loader node.""" if visited is None: visited = set() if node_id in visited: return False visited.add(node_id) if "pipe" in node["inputs"]: link_ids = node["inputs"]["pipe"] for id in link_ids: if id != 0 and id == str(clip_id): return True return False def find_nearest_steps(clip_id, prompt): """Find the nearest KSampler or preSampling node that references the given id.""" for id in prompt: node = prompt[id] if "Sampler" in node["class_type"] or "sampler" in node["class_type"] or "Sampling" in node["class_type"]: # Check if this KSampler node directly or indirectly references the given CLIPTextEncode node if check_link_to_clip(id, clip_id, None, node): steps = node["inputs"]["steps"] if "steps" in node["inputs"] else 1 return steps return 1 def find_wildcards_seed(text, prompt): if "__" in text: for i in prompt: if "wildcards" in prompt[i]['class_type'] and text == prompt[i]['inputs']['text']: return prompt[i]['inputs']['seed_num'] if "seed_num" in prompt[i]['inputs'] else None else: return None class easySave: def __init__(self, my_unique_id=0, prompt=None, extra_pnginfo=None, number_padding=5, overwrite_existing=False, output_dir=folder_paths.get_temp_directory()): self.number_padding = int(number_padding) if number_padding not in [None, "None", 0] else None self.overwrite_existing = overwrite_existing self.my_unique_id = my_unique_id self.prompt = prompt self.extra_pnginfo = extra_pnginfo self.type = 'temp' self.output_dir = output_dir if self.output_dir != folder_paths.get_temp_directory(): self.output_dir = self.folder_parser(self.output_dir, self.prompt, self.my_unique_id) if not os.path.exists(self.output_dir): self._create_directory(self.output_dir) @staticmethod def _create_directory(folder: str): """Try to create the directory and log the status.""" log_node_warn("", f"Folder {folder} does not exist. Attempting to create...") if not os.path.exists(folder): try: os.makedirs(folder) log_node_success("",f"{folder} Created Successfully") except OSError: log_node_error(f"Failed to create folder {folder}") pass @staticmethod def _map_filename(filename: str, filename_prefix: str) -> Tuple[int, str, Optional[int]]: """Utility function to map filename to its parts.""" # Get the prefix length and extract the prefix prefix_len = len(os.path.basename(filename_prefix)) prefix = filename[:prefix_len] # Search for the primary digits digits = re.search(r'(\d+)', filename[prefix_len:]) # Search for the number in brackets after the primary digits group_id = re.search(r'\((\d+)\)', filename[prefix_len:]) return (int(digits.group()) if digits else 0, prefix, int(group_id.group(1)) if group_id else 0) @staticmethod def _format_date(text: str, date: datetime.datetime) -> str: """Format the date according to specific patterns.""" date_formats = { 'd': lambda d: d.day, 'dd': lambda d: '{:02d}'.format(d.day), 'M': lambda d: d.month, 'MM': lambda d: '{:02d}'.format(d.month), 'h': lambda d: d.hour, 'hh': lambda d: '{:02d}'.format(d.hour), 'm': lambda d: d.minute, 'mm': lambda d: '{:02d}'.format(d.minute), 's': lambda d: d.second, 'ss': lambda d: '{:02d}'.format(d.second), 'y': lambda d: d.year, 'yy': lambda d: str(d.year)[2:], 'yyy': lambda d: str(d.year)[1:], 'yyyy': lambda d: d.year, } # We need to sort the keys in reverse order to ensure we match the longest formats first for format_str in sorted(date_formats.keys(), key=len, reverse=True): if format_str in text: text = text.replace(format_str, str(date_formats[format_str](date))) return text @staticmethod def _gather_all_inputs(prompt: Dict[str, dict], unique_id: str, linkInput: str = '', collected_inputs: Optional[Dict[str, Union[str, List[str]]]] = None) -> Dict[ str, Union[str, List[str]]]: """Recursively gather all inputs from the prompt dictionary.""" if prompt == None: return None collected_inputs = collected_inputs or {} prompt_inputs = prompt[str(unique_id)]["inputs"] for p_input, p_input_value in prompt_inputs.items(): a_input = f"{linkInput}>{p_input}" if linkInput else p_input if isinstance(p_input_value, list): easySave._gather_all_inputs(prompt, p_input_value[0], a_input, collected_inputs) else: existing_value = collected_inputs.get(a_input) if existing_value is None: collected_inputs[a_input] = p_input_value elif p_input_value not in existing_value: collected_inputs[a_input] = existing_value + "; " + p_input_value # if "text" in collected_inputs: # del collected_inputs['text'] # print(collected_inputs) return collected_inputs @staticmethod def _get_filename_with_padding(output_dir, filename, number_padding, group_id, ext): """Return filename with proper padding.""" try: filtered = list(filter(lambda a: a[1] == filename, map(lambda x: easySave._map_filename(x, filename), os.listdir(output_dir)))) last = max(filtered)[0] for f in filtered: if f[0] == last: if f[2] == 0 or f[2] == group_id: last += 1 counter = last except (ValueError, FileNotFoundError): os.makedirs(output_dir, exist_ok=True) counter = 1 if group_id == 0: return f"{filename}.{ext}" if number_padding is None else f"{filename}_{counter:0{number_padding}}.{ext}" else: return f"{filename}_({group_id}).{ext}" if number_padding is None else f"{filename}_{counter:0{number_padding}}_({group_id}).{ext}" @staticmethod def filename_parser(output_dir: str, filename_prefix: str, prompt: Dict[str, dict], my_unique_id: str, number_padding: int, group_id: int, ext: str) -> str: """Parse the filename using provided patterns and replace them with actual values.""" subfolder = os.path.dirname(os.path.normpath(filename_prefix)) filename = os.path.basename(os.path.normpath(filename_prefix)) filename = re.sub(r'%date:(.*?)%', lambda m: easySave._format_date(m.group(1), datetime.datetime.now()), filename_prefix) all_inputs = easySave._gather_all_inputs(prompt, my_unique_id) filename = re.sub(r'%(.*?)%', lambda m: str(all_inputs.get(m.group(1), '')), filename) filename = re.sub(r'[/\\]+', '-', filename) filename = easySave._get_filename_with_padding(output_dir, filename, number_padding, group_id, ext) return filename, subfolder @staticmethod def folder_parser(output_dir: str, prompt: Dict[str, dict], my_unique_id: str): output_dir = re.sub(r'%date:(.*?)%', lambda m: easySave._format_date(m.group(1), datetime.datetime.now()), output_dir) all_inputs = easySave._gather_all_inputs(prompt, my_unique_id) return re.sub(r'%(.*?)%', lambda m: str(all_inputs.get(m.group(1), '')), output_dir) def images(self, images, filename_prefix, output_type, embed_workflow=True, ext="png", group_id=0): FORMAT_MAP = { "png": "PNG", "jpg": "JPEG", "jpeg": "JPEG", "bmp": "BMP", "tif": "TIFF", "tiff": "TIFF" } if ext not in FORMAT_MAP: raise ValueError(f"Unsupported file extension {ext}") if output_type == "Hide": return list() if output_type in ("Save", "Hide/Save", "Sender/Save"): output_dir = self.output_dir if self.output_dir != folder_paths.get_temp_directory() else folder_paths.get_output_directory() self.type = "output" if output_type in ("Preview", "Sender"): output_dir = self.output_dir filename_prefix = 'easyPreview' results = list() for image in images: img = Image.fromarray(np.clip(255. * image.cpu().numpy(), 0, 255).astype(np.uint8)) filename = filename_prefix.replace("%width%", str(img.size[0])).replace("%height%", str(img.size[1])) filename, subfolder = easySave.filename_parser(output_dir, filename, self.prompt, self.my_unique_id, self.number_padding, group_id, ext) file_path = os.path.join(output_dir, filename) if ext == "png" and embed_workflow in (True, "True"): metadata = PngInfo() if self.prompt is not None: metadata.add_text("prompt", json.dumps(self.prompt)) if hasattr(self, 'extra_pnginfo') and self.extra_pnginfo is not None: for key, value in self.extra_pnginfo.items(): metadata.add_text(key, json.dumps(value)) if self.overwrite_existing or not os.path.isfile(file_path): img.save(file_path, pnginfo=metadata, format=FORMAT_MAP[ext]) else: if self.overwrite_existing or not os.path.isfile(file_path): img.save(file_path, format=FORMAT_MAP[ext]) else: log_node_error("",f"File {file_path} already exists... Skipping") results.append({ "filename": filename, "subfolder": subfolder, "type": self.type }) return results def textfile(self, text, filename_prefix, output_type, group_id=0, ext='txt'): if output_type == "Hide": return [] if output_type in ("Save", "Hide/Save"): output_dir = self.output_dir if self.output_dir != folder_paths.get_temp_directory() else folder_paths.get_output_directory() if output_type == "Preview": filename_prefix = 'easyPreview' filename = easySave.filename_parser(output_dir, filename_prefix, self.prompt, self.my_unique_id, self.number_padding, group_id, ext) file_path = os.path.join(output_dir, filename) if self.overwrite_existing or not os.path.isfile(file_path): with open(file_path, 'w') as f: f.write(text) else: log_node_error("", f"File {file_path} already exists... Skipping") # ---------------------------------------------------------------提示词 开始----------------------------------------------------------------------# # 正面提示词 class positivePrompt: def __init__(self): pass @classmethod def INPUT_TYPES(s): return {"required": { "positive": ("STRING", {"default": "", "multiline": True, "placeholder": "Positive"}),} } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("positive",) FUNCTION = "main" CATEGORY = "EasyUse/Prompt" @staticmethod def main(positive): return positive, # 通配符提示词 class wildcardsPrompt: def __init__(self): pass @classmethod def INPUT_TYPES(s): wildcard_list = get_wildcard_list() return {"required": { "text": ("STRING", {"default": "", "multiline": True, "dynamicPrompts": False, "placeholder": "(Support Lora Block Weight and wildcard)"}), "Select to add LoRA": (["Select the LoRA to add to the text"] + folder_paths.get_filename_list("loras"),), "Select to add Wildcard": (["Select the Wildcard to add to the text"] + wildcard_list,), "seed_num": ("INT", {"default": 0, "min": 0, "max": 1125899906842624}), }, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID"}, } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("text",) OUTPUT_NODE = True FUNCTION = "main" CATEGORY = "EasyUse/Prompt" @staticmethod def main(*args, **kwargs): my_unique_id = kwargs["my_unique_id"] extra_pnginfo = kwargs["extra_pnginfo"] prompt = kwargs["prompt"] seed_num = kwargs["seed_num"] # Clean loaded_objects easyCache.update_loaded_objects(prompt) my_unique_id = int(my_unique_id) easy_save = easySave(my_unique_id, prompt, extra_pnginfo) # if my_unique_id: # workflow = extra_pnginfo["workflow"] # node = next((x for x in workflow["nodes"] if str(x["id"]) == my_unique_id), None) # if node: # seed_num = prompt[my_unique_id]['inputs']['seed_num'] if 'seed_num' in prompt[my_unique_id][ # 'inputs'] else 0 # length = len(node["widgets_values"]) # node["widgets_values"][length - 2] = seed_num text = kwargs['text'] return {"ui": {"value": [seed_num]}, "result": (text,)} # 负面提示词 class negativePrompt: def __init__(self): pass @classmethod def INPUT_TYPES(s): return {"required": { "negative": ("STRING", {"default": "", "multiline": True, "placeholder": "Negative"}),} } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("negative",) FUNCTION = "main" CATEGORY = "EasyUse/Prompt" @staticmethod def main(negative): return negative, # 肖像大师 # Created by AI Wiz Art (Stefano Flore) # Version: 2.2 # https://stefanoflore.it # https://ai-wiz.art class portraitMaster: @classmethod def INPUT_TYPES(s): max_float_value = 1.95 prompt_path = Path(os.path.join(Path(__file__).parent.parent, 'resources/portrait_prompt.json')) if not os.path.exists(prompt_path): response = urlopen('https://raw.githubusercontent.com/yolain/ComfyUI-Easy-Use/main/resources/portrait_prompt.json') temp_prompt = json.loads(response.read()) prompt_serialized = json.dumps(temp_prompt, indent=4) with open(prompt_path, "w") as f: f.write(prompt_serialized) del response, temp_prompt # Load local with open(prompt_path, 'r') as f: list = json.load(f) keys = [ ['shot', 'COMBO', {"key": "shot_list"}], ['shot_weight', 'FLOAT'], ['gender', 'COMBO', {"default": "Woman", "key": "gender_list"}], ['age', 'INT', {"default": 30, "min": 18, "max": 90, "step": 1, "display": "slider"}], ['nationality_1', 'COMBO', {"default": "Chinese", "key": "nationality_list"}], ['nationality_2', 'COMBO', {"key": "nationality_list"}], ['nationality_mix', 'FLOAT'], ['body_type', 'COMBO', {"key": "body_type_list"}], ['body_type_weight', 'FLOAT'], ['model_pose', 'COMBO', {"key": "model_pose_list"}], ['eyes_color', 'COMBO', {"key": "eyes_color_list"}], ['facial_expression', 'COMBO', {"key": "face_expression_list"}], ['facial_expression_weight', 'FLOAT'], ['face_shape', 'COMBO', {"key": "face_shape_list"}], ['face_shape_weight', 'FLOAT'], ['facial_asymmetry', 'FLOAT'], ['hair_style', 'COMBO', {"key": "hair_style_list"}], ['hair_color', 'COMBO', {"key": "hair_color_list"}], ['disheveled', 'FLOAT'], ['beard', 'COMBO', {"key": "beard_list"}], ['skin_details', 'FLOAT'], ['skin_pores', 'FLOAT'], ['dimples', 'FLOAT'], ['freckles', 'FLOAT'], ['moles', 'FLOAT'], ['skin_imperfections', 'FLOAT'], ['skin_acne', 'FLOAT'], ['tanned_skin', 'FLOAT'], ['eyes_details', 'FLOAT'], ['iris_details', 'FLOAT'], ['circular_iris', 'FLOAT'], ['circular_pupil', 'FLOAT'], ['light_type', 'COMBO', {"key": "light_type_list"}], ['light_direction', 'COMBO', {"key": "light_direction_list"}], ['light_weight', 'FLOAT'] ] widgets = {} for i, obj in enumerate(keys): if obj[1] == 'COMBO': key = obj[2]['key'] if obj[2] and 'key' in obj[2] else obj[0] _list = list[key].copy() _list.insert(0, '-') widgets[obj[0]] = (_list, {**obj[2]}) elif obj[1] == 'FLOAT': widgets[obj[0]] = ("FLOAT", {"default": 0, "step": 0.05, "min": 0, "max": max_float_value, "display": "slider",}) elif obj[1] == 'INT': widgets[obj[0]] = (obj[1], obj[2]) del list return { "required": { **widgets, "photorealism_improvement": (["enable", "disable"],), "prompt_start": ("STRING", {"multiline": True, "default": "raw photo, (realistic:1.5)"}), "prompt_additional": ("STRING", {"multiline": True, "default": ""}), "prompt_end": ("STRING", {"multiline": True, "default": ""}), "negative_prompt": ("STRING", {"multiline": True, "default": ""}), } } RETURN_TYPES = ("STRING", "STRING",) RETURN_NAMES = ("positive", "negative",) FUNCTION = "pm" CATEGORY = "EasyUse/Prompt" def pm(self, shot="-", shot_weight=1, gender="-", body_type="-", body_type_weight=0, eyes_color="-", facial_expression="-", facial_expression_weight=0, face_shape="-", face_shape_weight=0, nationality_1="-", nationality_2="-", nationality_mix=0.5, age=30, hair_style="-", hair_color="-", disheveled=0, dimples=0, freckles=0, skin_pores=0, skin_details=0, moles=0, skin_imperfections=0, wrinkles=0, tanned_skin=0, eyes_details=1, iris_details=1, circular_iris=1, circular_pupil=1, facial_asymmetry=0, prompt_additional="", prompt_start="", prompt_end="", light_type="-", light_direction="-", light_weight=0, negative_prompt="", photorealism_improvement="disable", beard="-", model_pose="-", skin_acne=0): prompt = [] if gender == "-": gender = "" else: if age <= 25 and gender == 'Woman': gender = 'girl' if age <= 25 and gender == 'Man': gender = 'boy' gender = " " + gender + " " if nationality_1 != '-' and nationality_2 != '-': nationality = f"[{nationality_1}:{nationality_2}:{round(nationality_mix, 2)}]" elif nationality_1 != '-': nationality = nationality_1 + " " elif nationality_2 != '-': nationality = nationality_2 + " " else: nationality = "" if prompt_start != "": prompt.append(f"{prompt_start}") if shot != "-" and shot_weight > 0: prompt.append(f"({shot}:{round(shot_weight, 2)})") prompt.append(f"({nationality}{gender}{round(age)}-years-old:1.5)") if body_type != "-" and body_type_weight > 0: prompt.append(f"({body_type}, {body_type} body:{round(body_type_weight, 2)})") if model_pose != "-": prompt.append(f"({model_pose}:1.5)") if eyes_color != "-": prompt.append(f"({eyes_color} eyes:1.25)") if facial_expression != "-" and facial_expression_weight > 0: prompt.append( f"({facial_expression}, {facial_expression} expression:{round(facial_expression_weight, 2)})") if face_shape != "-" and face_shape_weight > 0: prompt.append(f"({face_shape} shape face:{round(face_shape_weight, 2)})") if hair_style != "-": prompt.append(f"({hair_style} hairstyle:1.25)") if hair_color != "-": prompt.append(f"({hair_color} hair:1.25)") if beard != "-": prompt.append(f"({beard}:1.15)") if disheveled != "-" and disheveled > 0: prompt.append(f"(disheveled:{round(disheveled, 2)})") if prompt_additional != "": prompt.append(f"{prompt_additional}") if skin_details > 0: prompt.append(f"(skin details, skin texture:{round(skin_details, 2)})") if skin_pores > 0: prompt.append(f"(skin pores:{round(skin_pores, 2)})") if skin_imperfections > 0: prompt.append(f"(skin imperfections:{round(skin_imperfections, 2)})") if skin_acne > 0: prompt.append(f"(acne, skin with acne:{round(skin_acne, 2)})") if wrinkles > 0: prompt.append(f"(skin imperfections:{round(wrinkles, 2)})") if tanned_skin > 0: prompt.append(f"(tanned skin:{round(tanned_skin, 2)})") if dimples > 0: prompt.append(f"(dimples:{round(dimples, 2)})") if freckles > 0: prompt.append(f"(freckles:{round(freckles, 2)})") if moles > 0: prompt.append(f"(skin pores:{round(moles, 2)})") if eyes_details > 0: prompt.append(f"(eyes details:{round(eyes_details, 2)})") if iris_details > 0: prompt.append(f"(iris details:{round(iris_details, 2)})") if circular_iris > 0: prompt.append(f"(circular iris:{round(circular_iris, 2)})") if circular_pupil > 0: prompt.append(f"(circular pupil:{round(circular_pupil, 2)})") if facial_asymmetry > 0: prompt.append(f"(facial asymmetry, face asymmetry:{round(facial_asymmetry, 2)})") if light_type != '-' and light_weight > 0: if light_direction != '-': prompt.append(f"({light_type} {light_direction}:{round(light_weight, 2)})") else: prompt.append(f"({light_type}:{round(light_weight, 2)})") if prompt_end != "": prompt.append(f"{prompt_end}") prompt = ", ".join(prompt) prompt = prompt.lower() if photorealism_improvement == "enable": prompt = prompt + ", (professional photo, balanced photo, balanced exposure:1.2), (film grain:1.15)" if photorealism_improvement == "enable": negative_prompt = negative_prompt + ", (shinny skin, reflections on the skin, skin reflections:1.25)" log_node_info("Portrait Master as generate the prompt:", prompt) return (prompt, negative_prompt,) # 潜空间sigma相乘 class latentMultiplyBySigma: @classmethod def INPUT_TYPES(s): return {"required": { "sampler_name": (comfy.samplers.KSampler.SAMPLERS,), "scheduler": (comfy.samplers.KSampler.SCHEDULERS,), "steps": ("INT", {"default": 10000, "min": 0, "max": 10000}), "start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}), "end_at_step": ("INT", {"default": 10000, "min": 1, "max": 10000}), }, "optional": { "pipe": ("PIPE_LINE",), "optional_model": ("MODEL",), "optional_latent": ("LATENT",) }} RETURN_TYPES = ("PIPE_LINE", "LATENT", "FLOAT",) RETURN_NAMES = ("pipe", "latent", "sigma",) FUNCTION = "run" CATEGORY = "EasyUse/Latent" def run(self, sampler_name, scheduler, steps, start_at_step, end_at_step, pipe=None, optional_model=None, optional_latent=None): model = optional_model if optional_model is not None else pipe["model"] samples = optional_latent if optional_latent is not None else pipe["samples"] device = comfy.model_management.get_torch_device() end_at_step = min(steps, end_at_step) start_at_step = min(start_at_step, end_at_step) real_model = None comfy.model_management.load_model_gpu(model) real_model = model.model sampler = comfy.samplers.KSampler(real_model, steps=steps, device=device, sampler=sampler_name, scheduler=scheduler, denoise=1.0, model_options=model.model_options) sigmas = sampler.sigmas sigma = sigmas[start_at_step] - sigmas[end_at_step] sigma /= model.model.latent_format.scale_factor sigma = sigma.cpu().numpy() samples_out = samples.copy() s1 = samples["samples"] samples_out["samples"] = s1 * sigma if pipe is None: pipe = {} new_pipe = { **pipe, "samples": samples_out } del pipe return (new_pipe, samples_out, sigma) # Latent遮罩复合 class latentCompositeMaskedWithCond: @classmethod def INPUT_TYPES(s): return { "required": { "pipe": ("PIPE_LINE",), "text_combine": ("STRING", {"default": ""}), "source_latent": ("LATENT",), "source_mask": ("MASK",), "new_mask": ("MASK",), }, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID"}, } RETURN_TYPES = ("PIPE_LINE", "LATENT", "CONDITIONING") RETURN_NAMES = ("pipe", "latent", "conditioning",) FUNCTION = "run" OUTPUT_MODE = True CATEGORY = "EasyUse/Latent" def run(self, pipe, text_combine, source_latent, source_mask, new_mask, prompt=None, extra_pnginfo=None, my_unique_id=None): clip = pipe["clip"] destination_latent = pipe["samples"] positive = pipe["loader_settings"]["positive"] + ',' + text_combine positive_token_normalization = pipe["loader_settings"]["positive_token_normalization"] positive_weight_interpretation = pipe["loader_settings"]["positive_weight_interpretation"] a1111_prompt_style = pipe["loader_settings"]["a1111_prompt_style"] positive_cond = pipe["positive"] log_node_warn("正在处理提示词编码...") # Use new clip text encode by smzNodes like same as webui, when if you installed the smzNodes if a1111_prompt_style: if "smZ CLIPTextEncode" in ALL_NODE_CLASS_MAPPINGS: cls = ALL_NODE_CLASS_MAPPINGS['smZ CLIPTextEncode'] steps = pipe["steps"] positive_embeddings_final, = cls().encode(clip, positive, "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) else: raise Exception(f"[ERROR] To use clip text encode same as webui, you need to install 'smzNodes'") else: positive_embeddings_final, positive_pooled = advanced_encode(clip, positive, positive_token_normalization, positive_weight_interpretation, w_max=1.0, apply_to_pooled='enable') positive_embeddings_final = [[positive_embeddings_final, {"pooled_output": positive_pooled}]] # source cond (cond_1,) = ConditioningSetMask().append(positive_cond, source_mask, "default", 1) (cond_2,) = ConditioningSetMask().append(positive_embeddings_final, new_mask, "default", 1) positive_cond = cond_1 + cond_2 # latent composite masked (samples,) = LatentCompositeMasked().composite(destination_latent, source_latent, 0, 0, False) new_pipe = { **pipe, "positive": positive_cond, "samples": samples, "loader_settings": { **pipe["loader_settings"], "positive": positive, } } del pipe return (new_pipe, samples, positive_cond) # 随机种 class easySeed: @classmethod def INPUT_TYPES(s): return { "required": { "seed_num": ("INT", {"default": 0, "min": 0, "max": 1125899906842624}), }, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID"}, } RETURN_TYPES = ("INT",) RETURN_NAMES = ("seed_num",) FUNCTION = "doit" CATEGORY = "EasyUse/Seed" OUTPUT_NODE = True def doit(self, seed_num=0, prompt=None, extra_pnginfo=None, my_unique_id=None): return seed_num, # 全局随机种 class globalSeed: @classmethod def INPUT_TYPES(s): return { "required": { "value": ("INT", {"default": 0, "min": 0, "max": 1125899906842624}), "mode": ("BOOLEAN", {"default": True, "label_on": "control_before_generate", "label_off": "control_after_generate"}), "action": (["fixed", "increment", "decrement", "randomize", "increment for each node", "decrement for each node", "randomize for each node"], ), "last_seed": ("STRING", {"default": ""}), } } RETURN_TYPES = () FUNCTION = "doit" CATEGORY = "EasyUse/Seed" OUTPUT_NODE = True def doit(self, **kwargs): return {} #---------------------------------------------------------------提示词 结束------------------------------------------------------------------------# #---------------------------------------------------------------加载器 开始----------------------------------------------------------------------# # 简易加载器完整 class fullLoader: @classmethod def INPUT_TYPES(cls): resolution_strings = [f"{width} x {height}" for width, height in BASE_RESOLUTIONS] a1111_prompt_style_default = False return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"),), "config_name": (["Default", ] + folder_paths.get_filename_list("configs"), {"default": "Default"}), "vae_name": (["Baked VAE"] + folder_paths.get_filename_list("vae"),), "clip_skip": ("INT", {"default": -1, "min": -24, "max": 0, "step": 1}), "lora_name": (["None"] + folder_paths.get_filename_list("loras"),), "lora_model_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), "lora_clip_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), "resolution": (resolution_strings,), "empty_latent_width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), "empty_latent_height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), "positive": ("STRING", {"default": "Positive", "multiline": True}), "positive_token_normalization": (["none", "mean", "length", "length+mean"],), "positive_weight_interpretation": (["comfy", "A1111", "comfy++", "compel", "fixed attention"],), "negative": ("STRING", {"default": "Negative", "multiline": True}), "negative_token_normalization": (["none", "mean", "length", "length+mean"],), "negative_weight_interpretation": (["comfy", "A1111", "comfy++", "compel", "fixed attention"],), "batch_size": ("INT", {"default": 1, "min": 1, "max": 64}), }, "optional": {"model_override": ("MODEL",), "clip_override": ("CLIP",), "vae_override": ("VAE",), "optional_lora_stack": ("LORA_STACK",), "a1111_prompt_style": ("BOOLEAN", {"default": a1111_prompt_style_default}),}, "hidden": {"prompt": "PROMPT", "my_unique_id": "UNIQUE_ID"} } RETURN_TYPES = ("PIPE_LINE", "MODEL", "VAE", "CLIP") RETURN_NAMES = ("pipe", "model", "vae", "clip") FUNCTION = "adv_pipeloader" CATEGORY = "EasyUse/Loaders" def adv_pipeloader(self, ckpt_name, config_name, vae_name, clip_skip, lora_name, lora_model_strength, lora_clip_strength, resolution, empty_latent_width, empty_latent_height, positive, positive_token_normalization, positive_weight_interpretation, negative, negative_token_normalization, negative_weight_interpretation, batch_size, model_override=None, clip_override=None, vae_override=None, optional_lora_stack=None, a1111_prompt_style=False, prompt=None, my_unique_id=None ): model: ModelPatcher | None = None clip: CLIP | None = None vae: VAE | None = None can_load_lora = True pipe_lora_stack = [] # resolution if resolution != "自定义 x 自定义": try: width, height = map(int, resolution.split(' x ')) empty_latent_width = width empty_latent_height = height except ValueError: raise ValueError("Invalid base_resolution format.") # Create Empty Latent latent = torch.zeros([batch_size, 4, empty_latent_height // 8, empty_latent_width // 8]).cpu() samples = {"samples": latent} # Clean models from loaded_objects easyCache.update_loaded_objects(prompt) log_node_warn("正在处理模型...") # 判断是否存在 模型叠加xyplot, 若存在优先缓存第一个模型 xyinputs_id = next((x for x in prompt if str(prompt[x]["class_type"]) == "easy XYInputs: ModelMergeBlocks"), None) if xyinputs_id is not None: node = prompt[xyinputs_id] if "ckpt_name_1" in node["inputs"]: ckpt_name_1 = node["inputs"]["ckpt_name_1"] model, clip, vae = easyCache.load_checkpoint(ckpt_name_1) can_load_lora = False # Load models elif model_override is not None and clip_override is not None and vae_override is not None: model = model_override clip = clip_override vae = vae_override elif model_override is not None: raise Exception(f"[ERROR] clip or vae is missing") elif vae_override is not None: raise Exception(f"[ERROR] model or clip is missing") elif clip_override is not None: raise Exception(f"[ERROR] model or vae is missing") else: model, clip, vae = easyCache.load_checkpoint(ckpt_name, config_name) if optional_lora_stack is not None: for lora in optional_lora_stack: if can_load_lora: model, clip = easyCache.load_lora(lora[0], model, clip, lora[1], lora[2]) pipe_lora_stack.append({"lora_name": lora[0], "model": model, "clip": clip, "lora_model_strength": lora[1], "lora_clip_strength": lora[2]}) if lora_name != "None": if can_load_lora: model, clip = easyCache.load_lora(lora_name, model, clip, lora_model_strength, lora_clip_strength) pipe_lora_stack.append({"lora_name": lora_name, "model": model, "clip": clip, "lora_model_strength": lora_model_strength, "lora_clip_strength": lora_clip_strength}) # Check for custom VAE if vae_name not in ["Baked VAE", "Baked-VAE"]: vae = easyCache.load_vae(vae_name) # CLIP skip if not clip: raise Exception("No CLIP found") log_node_warn("正在处理提示词...") positive_seed = find_wildcards_seed(positive, prompt) model, clip, positive, positive_decode, show_positive_prompt, pipe_lora_stack = process_with_loras(positive, model, clip, "Positive", positive_seed, can_load_lora, pipe_lora_stack) positive_wildcard_prompt = positive_decode if show_positive_prompt else "" negative_seed = find_wildcards_seed(negative, prompt) model, clip, negative, negative_decode, show_negative_prompt, pipe_lora_stack = process_with_loras(negative, model, clip, "Negative", negative_seed, can_load_lora, pipe_lora_stack) negative_wildcard_prompt = negative_decode if show_negative_prompt else "" clipped = clip.clone() if clip_skip != 0 and can_load_lora: clipped.clip_layer(clip_skip) log_node_warn("正在处理提示词编码...") # Use new clip text encode by smzNodes like same as webui, when if you installed the smzNodes if a1111_prompt_style: if "smZ CLIPTextEncode" in ALL_NODE_CLASS_MAPPINGS: cls = ALL_NODE_CLASS_MAPPINGS['smZ CLIPTextEncode'] steps = find_nearest_steps(my_unique_id, prompt) positive_embeddings_final, = cls().encode(clipped, positive, "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) negative_embeddings_final, = cls().encode(clipped, negative, "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) else: raise Exception(f"[ERROR] To use clip text encode same as webui, you need to install 'smzNodes'") else: positive_embeddings_final, positive_pooled = advanced_encode(clipped, positive, positive_token_normalization, positive_weight_interpretation, w_max=1.0, apply_to_pooled='enable') positive_embeddings_final = [[positive_embeddings_final, {"pooled_output": positive_pooled}]] negative_embeddings_final, negative_pooled = advanced_encode(clipped, negative, negative_token_normalization, negative_weight_interpretation, w_max=1.0, apply_to_pooled='enable') negative_embeddings_final = [[negative_embeddings_final, {"pooled_output": negative_pooled}]] image = easySampler.pil2tensor(Image.new('RGB', (1, 1), (0, 0, 0))) log_node_warn("处理结束...") pipe = {"model": model, "positive": positive_embeddings_final, "negative": negative_embeddings_final, "vae": vae, "clip": clip, "samples": samples, "images": image, "seed": 0, "loader_settings": {"ckpt_name": ckpt_name, "vae_name": vae_name, "lora_name": lora_name, "lora_model_strength": lora_model_strength, "lora_clip_strength": lora_clip_strength, "lora_stack": pipe_lora_stack, "refiner_ckpt_name": None, "refiner_vae_name": None, "refiner_lora_name": None, "refiner_lora_model_strength": None, "refiner_lora_clip_strength": None, "clip_skip": clip_skip, "a1111_prompt_style": a1111_prompt_style, "positive": positive, "positive_l": None, "positive_g": None, "positive_token_normalization": positive_token_normalization, "positive_weight_interpretation": positive_weight_interpretation, "positive_balance": None, "negative": negative, "negative_l": None, "negative_g": None, "negative_token_normalization": negative_token_normalization, "negative_weight_interpretation": negative_weight_interpretation, "negative_balance": None, "empty_latent_width": empty_latent_width, "empty_latent_height": empty_latent_height, "batch_size": batch_size, "seed": 0, "empty_samples": samples, } } return {"ui": {"positive": positive_wildcard_prompt, "negative": negative_wildcard_prompt}, "result": (pipe, model, vae, clip)} # A1111简易加载器 class a1111Loader: @classmethod def INPUT_TYPES(cls): resolution_strings = [f"{width} x {height}" for width, height in BASE_RESOLUTIONS] a1111_prompt_style_default = False checkpoints = folder_paths.get_filename_list("checkpoints") loras = ["None"] + folder_paths.get_filename_list("loras") return {"required": { "ckpt_name": (checkpoints,), "vae_name": (["Baked VAE"] + folder_paths.get_filename_list("vae"),), "clip_skip": ("INT", {"default": -1, "min": -24, "max": 0, "step": 1}), "lora_name": (loras,), "lora_model_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), "lora_clip_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), "resolution": (resolution_strings, {"default": "512 x 512"}), "empty_latent_width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), "empty_latent_height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), "positive": ("STRING", {"default": "Positive", "multiline": True}), "negative": ("STRING", {"default": "Negative", "multiline": True}), "batch_size": ("INT", {"default": 1, "min": 1, "max": 64}), }, "optional": {"optional_lora_stack": ("LORA_STACK",), "a1111_prompt_style": ("BOOLEAN", {"default": a1111_prompt_style_default})}, "hidden": {"prompt": "PROMPT", "my_unique_id": "UNIQUE_ID"} } RETURN_TYPES = ("PIPE_LINE", "MODEL", "VAE") RETURN_NAMES = ("pipe", "model", "vae") FUNCTION = "adv_pipeloader" CATEGORY = "EasyUse/Loaders" def adv_pipeloader(self, ckpt_name, vae_name, clip_skip, lora_name, lora_model_strength, lora_clip_strength, resolution, empty_latent_width, empty_latent_height, positive, negative, batch_size, optional_lora_stack=None, a1111_prompt_style=False, prompt=None, my_unique_id=None): return fullLoader.adv_pipeloader(self, ckpt_name, 'Default', vae_name, clip_skip, lora_name, lora_model_strength, lora_clip_strength, resolution, empty_latent_width, empty_latent_height, positive, 'none', 'A1111', negative,'none','A1111', batch_size, None, None, None, optional_lora_stack, a1111_prompt_style, prompt, my_unique_id ) # Comfy简易加载器 class comfyLoader: @classmethod def INPUT_TYPES(cls): resolution_strings = [f"{width} x {height}" for width, height in BASE_RESOLUTIONS] return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"),), "vae_name": (["Baked VAE"] + folder_paths.get_filename_list("vae"),), "clip_skip": ("INT", {"default": -1, "min": -24, "max": 0, "step": 1}), "lora_name": (["None"] + folder_paths.get_filename_list("loras"),), "lora_model_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), "lora_clip_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), "resolution": (resolution_strings, {"default": "512 x 512"}), "empty_latent_width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), "empty_latent_height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), "positive": ("STRING", {"default": "Positive", "multiline": True}), "negative": ("STRING", {"default": "Negative", "multiline": True}), "batch_size": ("INT", {"default": 1, "min": 1, "max": 64}), }, "optional": {"optional_lora_stack": ("LORA_STACK",)}, "hidden": {"prompt": "PROMPT", "positive_weight_interpretation": "comfy", "negative_weight_interpretation": "comfy"}, "my_unique_id": "UNIQUE_ID"} RETURN_TYPES = ("PIPE_LINE", "MODEL", "VAE") RETURN_NAMES = ("pipe", "model", "vae") FUNCTION = "adv_pipeloader" CATEGORY = "EasyUse/Loaders" def adv_pipeloader(self, ckpt_name, vae_name, clip_skip, lora_name, lora_model_strength, lora_clip_strength, resolution, empty_latent_width, empty_latent_height, positive, negative, batch_size, optional_lora_stack=None, prompt=None, my_unique_id=None): return fullLoader.adv_pipeloader(self, ckpt_name, 'Default', vae_name, clip_skip, lora_name, lora_model_strength, lora_clip_strength, resolution, empty_latent_width, empty_latent_height, positive, 'none', 'comfy', negative, 'none', 'comfy', batch_size, None, None, None, optional_lora_stack, False, prompt, my_unique_id ) # Zero123简易加载器 (3D) try: except FileNotFoundError: log_node_error("EasyUse[zero123Loader]", "请更新ComfyUI到最新版本") class zero123Loader: @classmethod def INPUT_TYPES(cls): def get_file_list(filenames): return [file for file in filenames if file != "put_models_here.txt" and "zero123" in file] return {"required": { "ckpt_name": (get_file_list(folder_paths.get_filename_list("checkpoints")),), "vae_name": (["Baked VAE"] + folder_paths.get_filename_list("vae"),), "init_image": ("IMAGE",), "empty_latent_width": ("INT", {"default": 256, "min": 16, "max": MAX_RESOLUTION, "step": 8}), "empty_latent_height": ("INT", {"default": 256, "min": 16, "max": MAX_RESOLUTION, "step": 8}), "batch_size": ("INT", {"default": 1, "min": 1, "max": 64}), "elevation": ("FLOAT", {"default": 0.0, "min": -180.0, "max": 180.0}), "azimuth": ("FLOAT", {"default": 0.0, "min": -180.0, "max": 180.0}), }, "hidden": {"prompt": "PROMPT"}, "my_unique_id": "UNIQUE_ID"} RETURN_TYPES = ("PIPE_LINE", "MODEL", "VAE") RETURN_NAMES = ("pipe", "model", "vae") FUNCTION = "adv_pipeloader" CATEGORY = "EasyUse/Loaders" def adv_pipeloader(self, ckpt_name, vae_name, init_image, empty_latent_width, empty_latent_height, batch_size, elevation, azimuth, prompt=None, my_unique_id=None): model: ModelPatcher | None = None vae: VAE | None = None clip: CLIP | None = None clip_vision = None # Clean models from loaded_objects easyCache.update_loaded_objects(prompt) model, clip_vision, vae = easyCache.load_checkpoint(ckpt_name, "Default", True) output = clip_vision.encode_image(init_image) pooled = output.image_embeds.unsqueeze(0) pixels = comfy.utils.common_upscale(init_image.movedim(-1, 1), empty_latent_width, empty_latent_height, "bilinear", "center").movedim(1, -1) encode_pixels = pixels[:, :, :, :3] t = vae.encode(encode_pixels) cam_embeds = camera_embeddings(elevation, azimuth) cond = torch.cat([pooled, cam_embeds.repeat((pooled.shape[0], 1, 1))], dim=-1) positive = [[cond, {"concat_latent_image": t}]] negative = [[torch.zeros_like(pooled), {"concat_latent_image": torch.zeros_like(t)}]] latent = torch.zeros([batch_size, 4, empty_latent_height // 8, empty_latent_width // 8]) samples = {"samples": latent} image = easySampler.pil2tensor(Image.new('RGB', (1, 1), (0, 0, 0))) pipe = {"model": model, "positive": positive, "negative": negative, "vae": vae, "clip": clip, "samples": samples, "images": image, "seed": 0, "loader_settings": {"ckpt_name": ckpt_name, "vae_name": vae_name, "positive": positive, "positive_l": None, "positive_g": None, "positive_balance": None, "negative": negative, "negative_l": None, "negative_g": None, "negative_balance": None, "empty_latent_width": empty_latent_width, "empty_latent_height": empty_latent_height, "batch_size": batch_size, "seed": 0, "empty_samples": samples, } } return (pipe, model, vae) #svd加载器 class svdLoader: @classmethod def INPUT_TYPES(cls): resolution_strings = [f"{width} x {height}" for width, height in BASE_RESOLUTIONS] def get_file_list(filenames): return [file for file in filenames if file != "put_models_here.txt" and "svd" in file] return {"required": { "ckpt_name": (get_file_list(folder_paths.get_filename_list("checkpoints")),), "vae_name": (["Baked VAE"] + folder_paths.get_filename_list("vae"),), "init_image": ("IMAGE",), "resolution": (resolution_strings, {"default": "1024 x 576"}), "empty_latent_width": ("INT", {"default": 256, "min": 16, "max": MAX_RESOLUTION, "step": 8}), "empty_latent_height": ("INT", {"default": 256, "min": 16, "max": MAX_RESOLUTION, "step": 8}), "video_frames": ("INT", {"default": 14, "min": 1, "max": 4096}), "motion_bucket_id": ("INT", {"default": 127, "min": 1, "max": 1023}), "fps": ("INT", {"default": 6, "min": 1, "max": 1024}), "augmentation_level": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.01}) }, "hidden": {"prompt": "PROMPT"}, "my_unique_id": "UNIQUE_ID"} RETURN_TYPES = ("PIPE_LINE", "MODEL", "VAE") RETURN_NAMES = ("pipe", "model", "vae") FUNCTION = "adv_pipeloader" CATEGORY = "EasyUse/Loaders" def adv_pipeloader(self, ckpt_name, vae_name, init_image, resolution, empty_latent_width, empty_latent_height, video_frames, motion_bucket_id, fps, augmentation_level, prompt=None, my_unique_id=None): model: ModelPatcher | None = None vae: VAE | None = None clip: CLIP | None = None clip_vision = None # resolution if resolution != "自定义 x 自定义": try: width, height = map(int, resolution.split(' x ')) empty_latent_width = width empty_latent_height = height except ValueError: raise ValueError("Invalid base_resolution format.") # Clean models from loaded_objects easyCache.update_loaded_objects(prompt) model, clip_vision, vae = easyCache.load_checkpoint(ckpt_name, "Default", True) output = clip_vision.encode_image(init_image) pooled = output.image_embeds.unsqueeze(0) pixels = comfy.utils.common_upscale(init_image.movedim(-1, 1), empty_latent_width, empty_latent_height, "bilinear", "center").movedim(1, -1) encode_pixels = pixels[:, :, :, :3] if augmentation_level > 0: encode_pixels += torch.randn_like(pixels) * augmentation_level t = vae.encode(encode_pixels) positive = [[pooled, {"motion_bucket_id": motion_bucket_id, "fps": fps, "augmentation_level": augmentation_level, "concat_latent_image": t}]] negative = [[torch.zeros_like(pooled), {"motion_bucket_id": motion_bucket_id, "fps": fps, "augmentation_level": augmentation_level, "concat_latent_image": torch.zeros_like(t)}]] latent = torch.zeros([video_frames, 4, empty_latent_height // 8, empty_latent_width // 8]) samples = {"samples": latent} image = easySampler.pil2tensor(Image.new('RGB', (1, 1), (0, 0, 0))) pipe = {"model": model, "positive": positive, "negative": negative, "vae": vae, "clip": clip, "samples": samples, "images": image, "seed": 0, "loader_settings": {"ckpt_name": ckpt_name, "vae_name": vae_name, "positive": positive, "positive_l": None, "positive_g": None, "positive_balance": None, "negative": negative, "negative_l": None, "negative_g": None, "negative_balance": None, "empty_latent_width": empty_latent_width, "empty_latent_height": empty_latent_height, "batch_size": 1, "seed": 0, "empty_samples": samples, } } return (pipe, model, vae) # lora class loraStackLoader: def __init__(self): pass @classmethod def INPUT_TYPES(s): max_lora_num = 10 inputs = { "required": { "toggle": ([True, False],), "mode": (["simple", "advanced"],), "num_loras": ("INT", {"default": 1, "min": 0, "max": max_lora_num}), }, "optional": { "optional_lora_stack": ("LORA_STACK",), }, } for i in range(1, max_lora_num+1): inputs["optional"][f"lora_{i}_name"] = ( ["None"] + folder_paths.get_filename_list("loras"), {"default": "None"}) inputs["optional"][f"lora_{i}_strength"] = ( "FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}) inputs["optional"][f"lora_{i}_model_strength"] = ( "FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}) inputs["optional"][f"lora_{i}_clip_strength"] = ( "FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}) return inputs RETURN_TYPES = ("LORA_STACK",) RETURN_NAMES = ("lora_stack",) FUNCTION = "stack" CATEGORY = "EasyUse/Loaders" def stack(self, toggle, mode, num_loras, lora_stack=None, **kwargs): if (toggle in [False, None, "False"]) or not kwargs: return None loras = [] # Import Stack values if lora_stack is not None: loras.extend([l for l in lora_stack if l[0] != "None"]) # Import Lora values for i in range(1, num_loras + 1): lora_name = kwargs.get(f"lora_{i}_name") if not lora_name or lora_name == "None": continue if mode == "simple": lora_strength = float(kwargs.get(f"lora_{i}_strength")) loras.append((lora_name, lora_strength, lora_strength)) elif mode == "advanced": model_strength = float(kwargs.get(f"lora_{i}_model_strength")) clip_strength = float(kwargs.get(f"lora_{i}_clip_strength")) loras.append((lora_name, model_strength, clip_strength)) return (loras,) # controlnet class controlnetSimple: @classmethod def INPUT_TYPES(s): def get_file_list(filenames): return [file for file in filenames if file != "put_models_here.txt" and "lllite" not in file] return { "required": { "pipe": ("PIPE_LINE",), "image": ("IMAGE",), "control_net_name": (get_file_list(folder_paths.get_filename_list("controlnet")),), }, "optional": { "control_net": ("CONTROL_NET",), "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}) } } RETURN_TYPES = ("PIPE_LINE",) RETURN_NAMES = ("pipe",) OUTPUT_NODE = True FUNCTION = "controlnetApply" CATEGORY = "EasyUse/Loaders" def controlnetApply(self, pipe, image, control_net_name, control_net=None,strength=1): if control_net is None: controlnet_path = folder_paths.get_full_path("controlnet", control_net_name) control_net = comfy.controlnet.load_controlnet(controlnet_path) control_hint = image.movedim(-1, 1) positive = pipe["positive"] negative = pipe["negative"] if strength != 0: if negative is None: p = [] for t in positive: n = [t[0], t[1].copy()] c_net = control_net.copy().set_cond_hint(control_hint, strength) if 'control' in t[1]: c_net.set_previous_controlnet(t[1]['control']) n[1]['control'] = c_net n[1]['control_apply_to_uncond'] = True p.append(n) positive = p else: cnets = {} out = [] for conditioning in [positive, negative]: c = [] for t in conditioning: d = t[1].copy() prev_cnet = d.get('control', None) if prev_cnet in cnets: c_net = cnets[prev_cnet] else: c_net = control_net.copy().set_cond_hint(control_hint, strength) c_net.set_previous_controlnet(prev_cnet) cnets[prev_cnet] = c_net d['control'] = c_net d['control_apply_to_uncond'] = False n = [t[0], d] c.append(n) out.append(c) positive = out[0] negative = out[1] new_pipe = { "model": pipe['model'], "positive": positive, "negative": negative, "vae": pipe['vae'], "clip": pipe['clip'], "samples": pipe["samples"], "images": pipe["images"], "seed": 0, "loader_settings": pipe["loader_settings"] } return (new_pipe,) # controlnetADV class controlnetAdvanced: @classmethod def INPUT_TYPES(s): def get_file_list(filenames): return [file for file in filenames if file != "put_models_here.txt" and "lllite" not in file] return { "required": { "pipe": ("PIPE_LINE",), "image": ("IMAGE",), "control_net_name": (get_file_list(folder_paths.get_filename_list("controlnet")),), }, "optional": { "control_net": ("CONTROL_NET",), "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}), "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}) } } RETURN_TYPES = ("PIPE_LINE",) RETURN_NAMES = ("pipe",) OUTPUT_NODE = True FUNCTION = "controlnetApply" CATEGORY = "EasyUse/Loaders" def controlnetApply(self, pipe, image, control_net_name, control_net=None, strength=1, start_percent=0, end_percent=1): if control_net is None: controlnet_path = folder_paths.get_full_path("controlnet", control_net_name) control_net = comfy.controlnet.load_controlnet(controlnet_path) control_hint = image.movedim(-1, 1) positive = pipe["positive"] negative = pipe["negative"] if strength != 0: if negative is None: p = [] for t in positive: n = [t[0], t[1].copy()] c_net = control_net.copy().set_cond_hint(control_hint, strength) if 'control' in t[1]: c_net.set_previous_controlnet(t[1]['control']) n[1]['control'] = c_net n[1]['control_apply_to_uncond'] = True p.append(n) positive = p else: cnets = {} out = [] for conditioning in [positive, negative]: c = [] for t in conditioning: d = t[1].copy() prev_cnet = d.get('control', None) if prev_cnet in cnets: c_net = cnets[prev_cnet] else: c_net = control_net.copy().set_cond_hint(control_hint, strength, (start_percent, end_percent)) c_net.set_previous_controlnet(prev_cnet) cnets[prev_cnet] = c_net d['control'] = c_net d['control_apply_to_uncond'] = False n = [t[0], d] c.append(n) out.append(c) positive = out[0] negative = out[1] new_pipe = { "model": pipe['model'], "positive": positive, "negative": negative, "vae": pipe['vae'], "clip": pipe['clip'], "samples": pipe["samples"], "images": pipe["images"], "seed": 0, "loader_settings": pipe["loader_settings"] } del pipe return (new_pipe,) #---------------------------------------------------------------预采样 开始----------------------------------------------------------------------# # 预采样设置(基础) class samplerSettings: def __init__(self): pass @classmethod def INPUT_TYPES(cls): return {"required": {"pipe": ("PIPE_LINE",), "steps": ("INT", {"default": 20, "min": 1, "max": 10000}), "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0}), "sampler_name": (comfy.samplers.KSampler.SAMPLERS,), "scheduler": (comfy.samplers.KSampler.SCHEDULERS,), "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), "seed_num": ("INT", {"default": 0, "min": 0, "max": 1125899906842624}), }, "optional": { "image_to_latent": ("IMAGE",), "latent": ("LATENT",), }, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID"}, } RETURN_TYPES = ("PIPE_LINE", ) RETURN_NAMES = ("pipe",) OUTPUT_NODE = True FUNCTION = "settings" CATEGORY = "EasyUse/PreSampling" def settings(self, pipe, steps, cfg, sampler_name, scheduler, denoise, seed_num, image_to_latent=None, latent=None, prompt=None, extra_pnginfo=None, my_unique_id=None): # if my_unique_id: # workflow = extra_pnginfo["workflow"] # node = next((x for x in workflow["nodes"] if str(x["id"]) == my_unique_id), None) # if node: # seed_num = prompt[my_unique_id]['inputs']['seed_num'] if 'seed_num' in prompt[my_unique_id][ # 'inputs'] else 0 # length = len(node["widgets_values"]) # node["widgets_values"][length - 2] = seed_num # 图生图转换 vae = pipe["vae"] batch_size = pipe["loader_settings"]["batch_size"] if "batch_size" in pipe["loader_settings"] else 1 if image_to_latent is not None: samples = {"samples": vae.encode(image_to_latent)} samples = RepeatLatentBatch().repeat(samples, batch_size)[0] images = image_to_latent elif latent is not None: samples = RepeatLatentBatch().repeat(latent, batch_size)[0] images = pipe["images"] else: samples = pipe["samples"] images = pipe["images"] new_pipe = { "model": pipe['model'], "positive": pipe['positive'], "negative": pipe['negative'], "vae": pipe['vae'], "clip": pipe['clip'], "samples": samples, "images": images, "seed": seed_num, "loader_settings": { **pipe["loader_settings"], "steps": steps, "cfg": cfg, "sampler_name": sampler_name, "scheduler": scheduler, "denoise": denoise, "add_noise": "enabled" } } del pipe return {"ui": {"value": [seed_num]}, "result": (new_pipe,)} # 预采样设置(高级) class samplerSettingsAdvanced: def __init__(self): pass @classmethod def INPUT_TYPES(cls): return {"required": {"pipe": ("PIPE_LINE",), "steps": ("INT", {"default": 20, "min": 1, "max": 10000}), "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0}), "sampler_name": (comfy.samplers.KSampler.SAMPLERS,), "scheduler": (comfy.samplers.KSampler.SCHEDULERS,), "start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}), "end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000}), "add_noise": (["enable", "disable"],), "seed_num": ("INT", {"default": 0, "min": 0, "max": 1125899906842624}), }, "optional": { "image_to_latent": ("IMAGE",), "latent": ("LATENT",) }, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID"}, } RETURN_TYPES = ("PIPE_LINE", ) RETURN_NAMES = ("pipe",) OUTPUT_NODE = True FUNCTION = "settings" CATEGORY = "EasyUse/PreSampling" def settings(self, pipe, steps, cfg, sampler_name, scheduler, start_at_step, end_at_step, add_noise, seed_num, image_to_latent=None, latent=None, prompt=None, extra_pnginfo=None, my_unique_id=None): # if my_unique_id: # workflow = extra_pnginfo["workflow"] # node = next((x for x in workflow["nodes"] if str(x["id"]) == my_unique_id), None) # if node: # seed_num = prompt[my_unique_id]['inputs']['seed_num'] if 'seed_num' in prompt[my_unique_id][ # 'inputs'] else 0 # length = len(node["widgets_values"]) # node["widgets_values"][length - 2] = seed_num # 图生图转换 vae = pipe["vae"] batch_size = pipe["loader_settings"]["batch_size"] if "batch_size" in pipe["loader_settings"] else 1 if image_to_latent is not None: samples = {"samples": vae.encode(image_to_latent)} samples = RepeatLatentBatch().repeat(samples, batch_size)[0] images = image_to_latent elif latent is not None: samples = RepeatLatentBatch().repeat(latent, batch_size)[0] images = pipe["images"] else: samples = pipe["samples"] images = pipe["images"] new_pipe = { "model": pipe['model'], "positive": pipe['positive'], "negative": pipe['negative'], "vae": pipe['vae'], "clip": pipe['clip'], "samples": samples, "images": images, "seed": seed_num, "loader_settings": { **pipe["loader_settings"], "steps": steps, "cfg": cfg, "sampler_name": sampler_name, "scheduler": scheduler, "start_step": start_at_step, "last_step": end_at_step, "denoise": 1.0, "add_noise": add_noise } } del pipe return {"ui": {"value": [seed_num]}, "result": (new_pipe,)} # 预采样设置(SDTurbo) class sdTurboSettings: def __init__(self): pass @classmethod def INPUT_TYPES(cls): return {"required": { "pipe": ("PIPE_LINE",), "steps": ("INT", {"default": 1, "min": 1, "max": 10}), "cfg": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0}), "sampler_name": (comfy.samplers.SAMPLER_NAMES,), "eta": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01, "round": False}), "s_noise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01, "round": False}), "upscale_ratio": ("FLOAT", {"default": 2.0, "min": 0.0, "max": 16.0, "step": 0.01, "round": False}), "start_step": ("INT", {"default": 5, "min": 0, "max": 1000, "step": 1}), "end_step": ("INT", {"default": 15, "min": 0, "max": 1000, "step": 1}), "upscale_n_step": ("INT", {"default": 3, "min": 0, "max": 1000, "step": 1}), "unsharp_kernel_size": ("INT", {"default": 3, "min": 1, "max": 21, "step": 1}), "unsharp_sigma": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 10.0, "step": 0.01, "round": False}), "unsharp_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.01, "round": False}), "seed_num": ("INT", {"default": 0, "min": 0, "max": 1125899906842624}), }, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID"}, } RETURN_TYPES = ("PIPE_LINE",) RETURN_NAMES = ("pipe",) OUTPUT_NODE = True FUNCTION = "settings" CATEGORY = "EasyUse/PreSampling" def settings(self, pipe, steps, cfg, sampler_name, eta, s_noise, upscale_ratio, start_step, end_step, upscale_n_step, unsharp_kernel_size, unsharp_sigma, unsharp_strength, seed_num, prompt=None, extra_pnginfo=None, my_unique_id=None): model = pipe['model'] # sigma timesteps = torch.flip(torch.arange(1, 11) * 100 - 1, (0,))[:steps] sigmas = model.model.model_sampling.sigma(timesteps) sigmas = torch.cat([sigmas, sigmas.new_zeros([1])]) #sampler sample_function = None extra_options = { "eta": eta, "s_noise": s_noise, "upscale_ratio": upscale_ratio, "start_step": start_step, "end_step": end_step, "upscale_n_step": upscale_n_step, "unsharp_kernel_size": unsharp_kernel_size, "unsharp_sigma": unsharp_sigma, "unsharp_strength": unsharp_strength, } if sampler_name == "euler_ancestral": sample_function = sample_euler_ancestral elif sampler_name == "dpmpp_2s_ancestral":
sample_function = sample_dpmpp_2s_ancestral
9
2023-12-10 07:02:36+00:00
12k
Open-All-Scale-Causal-Engine/OpenASCE
openasce/inference/graph_inference.py
[ { "identifier": "CausalGraph", "path": "openasce/discovery/causal_graph.py", "snippet": "class CausalGraph(object):\n \"\"\"Causal Graph Class\n\n Represent the casual graph\n\n \"\"\"\n\n DEFAULT_COLUMN_NAME_PREFIX = \"x\"\n\n def __init__(self, names=[], bn=None, w: np.ndarray = None):\...
import copy import numpy as np from functools import reduce from typing import Dict, Iterable, List from openasce.discovery.causal_graph import CausalGraph from openasce.discovery.discovery import Discovery from openasce.discovery.graph_node_form import GraphNodeForm from openasce.inference.inference_model import InferenceModel from openasce.utils.logger import logger
7,237
# Copyright 2023 AntGroup CO., Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. class GraphInferModel(InferenceModel): """The inference using the causal graph Attributes: graph: The causal graph. If not set, the class will try to find it out if discovery is available. column_names: all names of sample treatment_name: treatment column name in column_names label_name: target column name in column_names """ def __init__( self, *, graph: CausalGraph = None, column_names: List[str] = None, treatment_name: str = None, label_name: str = None, num_iteration=20, ) -> None: """ Arguments: graph: causal graph column_names: all names of column treatment_name: the name of treatment column label_name: the name of target name """ super().__init__() self._graph = graph self._column_names = column_names self._treatment_name = treatment_name self._label_name = label_name self._discovery = None self._data = None self._num_iteration = num_iteration self._label_value = None @property def data(self): assert self._data is not None, f"Must have sample data." return self._data @property def graph(self): assert self._graph is not None, "The graph object should be set" return self._graph @graph.setter def graph(self, value): assert self._graph is None, "The graph object should be set once only" self._graph = value # graph is available, set the column names using graph columns self.column_names = list(self.graph.names_to_index.keys()) @property def column_names(self): """All nodes' name. Note: should include the treatment node and label node. """ assert self._column_names is not None, "The column names should be set" return self._column_names @column_names.setter def column_names(self, value: List[str]): assert self._column_names is None, "The column names should be set once only" self._column_names = value @property def treatment_name(self): assert self._treatment_name is not None, "The treatment name should be set" return self._treatment_name @treatment_name.setter def treatment_name(self, value: str): assert ( self._treatment_name is None ), "The treatment name should be set once only" self._treatment_name = value @property def label_name(self): assert self._label_name is not None, "The label name should be set" return self._label_name @label_name.setter def label_name(self, value: str): assert self._label_name is None, "The label name should be set once only" self._label_name = value @property
# Copyright 2023 AntGroup CO., Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. class GraphInferModel(InferenceModel): """The inference using the causal graph Attributes: graph: The causal graph. If not set, the class will try to find it out if discovery is available. column_names: all names of sample treatment_name: treatment column name in column_names label_name: target column name in column_names """ def __init__( self, *, graph: CausalGraph = None, column_names: List[str] = None, treatment_name: str = None, label_name: str = None, num_iteration=20, ) -> None: """ Arguments: graph: causal graph column_names: all names of column treatment_name: the name of treatment column label_name: the name of target name """ super().__init__() self._graph = graph self._column_names = column_names self._treatment_name = treatment_name self._label_name = label_name self._discovery = None self._data = None self._num_iteration = num_iteration self._label_value = None @property def data(self): assert self._data is not None, f"Must have sample data." return self._data @property def graph(self): assert self._graph is not None, "The graph object should be set" return self._graph @graph.setter def graph(self, value): assert self._graph is None, "The graph object should be set once only" self._graph = value # graph is available, set the column names using graph columns self.column_names = list(self.graph.names_to_index.keys()) @property def column_names(self): """All nodes' name. Note: should include the treatment node and label node. """ assert self._column_names is not None, "The column names should be set" return self._column_names @column_names.setter def column_names(self, value: List[str]): assert self._column_names is None, "The column names should be set once only" self._column_names = value @property def treatment_name(self): assert self._treatment_name is not None, "The treatment name should be set" return self._treatment_name @treatment_name.setter def treatment_name(self, value: str): assert ( self._treatment_name is None ), "The treatment name should be set once only" self._treatment_name = value @property def label_name(self): assert self._label_name is not None, "The label name should be set" return self._label_name @label_name.setter def label_name(self, value: str): assert self._label_name is None, "The label name should be set once only" self._label_name = value @property
def discovery(self) -> Discovery:
1
2023-12-06 05:54:36+00:00
12k
eclipse-t2i/eclipse-inference
main.py
[ { "identifier": "PriorTransformer", "path": "src/priors/prior_transformer.py", "snippet": "class PriorTransformer(ModelMixin, ConfigMixin):\n \"\"\"\n A Prior Transformer model.\n\n Parameters:\n num_attention_heads (`int`, *optional*, defaults to 32): The number of heads to use for mult...
import gradio as gr import torch import math import numpy as np import torch from PIL import Image from torchvision import transforms from transformers import ( CLIPProcessor, CLIPModel, CLIPTokenizer, CLIPTextModelWithProjection, CLIPVisionModelWithProjection, CLIPFeatureExtractor, ) from typing import List from PIL import Image, ImageChops from diffusers import UnCLIPPipeline from transformers import CLIPTokenizer from src.priors.prior_transformer import ( PriorTransformer, ) # original huggingface prior transformer without time conditioning from src.pipelines.pipeline_kandinsky_prior import KandinskyPriorPipeline from diffusers import DiffusionPipeline
8,651
# from diffusers.utils.torch_utils import randn_tensor __DEVICE__ = "cpu" if torch.cuda.is_available(): __DEVICE__ = "cuda" class Ours: def __init__(self, device): text_encoder = ( CLIPTextModelWithProjection.from_pretrained( "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", projection_dim=1280, torch_dtype=torch.float16, ) .eval() .requires_grad_(False) ) tokenizer = CLIPTokenizer.from_pretrained( "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k" )
# from diffusers.utils.torch_utils import randn_tensor __DEVICE__ = "cpu" if torch.cuda.is_available(): __DEVICE__ = "cuda" class Ours: def __init__(self, device): text_encoder = ( CLIPTextModelWithProjection.from_pretrained( "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", projection_dim=1280, torch_dtype=torch.float16, ) .eval() .requires_grad_(False) ) tokenizer = CLIPTokenizer.from_pretrained( "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k" )
prior = PriorTransformer.from_pretrained(
0
2023-12-07 05:17:08+00:00
12k
AIFSH/NativeDancer
nativedancer/third_part/densepose/modeling/losses/cse.py
[ { "identifier": "CfgNode", "path": "nativedancer/third_part/detectron2/config/config.py", "snippet": "class CfgNode(_CfgNode):\n \"\"\"\n The same as `fvcore.common.config.CfgNode`, but different in:\n\n 1. Use unsafe yaml loading by default.\n Note that this may lead to arbitrary code ex...
from typing import Any, List from torch import nn from nativedancer.third_part.detectron2.config import CfgNode from nativedancer.third_part.detectron2.structures import Instances from .cycle_pix2shape import PixToShapeCycleLoss from .cycle_shape2shape import ShapeToShapeCycleLoss from .embed import EmbeddingLoss from .embed_utils import CseAnnotationsAccumulator from .mask_or_segm import MaskOrSegmentationLoss from .registry import DENSEPOSE_LOSS_REGISTRY from .soft_embed import SoftEmbeddingLoss from .utils import BilinearInterpolationHelper, LossDict, extract_packed_annotations_from_matches
10,100
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved @DENSEPOSE_LOSS_REGISTRY.register() class DensePoseCseLoss: """ """ _EMBED_LOSS_REGISTRY = { EmbeddingLoss.__name__: EmbeddingLoss, SoftEmbeddingLoss.__name__: SoftEmbeddingLoss, }
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved @DENSEPOSE_LOSS_REGISTRY.register() class DensePoseCseLoss: """ """ _EMBED_LOSS_REGISTRY = { EmbeddingLoss.__name__: EmbeddingLoss, SoftEmbeddingLoss.__name__: SoftEmbeddingLoss, }
def __init__(self, cfg: CfgNode):
0
2023-12-10 20:14:00+00:00
12k
ethanweber/nerfiller
nerfiller/scripts/inpaint_nerfstudio_dataset.py
[ { "identifier": "RGBInpainter", "path": "nerfiller/inpaint/rgb_inpainter.py", "snippet": "class RGBInpainter:\n \"\"\"\n Module for inpainting with the stable diffusion inpainting pipeline.\n \"\"\"\n\n def __init__(\n self,\n half_precision_weights: bool = True,\n lora_...
import json import shutil import mediapy import torch import tyro import math from pathlib import Path from nerfiller.inpaint.rgb_inpainter import RGBInpainter from nerfiller.inpaint.lama_inpainter import LaMaInpainter from nerfiller.nerf.dataset_utils import parse_nerfstudio_frame from nerfiller.utils.image_utils import get_inpainted_image_row from nerfiller.utils.camera_utils import rescale_intrinsics from nerfiller.configs.inpaint import InpaintConfig, AnnotatedBaseConfigUnion from datetime import datetime from nerfiller.utils.diff_utils import register_extended_attention from nerfiller.utils.mask_utils import downscale_mask
10,571
def main( config: InpaintConfig, ): """ Inpaint a Nerfstudio dataset where the masks == 0. """ if config.method_name == "individual-lama":
def main( config: InpaintConfig, ): """ Inpaint a Nerfstudio dataset where the masks == 0. """ if config.method_name == "individual-lama":
rgb_inpainter = LaMaInpainter(device=config.device, model_path=Path("data/models/big-lama"))
1
2023-12-07 19:12:08+00:00
12k
nnanhuang/Customize-it-3D
ldm/models/diffusion/ddpm.py
[ { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new(\"RGB\", wh, color=\"white\")\n ...
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl import itertools from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager, nullcontext from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.rank_zero import rank_zero_only from omegaconf import ListConfig from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config from ldm.modules.ema import LitEma from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like from ldm.models.diffusion.ddim import DDIMSampler from ldm.modules.attention import CrossAttention
10,071
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, ): super().__init__() assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) self.ucg_training = ucg_training or dict() if self.ucg_training: self.ucg_prng = np.random.RandomState() def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, ): super().__init__() assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) self.ucg_training = ucg_training or dict() if self.ucg_training: self.ucg_prng = np.random.RandomState() def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
if exists(given_betas):
1
2023-12-14 11:03:35+00:00
12k
TaoHuang13/diffusion_reward
scripts/train_vqdiffusion.py
[ { "identifier": "build_dataloader", "path": "diffusion_reward/models/video_models/vqdiffusion/data/build.py", "snippet": "def build_dataloader(config, args=None, return_dataset=True):\n dataset_cfg = config['dataloader']\n train_dataset = []\n for ds_cfg in dataset_cfg['train_datasets']:\n ...
import os import warnings import hydra import torch from diffusion_reward.models.video_models.vqdiffusion.data.build import \ build_dataloader from diffusion_reward.models.video_models.vqdiffusion.distributed.launch import launch from diffusion_reward.models.video_models.vqdiffusion.engine.logger import Logger from diffusion_reward.models.video_models.vqdiffusion.engine.solver import Solver from diffusion_reward.models.video_models.vqdiffusion.modeling.build import \ build_model from diffusion_reward.models.video_models.vqdiffusion.utils.io import load_yaml_config from diffusion_reward.models.video_models.vqdiffusion.utils.misc import ( merge_opts_to_config, modify_config_for_debug, seed_everything)
8,364
# environment variables NODE_RANK = os.environ['AZ_BATCHAI_TASK_INDEX'] if 'AZ_BATCHAI_TASK_INDEX' in os.environ else 0 NODE_RANK = int(NODE_RANK) MASTER_ADDR, MASTER_PORT = os.environ['AZ_BATCH_MASTER_NODE'].split(':') if 'AZ_BATCH_MASTER_NODE' in os.environ else ("127.0.0.1", 29500) MASTER_PORT = int(MASTER_PORT) DIST_URL = 'tcp://%s:%s' % (MASTER_ADDR, MASTER_PORT) @hydra.main(config_path='../diffusion_reward/configs/models/video_models/vqdiffusion', config_name='default') def main(args): args.save_dir = os.path.abspath(os.path.dirname(__file__)) args.node_rank = NODE_RANK args.dist_url = DIST_URL if args.seed is not None or args.cudnn_deterministic:
# environment variables NODE_RANK = os.environ['AZ_BATCHAI_TASK_INDEX'] if 'AZ_BATCHAI_TASK_INDEX' in os.environ else 0 NODE_RANK = int(NODE_RANK) MASTER_ADDR, MASTER_PORT = os.environ['AZ_BATCH_MASTER_NODE'].split(':') if 'AZ_BATCH_MASTER_NODE' in os.environ else ("127.0.0.1", 29500) MASTER_PORT = int(MASTER_PORT) DIST_URL = 'tcp://%s:%s' % (MASTER_ADDR, MASTER_PORT) @hydra.main(config_path='../diffusion_reward/configs/models/video_models/vqdiffusion', config_name='default') def main(args): args.save_dir = os.path.abspath(os.path.dirname(__file__)) args.node_rank = NODE_RANK args.dist_url = DIST_URL if args.seed is not None or args.cudnn_deterministic:
seed_everything(args.seed, args.cudnn_deterministic)
8
2023-12-05 02:42:28+00:00
12k
mkang315/ASF-YOLO
models/yolo.py
[ { "identifier": "check_anchor_order", "path": "utils/autoanchor.py", "snippet": "def check_anchor_order(m):\n # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary\n a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer\n da = a...
import argparse import contextlib import os import platform import sys import thop # for FLOPs computation import yaml # for torch hub from copy import deepcopy from pathlib import Path from models.common import * from models.experimental import * from utils.autoanchor import check_anchor_order from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args from utils.plots import feature_visualization from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device, time_sync)
7,849
b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) b.data[:, 5:5 + m.nc] += math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum()) # cls mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) Model = DetectionModel # retain YOLOv5 'Model' class for backwards compatibility class SegmentationModel(DetectionModel): # YOLOv5 segmentation model def __init__(self, cfg='yolov5s-seg.yaml', ch=3, nc=None, anchors=None): super().__init__(cfg, ch, nc, anchors) class ClassificationModel(BaseModel): # YOLOv5 classification model def __init__(self, cfg=None, model=None, nc=1000, cutoff=10): # yaml, model, number of classes, cutoff index super().__init__() self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg) def _from_detection_model(self, model, nc=1000, cutoff=10): # Create a YOLOv5 classification model from a YOLOv5 detection model if isinstance(model, DetectMultiBackend): model = model.model # unwrap DetectMultiBackend model.model = model.model[:cutoff] # backbone m = model.model[-1] # last layer ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels # ch into module c = Classify(ch, nc) # Classify() c.i, c.f, c.type = m.i, m.f, 'models.common.Classify' # index, from, type model.model[-1] = c # replace self.model = model.model self.stride = model.stride self.save = [] self.nc = nc def _from_yaml(self, cfg): # Create a YOLOv5 classification model from a *.yaml file self.model = None def parse_model(d, ch): # model_dict, input_channels(3) # Parse a YOLOv5 model.yaml dictionary LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") anchors, nc, gd, gw, act = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'], d.get('activation') if act: Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU() LOGGER.info(f"{colorstr('activation:')} {act}") # print na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors no = na * (nc + 5) # number of outputs = anchors * (classes + 5) layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args m = eval(m) if isinstance(m, str) else m # eval strings for j, a in enumerate(args): with contextlib.suppress(NameError): args[j] = eval(a) if isinstance(a, str) else a # eval strings n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain if m in { Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x, DownSample}: c1, c2 = ch[f], args[0] if c2 != no: # if not output c2 = make_divisible(c2 * gw, 8) args = [c1, c2, *args[1:]] if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}: args.insert(2, n) # number of repeats n = 1 elif m is nn.BatchNorm2d: args = [ch[f]] elif m is Concat: c2 = sum(ch[x] for x in f) elif m is ScalSeq: c2 = args[0] elif m is Add: c2 = args[0] elif m is Zoom_cat: c2 = 3*args[0] elif m is attention_model: c2 = args[0] # TODO: channel, gw, gd elif m in {Detect, Segment}: args.append([ch[x] for x in f]) if isinstance(args[1], int): # number of anchors args[1] = [list(range(args[1] * 2))] * len(f) if m is Segment: args[3] = make_divisible(args[3] * gw, 8) elif m is Contract: c2 = ch[f] * args[0] ** 2 elif m is Expand: c2 = ch[f] // args[0] ** 2 else: c2 = ch[f] m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module t = str(m)[8:-2].replace('__main__.', '') # module type np = sum(x.numel() for x in m_.parameters()) # number params m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist layers.append(m_) if i == 0: ch = [] ch.append(c2) return nn.Sequential(*layers), sorted(save) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs') parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--profile', action='store_true', help='profile model speed') parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer') parser.add_argument('--test', action='store_true', help='test all yolo*.yaml') opt = parser.parse_args() opt.cfg = check_yaml(opt.cfg) # check YAML print_args(vars(opt))
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ YOLO-specific modules Usage: $ python models/yolo.py --cfg yolov5s.yaml """ FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH if platform.system() != 'Windows': ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative try: except ImportError: thop = None class Detect(nn.Module): # YOLOv5 Detect head for detection models stride = None # strides computed during build dynamic = False # force grid reconstruction export = False # export mode def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer super().__init__() self.nc = nc # number of classes self.no = nc + 5 # number of outputs per anchor self.nl = len(anchors) # number of detection layers self.na = len(anchors[0]) // 2 # number of anchors self.grid = [torch.empty(0) for _ in range(self.nl)] # init grid self.anchor_grid = [torch.empty(0) for _ in range(self.nl)] # init anchor grid self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2) self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv self.inplace = inplace # use inplace ops (e.g. slice assignment) def forward(self, x): z = [] # inference output for i in range(self.nl): x[i] = self.m[i](x[i]) # conv bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() if not self.training: # inference if self.dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]: self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i) if isinstance(self, Segment): # (boxes + masks) xy, wh, conf, mask = x[i].split((2, 2, self.nc + 1, self.no - self.nc - 5), 4) xy = (xy.sigmoid() * 2 + self.grid[i]) * self.stride[i] # xy wh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i] # wh y = torch.cat((xy, wh, conf.sigmoid(), mask), 4) else: # Detect (boxes only) xy, wh, conf = x[i].sigmoid().split((2, 2, self.nc + 1), 4) xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh y = torch.cat((xy, wh, conf), 4) z.append(y.view(bs, self.na * nx * ny, self.no)) return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x) def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, '1.10.0')): d = self.anchors[i].device t = self.anchors[i].dtype shape = 1, self.na, ny, nx, 2 # grid shape y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t) yv, xv = torch.meshgrid(y, x, indexing='ij') if torch_1_10 else torch.meshgrid(y, x) # torch>=0.7 compatibility grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5 anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape) return grid, anchor_grid class Segment(Detect): # YOLOv5 Segment head for segmentation models def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True): super().__init__(nc, anchors, ch, inplace) self.nm = nm # number of masks self.npr = npr # number of protos self.no = 5 + nc + self.nm # number of outputs per anchor self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv self.proto = Proto(ch[0], self.npr, self.nm) # protos self.detect = Detect.forward def forward(self, x): p = self.proto(x[0]) x = self.detect(self, x) return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1]) class BaseModel(nn.Module): # YOLOv5 base model def forward(self, x, profile=False, visualize=False): return self._forward_once(x, profile, visualize) # single-scale inference, train def _forward_once(self, x, profile=False, visualize=False): y, dt = [], [] # outputs for m in self.model: if m.f != -1: # if not from previous layer x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers if profile: self._profile_one_layer(m, x, dt) x = m(x) # run y.append(x if m.i in self.save else None) # save output if visualize: feature_visualization(x, m.type, m.i, save_dir=visualize) return x def _profile_one_layer(self, m, x, dt): c = m == self.model[-1] # is final layer, copy input as inplace fix o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs t = time_sync() for _ in range(10): m(x.copy() if c else x) dt.append((time_sync() - t) * 100) if m == self.model[0]: LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module") LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}') if c: LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total") def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers LOGGER.info('Fusing layers... ') for m in self.model.modules(): if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'): m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv delattr(m, 'bn') # remove batchnorm m.forward = m.forward_fuse # update forward self.info() return self def info(self, verbose=False, img_size=640): # print model information model_info(self, verbose, img_size) def _apply(self, fn): # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers self = super()._apply(fn) m = self.model[-1] # Detect() if isinstance(m, (Detect, Segment)): m.stride = fn(m.stride) m.grid = list(map(fn, m.grid)) if isinstance(m.anchor_grid, list): m.anchor_grid = list(map(fn, m.anchor_grid)) return self class DetectionModel(BaseModel): # YOLOv5 detection model def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes super().__init__() if isinstance(cfg, dict): self.yaml = cfg # model dict else: # is *.yaml self.yaml_file = Path(cfg).name with open(cfg, encoding='ascii', errors='ignore') as f: self.yaml = yaml.safe_load(f) # model dict # Define model ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels if nc and nc != self.yaml['nc']: LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") self.yaml['nc'] = nc # override yaml value if anchors: LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}') self.yaml['anchors'] = round(anchors) # override yaml value self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist self.names = [str(i) for i in range(self.yaml['nc'])] # default names self.inplace = self.yaml.get('inplace', True) # Build strides, anchors m = self.model[-1] # Detect() if isinstance(m, (Detect, Segment)): s = 256 # 2x min stride m.inplace = self.inplace forward = lambda x: self.forward(x)[0] if isinstance(m, Segment) else self.forward(x) m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))]) # forward check_anchor_order(m) m.anchors /= m.stride.view(-1, 1, 1) self.stride = m.stride self._initialize_biases() # only run once # Init weights, biases initialize_weights(self) self.info() LOGGER.info('') def forward(self, x, augment=False, profile=False, visualize=False): if augment: return self._forward_augment(x) # augmented inference, None return self._forward_once(x, profile, visualize) # single-scale inference, train def _forward_augment(self, x): img_size = x.shape[-2:] # height, width s = [1, 0.83, 0.67] # scales f = [None, 3, None] # flips (2-ud, 3-lr) y = [] # outputs for si, fi in zip(s, f): xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) yi = self._forward_once(xi)[0] # forward # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save yi = self._descale_pred(yi, fi, si, img_size) y.append(yi) y = self._clip_augmented(y) # clip augmented tails return torch.cat(y, 1), None # augmented inference, train def _descale_pred(self, p, flips, scale, img_size): # de-scale predictions following augmented inference (inverse operation) if self.inplace: p[..., :4] /= scale # de-scale if flips == 2: p[..., 1] = img_size[0] - p[..., 1] # de-flip ud elif flips == 3: p[..., 0] = img_size[1] - p[..., 0] # de-flip lr else: x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale if flips == 2: y = img_size[0] - y # de-flip ud elif flips == 3: x = img_size[1] - x # de-flip lr p = torch.cat((x, y, wh, p[..., 4:]), -1) return p def _clip_augmented(self, y): # Clip YOLOv5 augmented inference tails nl = self.model[-1].nl # number of detection layers (P3-P5) g = sum(4 ** x for x in range(nl)) # grid points e = 1 # exclude layer count i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices y[0] = y[0][:, :-i] # large i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices y[-1] = y[-1][:, i:] # small return y def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency # https://arxiv.org/abs/1708.02002 section 3.3 # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. m = self.model[-1] # Detect() module for mi, s in zip(m.m, m.stride): # from b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) b.data[:, 5:5 + m.nc] += math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum()) # cls mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) Model = DetectionModel # retain YOLOv5 'Model' class for backwards compatibility class SegmentationModel(DetectionModel): # YOLOv5 segmentation model def __init__(self, cfg='yolov5s-seg.yaml', ch=3, nc=None, anchors=None): super().__init__(cfg, ch, nc, anchors) class ClassificationModel(BaseModel): # YOLOv5 classification model def __init__(self, cfg=None, model=None, nc=1000, cutoff=10): # yaml, model, number of classes, cutoff index super().__init__() self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg) def _from_detection_model(self, model, nc=1000, cutoff=10): # Create a YOLOv5 classification model from a YOLOv5 detection model if isinstance(model, DetectMultiBackend): model = model.model # unwrap DetectMultiBackend model.model = model.model[:cutoff] # backbone m = model.model[-1] # last layer ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels # ch into module c = Classify(ch, nc) # Classify() c.i, c.f, c.type = m.i, m.f, 'models.common.Classify' # index, from, type model.model[-1] = c # replace self.model = model.model self.stride = model.stride self.save = [] self.nc = nc def _from_yaml(self, cfg): # Create a YOLOv5 classification model from a *.yaml file self.model = None def parse_model(d, ch): # model_dict, input_channels(3) # Parse a YOLOv5 model.yaml dictionary LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") anchors, nc, gd, gw, act = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'], d.get('activation') if act: Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU() LOGGER.info(f"{colorstr('activation:')} {act}") # print na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors no = na * (nc + 5) # number of outputs = anchors * (classes + 5) layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args m = eval(m) if isinstance(m, str) else m # eval strings for j, a in enumerate(args): with contextlib.suppress(NameError): args[j] = eval(a) if isinstance(a, str) else a # eval strings n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain if m in { Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x, DownSample}: c1, c2 = ch[f], args[0] if c2 != no: # if not output c2 = make_divisible(c2 * gw, 8) args = [c1, c2, *args[1:]] if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}: args.insert(2, n) # number of repeats n = 1 elif m is nn.BatchNorm2d: args = [ch[f]] elif m is Concat: c2 = sum(ch[x] for x in f) elif m is ScalSeq: c2 = args[0] elif m is Add: c2 = args[0] elif m is Zoom_cat: c2 = 3*args[0] elif m is attention_model: c2 = args[0] # TODO: channel, gw, gd elif m in {Detect, Segment}: args.append([ch[x] for x in f]) if isinstance(args[1], int): # number of anchors args[1] = [list(range(args[1] * 2))] * len(f) if m is Segment: args[3] = make_divisible(args[3] * gw, 8) elif m is Contract: c2 = ch[f] * args[0] ** 2 elif m is Expand: c2 = ch[f] // args[0] ** 2 else: c2 = ch[f] m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module t = str(m)[8:-2].replace('__main__.', '') # module type np = sum(x.numel() for x in m_.parameters()) # number params m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist layers.append(m_) if i == 0: ch = [] ch.append(c2) return nn.Sequential(*layers), sorted(save) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs') parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--profile', action='store_true', help='profile model speed') parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer') parser.add_argument('--test', action='store_true', help='test all yolo*.yaml') opt = parser.parse_args() opt.cfg = check_yaml(opt.cfg) # check YAML print_args(vars(opt))
device = select_device(opt.device)
12
2023-12-10 14:18:29+00:00
12k
ylacombe/finetune-hf-vits
convert_original_discriminator_checkpoint.py
[ { "identifier": "VitsFeatureExtractor", "path": "utils/feature_extraction_vits.py", "snippet": "class VitsFeatureExtractor(SequenceFeatureExtractor):\n r\"\"\"\n Constructs a Vits feature extractor.\n\n This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExt...
import argparse import torch from transformers.models.vits.modeling_vits import VitsModel from transformers.models.vits.tokenization_vits import VitsTokenizer from huggingface_hub import hf_hub_download from utils.feature_extraction_vits import VitsFeatureExtractor from utils.configuration_vits import VitsConfig, logging from utils.modeling_vits_training import VitsDiscriminator, VitsModelForPreTraining
8,362
"""Convert VITS discriminator checkpoint and add it to an already converted VITS checkpoint.""" logging.set_verbosity_info() logger = logging.get_logger("transformers.models.vits") MAPPING = { "conv_post": "final_conv", } TOP_LEVEL_KEYS = [] IGNORE_KEYS = [] @torch.no_grad() def convert_checkpoint( language_code, pytorch_dump_folder_path, checkpoint_path=None, generator_checkpoint_path=None, repo_id=None, ): """ Copy/paste/tweak model's weights to transformers design. """ if language_code is not None: checkpoint_path = hf_hub_download(repo_id="facebook/mms-tts", subfolder=f"full_models/{language_code}", filename="D_100000.pth") generator_checkpoint_path = f"facebook/mms-tts-{language_code}" config = VitsConfig.from_pretrained(generator_checkpoint_path) generator = VitsModel.from_pretrained(generator_checkpoint_path) discriminator = VitsDiscriminator(config) for disc in discriminator.discriminators: disc.apply_weight_norm() checkpoint = torch.load(checkpoint_path, map_location=torch.device("cpu")) # load weights state_dict = checkpoint["model"] for k, v in list(state_dict.items()): for old_layer_name in MAPPING: new_k = k.replace(old_layer_name, MAPPING[old_layer_name]) state_dict[new_k] = state_dict.pop(k) extra_keys = set(state_dict.keys()) - set(discriminator.state_dict().keys()) extra_keys = {k for k in extra_keys if not k.endswith(".attn.bias")} missing_keys = set(discriminator.state_dict().keys()) - set(state_dict.keys()) missing_keys = {k for k in missing_keys if not k.endswith(".attn.bias")} if len(extra_keys) != 0: raise ValueError(f"extra keys found: {extra_keys}") if len(missing_keys) != 0: raise ValueError(f"missing keys: {missing_keys}") discriminator.load_state_dict(state_dict, strict=False) n_params = discriminator.num_parameters(exclude_embeddings=True) logger.info(f"model loaded: {round(n_params/1e6,1)}M params") for disc in discriminator.discriminators: disc.remove_weight_norm()
"""Convert VITS discriminator checkpoint and add it to an already converted VITS checkpoint.""" logging.set_verbosity_info() logger = logging.get_logger("transformers.models.vits") MAPPING = { "conv_post": "final_conv", } TOP_LEVEL_KEYS = [] IGNORE_KEYS = [] @torch.no_grad() def convert_checkpoint( language_code, pytorch_dump_folder_path, checkpoint_path=None, generator_checkpoint_path=None, repo_id=None, ): """ Copy/paste/tweak model's weights to transformers design. """ if language_code is not None: checkpoint_path = hf_hub_download(repo_id="facebook/mms-tts", subfolder=f"full_models/{language_code}", filename="D_100000.pth") generator_checkpoint_path = f"facebook/mms-tts-{language_code}" config = VitsConfig.from_pretrained(generator_checkpoint_path) generator = VitsModel.from_pretrained(generator_checkpoint_path) discriminator = VitsDiscriminator(config) for disc in discriminator.discriminators: disc.apply_weight_norm() checkpoint = torch.load(checkpoint_path, map_location=torch.device("cpu")) # load weights state_dict = checkpoint["model"] for k, v in list(state_dict.items()): for old_layer_name in MAPPING: new_k = k.replace(old_layer_name, MAPPING[old_layer_name]) state_dict[new_k] = state_dict.pop(k) extra_keys = set(state_dict.keys()) - set(discriminator.state_dict().keys()) extra_keys = {k for k in extra_keys if not k.endswith(".attn.bias")} missing_keys = set(discriminator.state_dict().keys()) - set(state_dict.keys()) missing_keys = {k for k in missing_keys if not k.endswith(".attn.bias")} if len(extra_keys) != 0: raise ValueError(f"extra keys found: {extra_keys}") if len(missing_keys) != 0: raise ValueError(f"missing keys: {missing_keys}") discriminator.load_state_dict(state_dict, strict=False) n_params = discriminator.num_parameters(exclude_embeddings=True) logger.info(f"model loaded: {round(n_params/1e6,1)}M params") for disc in discriminator.discriminators: disc.remove_weight_norm()
model = VitsModelForPreTraining(config)
3
2023-12-11 17:56:49+00:00
12k
youngskkim/CRN
exps/det/BEVDepth_r50_256x704_128x128_4key.py
[ { "identifier": "synchronize", "path": "utils/torch_dist.py", "snippet": "def synchronize():\n \"\"\"Helper function to synchronize (barrier)\n among all processes when using distributed training\"\"\"\n if not dist.is_available():\n return\n if not dist.is_initialized():\n ...
import torch from utils.torch_dist import synchronize from exps.base_cli import run_cli from exps.base_exp import BEVDepthLightningModel as BaseBEVDepthLightningModel from models.base_bev_depth import BaseBEVDepth
8,503
depth=18, num_stages=3, strides=(1, 2, 2), dilations=(1, 1, 1), out_indices=[0, 1, 2], norm_eval=False, base_channels=160, ), 'bev_neck_conf': dict( type='SECONDFPN', in_channels=[80, 160, 320, 640], upsample_strides=[1, 2, 4, 8], out_channels=[64, 64, 64, 64] ), 'tasks': [ dict(num_class=1, class_names=['car']), dict(num_class=2, class_names=['truck', 'construction_vehicle']), dict(num_class=2, class_names=['bus', 'trailer']), dict(num_class=1, class_names=['barrier']), dict(num_class=2, class_names=['motorcycle', 'bicycle']), dict(num_class=2, class_names=['pedestrian', 'traffic_cone']), ], 'common_heads': dict( reg=(2, 2), height=(1, 2), dim=(3, 2), rot=(2, 2), vel=(2, 2)), 'bbox_coder': dict( type='CenterPointBBoxCoder', post_center_range=[-61.2, -61.2, -10.0, 61.2, 61.2, 10.0], max_num=500, score_threshold=0.01, out_size_factor=4, voxel_size=[0.2, 0.2, 8], pc_range=[-51.2, -51.2, -5, 51.2, 51.2, 3], code_size=9, ), 'train_cfg': dict( point_cloud_range=[-51.2, -51.2, -5, 51.2, 51.2, 3], grid_size=[512, 512, 1], voxel_size=[0.2, 0.2, 8], out_size_factor=4, dense_reg=1, gaussian_overlap=0.1, max_objs=500, min_radius=2, code_weights=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], ), 'test_cfg': dict( post_center_limit_range=[-61.2, -61.2, -10.0, 61.2, 61.2, 10.0], max_per_img=500, max_pool_nms=False, min_radius=[4, 12, 10, 1, 0.85, 0.175], score_threshold=0.01, out_size_factor=4, voxel_size=[0.2, 0.2, 8], nms_type='circle', pre_max_size=1000, post_max_size=200, nms_thr=0.2, ), 'in_channels': 256, # Equal to bev_neck output_channels. 'loss_cls': dict(type='GaussianFocalLoss', reduction='mean'), 'loss_bbox': dict(type='L1Loss', reduction='mean', loss_weight=0.25), 'gaussian_overlap': 0.1, 'min_radius': 2, } ################################################ self.key_idxes = [-2, -4, -6] self.head_conf['bev_backbone_conf']['in_channels'] = 80 * ( len(self.key_idxes) + 1) self.head_conf['bev_neck_conf']['in_channels'] = [ 80 * (len(self.key_idxes) + 1), 160, 320, 640 ] self.dbound = self.backbone_img_conf['d_bound'] self.depth_channels = int( (self.dbound[1] - self.dbound[0]) / self.dbound[2]) self.model = BaseBEVDepth(self.backbone_img_conf, self.head_conf) def forward(self, sweep_imgs, mats, is_train=False, **inputs): return self.model(sweep_imgs, mats, is_train=is_train) def training_step(self, batch): if self.global_rank == 0: for pg in self.trainer.optimizers[0].param_groups: self.log('learning_rate', pg["lr"]) (sweep_imgs, mats, _, gt_boxes_3d, gt_labels_3d, _, depth_labels, _) = batch if torch.cuda.is_available(): if self.return_image: sweep_imgs = sweep_imgs.cuda() for key, value in mats.items(): mats[key] = value.cuda() gt_boxes_3d = [gt_box.cuda() for gt_box in gt_boxes_3d] gt_labels_3d = [gt_label.cuda() for gt_label in gt_labels_3d] preds, depth_preds = self(sweep_imgs, mats, is_train=True) targets = self.model.get_targets(gt_boxes_3d, gt_labels_3d) loss_detection, loss_heatmap, loss_bbox = self.model.loss(targets, preds) if len(depth_labels.shape) == 5: # only key-frame will calculate depth loss depth_labels = depth_labels[:, 0, ...].contiguous() loss_depth = self.get_depth_loss(depth_labels.cuda(), depth_preds, weight=3.) self.log('train/detection', loss_detection) self.log('train/heatmap', loss_heatmap) self.log('train/bbox', loss_bbox) self.log('train/depth', loss_depth) return loss_detection + loss_depth def validation_epoch_end(self, validation_step_outputs): detection_losses = list() heatmap_losses = list() bbox_losses = list() depth_losses = list() for validation_step_output in validation_step_outputs: detection_losses.append(validation_step_output[0]) heatmap_losses.append(validation_step_output[1]) bbox_losses.append(validation_step_output[2]) depth_losses.append(validation_step_output[3])
# Copyright (c) Megvii Inc. All rights reserved. """ mAP: 0.3672 mATE: 0.6827 mASE: 0.2833 mAOE: 0.5354 mAVE: 0.4156 mAAE: 0.2066 NDS: 0.4712 Eval time: 199.7s Per-class results: Object Class AP ATE ASE AOE AVE AAE car 0.540 0.488 0.165 0.153 0.493 0.216 truck 0.302 0.707 0.225 0.182 0.380 0.202 bus 0.387 0.722 0.224 0.121 0.755 0.302 trailer 0.176 1.071 0.255 0.516 0.268 0.086 construction_vehicle 0.103 1.061 0.522 1.298 0.127 0.353 pedestrian 0.310 0.745 0.290 0.829 0.465 0.253 motorcycle 0.390 0.624 0.257 0.691 0.654 0.232 bicycle 0.379 0.494 0.268 0.828 0.183 0.009 traffic_cone 0.516 0.487 0.347 nan nan nan barrier 0.568 0.426 0.280 0.202 nan nan img: 24.63 img_backbone: 11.21 img_dep: 6.67 img_transform: 5.11 img_pool: 0.99 head: 9.04 head_backbone: 3.10 head_head: 5.94 total: 33.68 FPS: 29.70 | Name | Type | Params ----------------------------------------------------------------------- 0 | model | BaseBEVDepth | 77.6 M 1 | model.backbone_img | BaseLSSFPN | 53.3 M 2 | model.backbone_img.img_backbone | ResNet | 23.5 M 3 | model.backbone_img.img_neck | SECONDFPN | 2.0 M 4 | model.backbone_img.depth_net | DepthNet | 27.8 M 5 | model.head | BEVDepthHead | 24.4 M 6 | model.head.loss_cls | GaussianFocalLoss | 0 7 | model.head.loss_bbox | L1Loss | 0 8 | model.head.shared_conv | ConvModule | 147 K 9 | model.head.task_heads | ModuleList | 1.4 M 10 | model.head.trunk | ResNet | 19.8 M 11 | model.head.neck | SECONDFPN | 3.0 M ----------------------------------------------------------------------- """ class BEVDepthLightningModel(BaseBEVDepthLightningModel): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.return_image = True self.return_depth = True self.return_radar_pv = False ################################################ self.optimizer_config = dict( type='AdamW', lr=2e-4, weight_decay=1e-4) ################################################ self.ida_aug_conf = { 'resize_lim': (0.386, 0.55), 'final_dim': (256, 704), 'rot_lim': (-5.4, 5.4), 'H': 900, 'W': 1600, 'rand_flip': True, 'bot_pct_lim': (0.0, 0.0), 'cams': [ 'CAM_FRONT_LEFT', 'CAM_FRONT', 'CAM_FRONT_RIGHT', 'CAM_BACK_LEFT', 'CAM_BACK', 'CAM_BACK_RIGHT' ], 'Ncams': 6, } self.bda_aug_conf = { 'rot_ratio': 1.0, 'rot_lim': (-22.5, 22.5), 'scale_lim': (0.95, 1.05), 'flip_dx_ratio': 0.5, 'flip_dy_ratio': 0.5 } ################################################ self.backbone_img_conf = { 'x_bound': [-51.2, 51.2, 0.8], 'y_bound': [-51.2, 51.2, 0.8], 'z_bound': [-5, 3, 8], 'd_bound': [2.0, 58.0, 0.5], 'final_dim': (256, 704), 'downsample_factor': 16, 'img_backbone_conf': dict( type='ResNet', depth=50, frozen_stages=0, out_indices=[0, 1, 2, 3], norm_eval=False, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), ), 'img_neck_conf': dict( type='SECONDFPN', in_channels=[256, 512, 1024, 2048], upsample_strides=[0.25, 0.5, 1, 2], out_channels=[128, 128, 128, 128], ), 'depth_net_conf': dict(in_channels=512, mid_channels=512), 'camera_aware': True, 'output_channels': 80, } ################################################ self.head_conf = { 'bev_backbone_conf': dict( type='ResNet', in_channels=128, depth=18, num_stages=3, strides=(1, 2, 2), dilations=(1, 1, 1), out_indices=[0, 1, 2], norm_eval=False, base_channels=160, ), 'bev_neck_conf': dict( type='SECONDFPN', in_channels=[80, 160, 320, 640], upsample_strides=[1, 2, 4, 8], out_channels=[64, 64, 64, 64] ), 'tasks': [ dict(num_class=1, class_names=['car']), dict(num_class=2, class_names=['truck', 'construction_vehicle']), dict(num_class=2, class_names=['bus', 'trailer']), dict(num_class=1, class_names=['barrier']), dict(num_class=2, class_names=['motorcycle', 'bicycle']), dict(num_class=2, class_names=['pedestrian', 'traffic_cone']), ], 'common_heads': dict( reg=(2, 2), height=(1, 2), dim=(3, 2), rot=(2, 2), vel=(2, 2)), 'bbox_coder': dict( type='CenterPointBBoxCoder', post_center_range=[-61.2, -61.2, -10.0, 61.2, 61.2, 10.0], max_num=500, score_threshold=0.01, out_size_factor=4, voxel_size=[0.2, 0.2, 8], pc_range=[-51.2, -51.2, -5, 51.2, 51.2, 3], code_size=9, ), 'train_cfg': dict( point_cloud_range=[-51.2, -51.2, -5, 51.2, 51.2, 3], grid_size=[512, 512, 1], voxel_size=[0.2, 0.2, 8], out_size_factor=4, dense_reg=1, gaussian_overlap=0.1, max_objs=500, min_radius=2, code_weights=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], ), 'test_cfg': dict( post_center_limit_range=[-61.2, -61.2, -10.0, 61.2, 61.2, 10.0], max_per_img=500, max_pool_nms=False, min_radius=[4, 12, 10, 1, 0.85, 0.175], score_threshold=0.01, out_size_factor=4, voxel_size=[0.2, 0.2, 8], nms_type='circle', pre_max_size=1000, post_max_size=200, nms_thr=0.2, ), 'in_channels': 256, # Equal to bev_neck output_channels. 'loss_cls': dict(type='GaussianFocalLoss', reduction='mean'), 'loss_bbox': dict(type='L1Loss', reduction='mean', loss_weight=0.25), 'gaussian_overlap': 0.1, 'min_radius': 2, } ################################################ self.key_idxes = [-2, -4, -6] self.head_conf['bev_backbone_conf']['in_channels'] = 80 * ( len(self.key_idxes) + 1) self.head_conf['bev_neck_conf']['in_channels'] = [ 80 * (len(self.key_idxes) + 1), 160, 320, 640 ] self.dbound = self.backbone_img_conf['d_bound'] self.depth_channels = int( (self.dbound[1] - self.dbound[0]) / self.dbound[2]) self.model = BaseBEVDepth(self.backbone_img_conf, self.head_conf) def forward(self, sweep_imgs, mats, is_train=False, **inputs): return self.model(sweep_imgs, mats, is_train=is_train) def training_step(self, batch): if self.global_rank == 0: for pg in self.trainer.optimizers[0].param_groups: self.log('learning_rate', pg["lr"]) (sweep_imgs, mats, _, gt_boxes_3d, gt_labels_3d, _, depth_labels, _) = batch if torch.cuda.is_available(): if self.return_image: sweep_imgs = sweep_imgs.cuda() for key, value in mats.items(): mats[key] = value.cuda() gt_boxes_3d = [gt_box.cuda() for gt_box in gt_boxes_3d] gt_labels_3d = [gt_label.cuda() for gt_label in gt_labels_3d] preds, depth_preds = self(sweep_imgs, mats, is_train=True) targets = self.model.get_targets(gt_boxes_3d, gt_labels_3d) loss_detection, loss_heatmap, loss_bbox = self.model.loss(targets, preds) if len(depth_labels.shape) == 5: # only key-frame will calculate depth loss depth_labels = depth_labels[:, 0, ...].contiguous() loss_depth = self.get_depth_loss(depth_labels.cuda(), depth_preds, weight=3.) self.log('train/detection', loss_detection) self.log('train/heatmap', loss_heatmap) self.log('train/bbox', loss_bbox) self.log('train/depth', loss_depth) return loss_detection + loss_depth def validation_epoch_end(self, validation_step_outputs): detection_losses = list() heatmap_losses = list() bbox_losses = list() depth_losses = list() for validation_step_output in validation_step_outputs: detection_losses.append(validation_step_output[0]) heatmap_losses.append(validation_step_output[1]) bbox_losses.append(validation_step_output[2]) depth_losses.append(validation_step_output[3])
synchronize()
0
2023-12-06 14:57:49+00:00
12k
LIU-Yuxin/SyncMVD
src/pipeline.py
[ { "identifier": "UVProjection", "path": "src/renderer/project.py", "snippet": "class UVProjection():\n\tdef __init__(self, texture_size=96, render_size=64, sampling_mode=\"nearest\", channels=3, device=None):\n\t\tself.channels = channels\n\t\tself.device = device or torch.device(\"cpu\")\n\t\tself.ligh...
import os import numpy as np import math import random import torch import select import sys from typing import Any, Callable, Dict, List, Optional, Tuple, Union from PIL import Image from IPython.display import display from torch import functional as F from torch import nn from torchvision.transforms import Compose, Resize, GaussianBlur, InterpolationMode from diffusers import StableDiffusionControlNetPipeline, ControlNetModel from diffusers import DDPMScheduler, DDIMScheduler, UniPCMultistepScheduler from diffusers.models import AutoencoderKL, ControlNetModel, UNet2DConditionModel from diffusers.schedulers import KarrasDiffusionSchedulers from diffusers.image_processor import VaeImageProcessor from diffusers.utils import ( BaseOutput, randn_tensor, numpy_to_pil, pt_to_pil, # make_image_grid, is_accelerate_available, is_accelerate_version, is_compiled_module, logging, randn_tensor, replace_example_docstring ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.models.attention_processor import Attention, AttentionProcessor from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from .renderer.project import UVProjection as UVP from .syncmvd.attention import SamplewiseAttnProcessor2_0, replace_attention_processors from .syncmvd.prompt import * from .syncmvd.step import step_tex from .utils import *
10,786
group_sets.append((group, ref_group)) group_metas = [] for group, ref_group in group_sets: in_mask = sorted(list(group | ref_group)) out_mask = [] group_attention_masks = [] for idx in in_mask: if idx in group: out_mask.append(in_mask.index(idx)) group_attention_masks.append([in_mask.index(idxx) for idxx in attention_mask[idx] if idxx in in_mask]) ref_attention_mask = [in_mask.index(idx) for idx in ref_view] group_metas.append([in_mask, out_mask, group_attention_masks, ref_attention_mask]) return group_metas ''' MultiView-Diffusion Stable-Diffusion Pipeline Modified from a Diffusers StableDiffusionControlNetPipeline Just mimic the pipeline structure but did not follow any API convention ''' class StableSyncMVDPipeline(StableDiffusionControlNetPipeline): def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel]], scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessor, requires_safety_checker: bool = False, ): super().__init__( vae, text_encoder, tokenizer, unet, controlnet, scheduler, safety_checker, feature_extractor, requires_safety_checker ) self.scheduler = DDPMScheduler.from_config(self.scheduler.config) self.model_cpu_offload_seq = "vae->text_encoder->unet->vae" self.enable_model_cpu_offload() self.enable_vae_slicing() self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor) def initialize_pipeline( self, mesh_path=None, mesh_transform=None, mesh_autouv=None, camera_azims=None, camera_centers=None, top_cameras=True, ref_views=[], latent_size=None, render_rgb_size=None, texture_size=None, texture_rgb_size=None, max_batch_size=24, logging_config=None, ): # Make output dir output_dir = logging_config["output_dir"] self.result_dir = f"{output_dir}/results" self.intermediate_dir = f"{output_dir}/intermediate" dirs = [output_dir, self.result_dir, self.intermediate_dir] for dir_ in dirs: if not os.path.isdir(dir_): os.mkdir(dir_) # Define the cameras for rendering self.camera_poses = [] self.attention_mask=[] self.centers = camera_centers cam_count = len(camera_azims) front_view_diff = 360 back_view_diff = 360 front_view_idx = 0 back_view_idx = 0 for i, azim in enumerate(camera_azims): if azim < 0: azim += 360 self.camera_poses.append((0, azim)) self.attention_mask.append([(cam_count+i-1)%cam_count, i, (i+1)%cam_count]) if abs(azim) < front_view_diff: front_view_idx = i front_view_diff = abs(azim) if abs(azim - 180) < back_view_diff: back_view_idx = i back_view_diff = abs(azim - 180) # Add two additional cameras for painting the top surfaces if top_cameras: self.camera_poses.append((30, 0)) self.camera_poses.append((30, 180)) self.attention_mask.append([front_view_idx, cam_count]) self.attention_mask.append([back_view_idx, cam_count+1]) # Reference view for attention (all views attend the the views in this list) # A forward view will be used if not specified if len(ref_views) == 0: ref_views = [front_view_idx] # Calculate in-group attention mask self.group_metas = split_groups(self.attention_mask, max_batch_size, ref_views) # Set up pytorch3D for projection between screen space and UV space # uvp is for latent and uvp_rgb for rgb color
if torch.cuda.is_available(): device = torch.device("cuda:0") torch.cuda.set_device(device) else: device = torch.device("cpu") # Background colors color_constants = {"black": [-1, -1, -1], "white": [1, 1, 1], "maroon": [0, -1, -1], "red": [1, -1, -1], "olive": [0, 0, -1], "yellow": [1, 1, -1], "green": [-1, 0, -1], "lime": [-1 ,1, -1], "teal": [-1, 0, 0], "aqua": [-1, 1, 1], "navy": [-1, -1, 0], "blue": [-1, -1, 1], "purple": [0, -1 , 0], "fuchsia": [1, -1, 1]} color_names = list(color_constants.keys()) # Used to generate depth or normal conditioning images @torch.no_grad() def get_conditioning_images(uvp, output_size, render_size=512, blur_filter=5, cond_type="normal"): verts, normals, depths, cos_maps, texels, fragments = uvp.render_geometry(image_size=render_size) masks = normals[...,3][:,None,...] masks = Resize((output_size//8,)*2, antialias=True)(masks) normals_transforms = Compose([ Resize((output_size,)*2, interpolation=InterpolationMode.BILINEAR, antialias=True), GaussianBlur(blur_filter, blur_filter//3+1)] ) if cond_type == "normal": view_normals = uvp.decode_view_normal(normals).permute(0,3,1,2) *2 - 1 conditional_images = normals_transforms(view_normals) # Some problem here, depth controlnet don't work when depth is normalized # But it do generate using the unnormalized form as below elif cond_type == "depth": view_depths = uvp.decode_normalized_depth(depths).permute(0,3,1,2) conditional_images = normals_transforms(view_depths) return conditional_images, masks # Revert time 0 background to time t to composite with time t foreground @torch.no_grad() def composite_rendered_view(scheduler, backgrounds, foregrounds, masks, t): composited_images = [] for i, (background, foreground, mask) in enumerate(zip(backgrounds, foregrounds, masks)): if t > 0: alphas_cumprod = scheduler.alphas_cumprod[t] noise = torch.normal(0, 1, background.shape, device=background.device) background = (1-alphas_cumprod) * noise + alphas_cumprod * background composited = foreground * mask + background * (1-mask) composited_images.append(composited) composited_tensor = torch.stack(composited_images) return composited_tensor # Split into micro-batches to use less memory in each unet prediction # But need more investigation on reducing memory usage # Assume it has no possitive effect and use a large "max_batch_size" to skip splitting def split_groups(attention_mask, max_batch_size, ref_view=[]): group_sets = [] group = set() ref_group = set() idx = 0 while idx < len(attention_mask): new_group = group | set([idx]) new_ref_group = (ref_group | set(attention_mask[idx] + ref_view)) - new_group if len(new_group) + len(new_ref_group) <= max_batch_size: group = new_group ref_group = new_ref_group idx += 1 else: assert len(group) != 0, "Cannot fit into a group" group_sets.append((group, ref_group)) group = set() ref_group = set() if len(group)>0: group_sets.append((group, ref_group)) group_metas = [] for group, ref_group in group_sets: in_mask = sorted(list(group | ref_group)) out_mask = [] group_attention_masks = [] for idx in in_mask: if idx in group: out_mask.append(in_mask.index(idx)) group_attention_masks.append([in_mask.index(idxx) for idxx in attention_mask[idx] if idxx in in_mask]) ref_attention_mask = [in_mask.index(idx) for idx in ref_view] group_metas.append([in_mask, out_mask, group_attention_masks, ref_attention_mask]) return group_metas ''' MultiView-Diffusion Stable-Diffusion Pipeline Modified from a Diffusers StableDiffusionControlNetPipeline Just mimic the pipeline structure but did not follow any API convention ''' class StableSyncMVDPipeline(StableDiffusionControlNetPipeline): def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel]], scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessor, requires_safety_checker: bool = False, ): super().__init__( vae, text_encoder, tokenizer, unet, controlnet, scheduler, safety_checker, feature_extractor, requires_safety_checker ) self.scheduler = DDPMScheduler.from_config(self.scheduler.config) self.model_cpu_offload_seq = "vae->text_encoder->unet->vae" self.enable_model_cpu_offload() self.enable_vae_slicing() self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor) def initialize_pipeline( self, mesh_path=None, mesh_transform=None, mesh_autouv=None, camera_azims=None, camera_centers=None, top_cameras=True, ref_views=[], latent_size=None, render_rgb_size=None, texture_size=None, texture_rgb_size=None, max_batch_size=24, logging_config=None, ): # Make output dir output_dir = logging_config["output_dir"] self.result_dir = f"{output_dir}/results" self.intermediate_dir = f"{output_dir}/intermediate" dirs = [output_dir, self.result_dir, self.intermediate_dir] for dir_ in dirs: if not os.path.isdir(dir_): os.mkdir(dir_) # Define the cameras for rendering self.camera_poses = [] self.attention_mask=[] self.centers = camera_centers cam_count = len(camera_azims) front_view_diff = 360 back_view_diff = 360 front_view_idx = 0 back_view_idx = 0 for i, azim in enumerate(camera_azims): if azim < 0: azim += 360 self.camera_poses.append((0, azim)) self.attention_mask.append([(cam_count+i-1)%cam_count, i, (i+1)%cam_count]) if abs(azim) < front_view_diff: front_view_idx = i front_view_diff = abs(azim) if abs(azim - 180) < back_view_diff: back_view_idx = i back_view_diff = abs(azim - 180) # Add two additional cameras for painting the top surfaces if top_cameras: self.camera_poses.append((30, 0)) self.camera_poses.append((30, 180)) self.attention_mask.append([front_view_idx, cam_count]) self.attention_mask.append([back_view_idx, cam_count+1]) # Reference view for attention (all views attend the the views in this list) # A forward view will be used if not specified if len(ref_views) == 0: ref_views = [front_view_idx] # Calculate in-group attention mask self.group_metas = split_groups(self.attention_mask, max_batch_size, ref_views) # Set up pytorch3D for projection between screen space and UV space # uvp is for latent and uvp_rgb for rgb color
self.uvp = UVP(texture_size=texture_size, render_size=latent_size, sampling_mode="nearest", channels=4, device=self._execution_device)
0
2023-12-09 03:27:58+00:00
12k
jinxixiang/magic_animate_unofficial
animatediff/magic_animate/unet.py
[ { "identifier": "CrossAttnDownBlock3D", "path": "animatediff/magic_animate/unet_3d_blocks.py", "snippet": "class CrossAttnDownBlock3D(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n temb_channels: int,\n dropout: float = 0.0,\n ...
from dataclasses import dataclass from typing import List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.models.modeling_utils import ModelMixin from diffusers.utils import BaseOutput, logging from diffusers.models.embeddings import TimestepEmbedding, Timesteps from .unet_3d_blocks import ( CrossAttnDownBlock3D, CrossAttnUpBlock3D, DownBlock3D, UNetMidBlock3DCrossAttn, UpBlock3D, get_down_block, get_up_block, ) from .resnet import InflatedConv3d from diffusers.utils import WEIGHTS_NAME import os import json import pdb import torch import torch.nn as nn import torch.utils.checkpoint
9,127
# up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_attention_head_dim = list(reversed(attention_head_dim)) only_cross_attention = list(reversed(only_cross_attention)) output_channel = reversed_block_out_channels[0] for i, up_block_type in enumerate(up_block_types): res = 2 ** (3 - i) is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False up_block = get_up_block( up_block_type, num_layers=layers_per_block + 1, in_channels=input_channel, out_channels=output_channel, prev_output_channel=prev_output_channel, temb_channels=time_embed_dim, add_upsample=add_upsample, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=reversed_attention_head_dim[i], dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and (res in motion_module_resolutions), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps) self.conv_act = nn.SiLU() self.conv_out = InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1) def set_attention_slice(self, slice_size): r""" Enable sliced attention computation. When this option is enabled, the attention module will split the input tensor in slices, to compute attention in several steps. This is useful to save some memory in exchange for a small speed decrease. Args: slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim` must be a multiple of `slice_size`. """ sliceable_head_dims = [] def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module): if hasattr(module, "set_attention_slice"): sliceable_head_dims.append(module.sliceable_head_dim) for child in module.children(): fn_recursive_retrieve_slicable_dims(child) # retrieve number of attention layers for module in self.children(): fn_recursive_retrieve_slicable_dims(module) num_slicable_layers = len(sliceable_head_dims) if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory slice_size = [dim // 2 for dim in sliceable_head_dims] elif slice_size == "max": # make smallest slice possible slice_size = num_slicable_layers * [1] slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size if len(slice_size) != len(sliceable_head_dims): raise ValueError( f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different" f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}." ) for i in range(len(slice_size)): size = slice_size[i] dim = sliceable_head_dims[i] if size is not None and size > dim: raise ValueError(f"size {size} has to be smaller or equal to {dim}.") # Recursively walk through all the children. # Any children which exposes the set_attention_slice method # gets the message def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]): if hasattr(module, "set_attention_slice"): module.set_attention_slice(slice_size.pop()) for child in module.children(): fn_recursive_set_attention_slice(child, slice_size) reversed_slice_size = list(reversed(slice_size)) for module in self.children(): fn_recursive_set_attention_slice(module, reversed_slice_size) def _set_gradient_checkpointing(self, module, value=False):
# ************************************************************************* # This file may have been modified by Bytedance Inc. (“Bytedance Inc.'s Mo- # difications”). All Bytedance Inc.'s Modifications are Copyright (2023) B- # ytedance Inc.. # ************************************************************************* # Adapted from https://github.com/guoyww/AnimateDiff # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): sample: torch.FloatTensor class UNet3DConditionModel(ModelMixin, ConfigMixin): _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D", ), mid_block_type: str = "UNetMidBlock3DCrossAttn", up_block_types: Tuple[str] = ( "UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D" ), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", # Additional use_motion_module = False, motion_module_resolutions = ( 1,2,4,8 ), motion_module_mid_block = False, motion_module_decoder_only = False, motion_module_type = None, motion_module_kwargs = {}, unet_use_cross_frame_attention = None, unet_use_temporal_attention = None, ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block, in_channels=input_channel, out_channels=output_channel, temb_channels=time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock3DCrossAttn": self.mid_block = UNetMidBlock3DCrossAttn( in_channels=block_out_channels[-1], temb_channels=time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, resnet_time_scale_shift=resnet_time_scale_shift, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[-1], resnet_groups=norm_num_groups, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, upcast_attention=upcast_attention, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and motion_module_mid_block, motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) else: raise ValueError(f"unknown mid_block_type : {mid_block_type}") # count how many layers upsample the videos self.num_upsamplers = 0 # up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_attention_head_dim = list(reversed(attention_head_dim)) only_cross_attention = list(reversed(only_cross_attention)) output_channel = reversed_block_out_channels[0] for i, up_block_type in enumerate(up_block_types): res = 2 ** (3 - i) is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False up_block = get_up_block( up_block_type, num_layers=layers_per_block + 1, in_channels=input_channel, out_channels=output_channel, prev_output_channel=prev_output_channel, temb_channels=time_embed_dim, add_upsample=add_upsample, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=reversed_attention_head_dim[i], dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and (res in motion_module_resolutions), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps) self.conv_act = nn.SiLU() self.conv_out = InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1) def set_attention_slice(self, slice_size): r""" Enable sliced attention computation. When this option is enabled, the attention module will split the input tensor in slices, to compute attention in several steps. This is useful to save some memory in exchange for a small speed decrease. Args: slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim` must be a multiple of `slice_size`. """ sliceable_head_dims = [] def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module): if hasattr(module, "set_attention_slice"): sliceable_head_dims.append(module.sliceable_head_dim) for child in module.children(): fn_recursive_retrieve_slicable_dims(child) # retrieve number of attention layers for module in self.children(): fn_recursive_retrieve_slicable_dims(module) num_slicable_layers = len(sliceable_head_dims) if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory slice_size = [dim // 2 for dim in sliceable_head_dims] elif slice_size == "max": # make smallest slice possible slice_size = num_slicable_layers * [1] slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size if len(slice_size) != len(sliceable_head_dims): raise ValueError( f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different" f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}." ) for i in range(len(slice_size)): size = slice_size[i] dim = sliceable_head_dims[i] if size is not None and size > dim: raise ValueError(f"size {size} has to be smaller or equal to {dim}.") # Recursively walk through all the children. # Any children which exposes the set_attention_slice method # gets the message def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]): if hasattr(module, "set_attention_slice"): module.set_attention_slice(slice_size.pop()) for child in module.children(): fn_recursive_set_attention_slice(child, slice_size) reversed_slice_size = list(reversed(slice_size)) for module in self.children(): fn_recursive_set_attention_slice(module, reversed_slice_size) def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):
0
2023-12-12 00:16:39+00:00
12k
Chat-3D/Chat-3D-v2
others/process_vil3dref_results.py
[ { "identifier": "Chat3D", "path": "models/chat3d.py", "snippet": "class Chat3D(nn.Module):\n \"\"\"\n VideoChat model.\n \"\"\"\n def __init__(self, config):\n super().__init__()\n llama_model_path = config.get(\"llama_model_path\")\n low_resource = config.get(\"low_reso...
import json import jsonlines import math import torch import sys import torch from models.chat3d import Chat3D from utils.config_utils import setup_main from tasks.shared_utils import setup_model from utils.basic_utils import setup_seed from utils.distributed import get_rank from dataset.base_dataset import process_batch_data from tqdm import tqdm
9,435
""" loss/og3d: 2.9594, loss/obj3d_clf: 3.3753, loss/obj3d_clf_pre: 2.0714, loss/txt_clf: 0.6708, loss/total: 10.2789, loss/cross_attn_0: 0.0032, loss/cross_attn_1: 0.0011, loss/cross_attn_2: 0.0011, loss/cross_attn_3: 0.0012, loss/self_attn_0: 0.1595, loss/self_attn_1: 0.0425, loss/self_attn_2: 0.0541, loss/self_attn_3: 0.1030, loss/hidden_state_0: 0.3919, loss/hidden_state_1: 0.0765, loss/hidden_state_2: 0.1033, loss/hidden_state_3: 0.1308, loss/hidden_state_4: 0.1337, acc/og3d: 0.6373, acc/og3d_class: 0.8903, acc/obj3d_clf: 0.6828, acc/obj3d_clf_pre: 0.6131, acc/txt_clf: 0.9281 """ val_file = "/root/scene-LLaMA/datasets/exprs_neurips22/gtlabelpcd_mix/nr3d/preds/val_outs.json" nr3d_anno_file = "/root/scene-LLaMA/datasets/referit3d/annotations/bert_tokenized/nr3d.jsonl" anno_root = "annotations" # annotation dir attribute_file = f"{anno_root}/scannet_attributes_old.json" attributes = json.load(open(attribute_file, 'r')) val_results = json.load(open(val_file)) nr3d_anno = {} with jsonlines.open(nr3d_anno_file, "r") as reader: for l in reader: nr3d_anno[l["item_id"]] = l item_list = [] acc = 0 for k, v in val_results.items(): obj_ids = v["obj_ids"] obj_logits = v["obj_logits"] obj_logits = (torch.tensor(obj_logits)).softmax(dim=-1).tolist() scan_id = nr3d_anno[k]["scan_id"] utter = nr3d_anno[k]["utterance"] target_id = nr3d_anno[k]["target_id"] obj_num = len(attributes[scan_id]["locs"]) assert target_id < obj_num, f"{obj_num}, {target_id}, {scan_id}" logit_ids = zip(obj_logits, obj_ids) logit_ids = sorted(logit_ids, reverse=True) logits, ids = zip(*logit_ids) # logits = (torch.tensor(logits[:5]) / 5.).softmax(dim=-1).tolist() print(logits) if ids[0] == target_id: acc += 1 item_list.append({ "can_ids": ids[:5], "can_preds": logits[:5], "utter": utter, "target_id": target_id, "scan_id": scan_id }) # print(target_id) # print(ids[:5]) # print(logits[:5]) # exit() print("Acc:", float(acc) / len(item_list)) # print(item_list[:5]) # exit() sys.path.append(".")
""" loss/og3d: 2.9594, loss/obj3d_clf: 3.3753, loss/obj3d_clf_pre: 2.0714, loss/txt_clf: 0.6708, loss/total: 10.2789, loss/cross_attn_0: 0.0032, loss/cross_attn_1: 0.0011, loss/cross_attn_2: 0.0011, loss/cross_attn_3: 0.0012, loss/self_attn_0: 0.1595, loss/self_attn_1: 0.0425, loss/self_attn_2: 0.0541, loss/self_attn_3: 0.1030, loss/hidden_state_0: 0.3919, loss/hidden_state_1: 0.0765, loss/hidden_state_2: 0.1033, loss/hidden_state_3: 0.1308, loss/hidden_state_4: 0.1337, acc/og3d: 0.6373, acc/og3d_class: 0.8903, acc/obj3d_clf: 0.6828, acc/obj3d_clf_pre: 0.6131, acc/txt_clf: 0.9281 """ val_file = "/root/scene-LLaMA/datasets/exprs_neurips22/gtlabelpcd_mix/nr3d/preds/val_outs.json" nr3d_anno_file = "/root/scene-LLaMA/datasets/referit3d/annotations/bert_tokenized/nr3d.jsonl" anno_root = "annotations" # annotation dir attribute_file = f"{anno_root}/scannet_attributes_old.json" attributes = json.load(open(attribute_file, 'r')) val_results = json.load(open(val_file)) nr3d_anno = {} with jsonlines.open(nr3d_anno_file, "r") as reader: for l in reader: nr3d_anno[l["item_id"]] = l item_list = [] acc = 0 for k, v in val_results.items(): obj_ids = v["obj_ids"] obj_logits = v["obj_logits"] obj_logits = (torch.tensor(obj_logits)).softmax(dim=-1).tolist() scan_id = nr3d_anno[k]["scan_id"] utter = nr3d_anno[k]["utterance"] target_id = nr3d_anno[k]["target_id"] obj_num = len(attributes[scan_id]["locs"]) assert target_id < obj_num, f"{obj_num}, {target_id}, {scan_id}" logit_ids = zip(obj_logits, obj_ids) logit_ids = sorted(logit_ids, reverse=True) logits, ids = zip(*logit_ids) # logits = (torch.tensor(logits[:5]) / 5.).softmax(dim=-1).tolist() print(logits) if ids[0] == target_id: acc += 1 item_list.append({ "can_ids": ids[:5], "can_preds": logits[:5], "utter": utter, "target_id": target_id, "scan_id": scan_id }) # print(target_id) # print(ids[:5]) # print(logits[:5]) # exit() print("Acc:", float(acc) / len(item_list)) # print(item_list[:5]) # exit() sys.path.append(".")
config = setup_main()
1
2023-12-11 14:39:58+00:00
12k
SqueezeBits/owlite
owlite/backend/onnx/transforms.py
[ { "identifier": "log", "path": "owlite/logger.py", "snippet": "class Logger(logging.Logger):\n class _WarningFilterContext:\n class WarningFilter(logging.Filter):\n ENV_VAR = \"OWLITE_LOG_LEVEL\"\n DEBUG_WARNING = 15\n ULTRA_VERBOSE = -10\n def ignore_warnings(self):\n ...
import os import sys import uuid import numpy as np import onnx import onnx_graphsurgeon as gs from collections import Counter, OrderedDict from collections.abc import Iterable from itertools import chain from typing import Callable, Optional, Union, cast from onnx import GraphProto, ModelProto, TensorProto from onnx.external_data_helper import ( _get_attribute_tensors_from_graph, _get_initializer_tensors_from_graph, _is_valid_filename, save_external_data, set_external_data, uses_external_data, ) from onnx_graphsurgeon.exporters.onnx_exporter import OnnxExporter from onnx_graphsurgeon.importers.onnx_importer import get_numpy_type from ...logger import log from ..utils import is_floating_point, nodestr from .fold_constants import fold_constants from .onnx_op import ONNXOp
9,943
conv_weight.values *= value_to_fold.reshape(target_shape) conv_node.outputs = mul_or_div_node.outputs mul_or_div_node.outputs.clear() def _fold_add_or_sub(conv_node: gs.Node, add_or_sub_node: gs.Node) -> None: assert conv_node.op == "Conv" and add_or_sub_node.op in ("Add", "Sub") conv_params = _get_constant_conv_params(conv_node) assert conv_params is not None conv_weight, conv_bias, _ = conv_params param_to_fold = _get_constant_param_to_fold(add_or_sub_node) assert param_to_fold is not None value_to_fold: np.ndarray = param_to_fold.values value_to_fold = np.broadcast_to( value_to_fold.squeeze(), conv_weight.values.shape[0] ) if add_or_sub_node.op == "Sub": if ( add_or_sub_node.inputs[1] is conv_node.outputs[0] ): # Sub(param, Conv(x, w, b)) conv_weight.values = -conv_weight.values if conv_bias is not None: conv_bias.values = -conv_bias.values else: # Sub(Conv(x, w, b), param) value_to_fold = -value_to_fold if conv_bias is not None: conv_bias.values += value_to_fold else: new_bias = gs.Constant( param_to_fold.name, value_to_fold, param_to_fold.data_location ) conv_node.inputs.append(new_bias) conv_node.outputs = add_or_sub_node.outputs add_or_sub_node.outputs.clear() if node_to_fold.op in ("Mul", "Div"): _fold_mul_or_div(conv_node, node_to_fold) elif node_to_fold.op in ("Add", "Sub"): _fold_add_or_sub(conv_node, node_to_fold) else: # for future extensibility, we might be able to fold more operations raise NotImplementedError() for node in graph.nodes: if node.op == "Conv": i = 0 while i < MAXIMUM_ITERATION: if _is_foldable(node.outputs[0]): log.debug( f"Folding {nodestr(node.outputs[0].outputs[0])} into {nodestr(node)}" ) _fold(node, node.outputs[0].outputs[0]) i += 1 continue break return graph # pylint: disable=missing-function-docstring def remove_if_dropout_op_with_ratio_zero(node: gs.Node, graph: gs.Graph) -> None: if node.op != "Dropout": return ratio_input_node = input_node_of(node, 1, 0) if ratio_input_node is None or "value" not in ratio_input_node.attrs: return if ratio_input_node.attrs["value"].values.item() != 0.0: return remove_if_has_unique_non_optional_input_and_unique_used_output(node, graph) def remove_if_cast_op_with_no_effect(node: gs.Node, graph: gs.Graph) -> None: if node.op != "Cast": return if "to" not in node.attrs: log.debug_warning(f'Missing required attribute "to" in {nodestr(node)}') return if len(node.inputs) != 1: log.debug_warning( f"{nodestr(node)} must have 1 input but {len(node.inputs)} found: {node.inputs}" ) return if len(node.outputs) != 1: log.debug_warning( f"{nodestr(node)} must have 1 output but {len(node.outputs)} found: {node.outputs}" ) return the_input = node.inputs[0] the_output = node.outputs[0] data_type = cast(TensorProto.DataType, node.attrs["to"]) dtype = get_numpy_type(data_type) if not isinstance(dtype, np.dtype): log.debug_warning( f'Failed to convert attribute "to": {TensorProto.DataType.Name(data_type)}' " of {nodestr(node)} into numpy type" ) return if the_input.dtype in (dtype, the_output.dtype): remove_if_has_unique_non_optional_input_and_unique_used_output(node, graph) def cast_constant_input_fp_tensors_of(node: gs.Node, dtype: np.dtype) -> None:
"""Preprocessing steps required for onnx simplifier and for further optimization""" OnnxTransform = Callable[[gs.Graph], gs.Graph] ONNX_TRANSFORMS: dict[str, OnnxTransform] = {} TensorType = Union[gs.Constant, gs.Variable] MAXIMUM_ITERATION = 100 def apply_onnx_transforms( onnx_proto: ModelProto, output_path: Optional[str] = None, **kwargs ) -> ModelProto: """Applies all transformations registered in this file. Args: onnx_proto (ModelProto): the ONNX model proto to apply transformations. output_path (Optional[str], optional): the output path in string. If provided, runs the ModelProto will be written with external data after the transformations (required for large models > 2GB). Defaults to None. Returns: ModelProto: _description_ """ graph = gs.import_onnx(onnx_proto) for name, transform in ONNX_TRANSFORMS.items(): log.debug(f"Applying ONNX transform: {name}") graph = transform(graph) graph.toposort() graph = fold_constants(graph) graph.cleanup() if output_path is None: return gs.export_onnx(graph) export_to_onnx_with_external_data(graph, output_path, **kwargs) return onnx.load(output_path) def register_onnx_transform(transform: OnnxTransform) -> OnnxTransform: """Registers a ONNX transform globally. Note that the registration order matters. Use this function as a decorator to register your custom ONNX transform. For example: @register_onnx_transform def do_something_on_onnx_graph(graph: gs.Graph) -> gs.Graph: ... """ name = transform.__name__ if name in ONNX_TRANSFORMS: log.debug_warning(f"Overwriting existing ONNX transform: {name}") ONNX_TRANSFORMS[name] = transform return transform @register_onnx_transform def fold_trilu_constants(graph: gs.Graph) -> gs.Graph: """Folds Trilu ops if constant-foldable. Note that this transformation is a workaround for the missing support for the Trilu op in onnx-runtime Args: graph (gs.Graph): a ONNX graph. Returns: gs.Graph: the ONNX graph with constant-foldable Trilu ops removed. """ for node in graph.nodes: if node.op == "Trilu": input_node = input_node_of(node, 0) if input_node is None or "value" not in input_node.attrs: continue input_values: np.ndarray = input_node.attrs["value"].values k_node = input_node_of(node, 1) if k_node is None or "value" not in k_node.attrs: continue k_values: np.ndarray = k_node.attrs["value"].values folded_values: np.ndarray = np.tril(input_values, k_values) output_tensor: gs.Variable = node.outputs[0] output_tensor.inputs.clear() output_const = gs.Constant(name=f"{node.name}_const", values=folded_values) const_node = gs.Node( op="Constant", name=f"{node.name}_folded", attrs=OrderedDict([("value", output_const)]), outputs=[output_tensor], ) graph.nodes.remove(node) graph.nodes.append(const_node) log.debug(f"Replaced {nodestr(node)} by {nodestr(const_node)}") graph.cleanup() graph.toposort() return graph @register_onnx_transform def eliminate_nop_dropouts(graph: gs.Graph) -> gs.Graph: """Eliminates all Dropout ops with no effect. Args: graph (gs.Graph): a ONNX graph. Returns: gs.Graph: the ONNX graph with meaningless Dropout ops removed. """ for node in graph.nodes: remove_if_dropout_op_with_ratio_zero(node, graph) graph.cleanup() graph.toposort() return graph @register_onnx_transform def eliminate_nop_cast(graph: gs.Graph) -> gs.Graph: """Eliminates all Cast ops with no effect. Args: graph (gs.Graph): a ONNX graph. Returns: gs.Graph: the ONNX graph with meaningless Cast ops removed. """ for node in graph.nodes: remove_if_cast_op_with_no_effect(node, graph) graph.cleanup() graph.toposort() return graph @register_onnx_transform def synchronize_floating_point_types(graph: gs.Graph) -> gs.Graph: """Synchronizes all floating points types used in the graph as the most common one. Args: graph (gs.Graph): a ONNX graph. Returns: gs.Graph: the ONNX graph with only one floating point type. """ floating_point_dtypes: list[np.dtype] = [ *filter(is_floating_point, (t.dtype for t in graph.tensors().values())) ] counter = Counter(floating_point_dtypes) log.debug(f"Counts of floating point types: {counter}") if len(counter) == 0: log.debug("No tensor with floating point type found in the graph") return graph most_common_dtype = counter.most_common(1)[0][0] log.debug(f"Most common floating point type: {most_common_dtype}") if len(counter) > 1: log.warning( "More than one floating point types are used in the graph (" f'{", ".join(f"{value} tensors of type {key.name}" for key, value in OrderedDict(counter).items())}). ' f"Will use the most common one: {most_common_dtype}" ) for node in graph.nodes: cast_constant_input_fp_tensors_of(node, most_common_dtype) cast_output_fp_tensors_of(node, most_common_dtype) return eliminate_nop_cast(graph) @register_onnx_transform def fold_nodes_after_conv(graph: gs.Graph) -> gs.Graph: """Fold foldable element-wise operations after convolution into convolution's weight and bias. Args: graph (gs.Graph): a ONNX graph. Returns: gs.Graph: the transformed ONNX graph """ # pylint: disable=too-many-statements def _get_constant_or_none(tensor: TensorType) -> Optional[gs.Constant]: if isinstance(tensor, gs.Constant): return tensor if ( len(tensor.inputs) == 1 and tensor.inputs[0].op == "Constant" and isinstance(tensor.inputs[0].attrs.get("value"), gs.Constant) ): return tensor.inputs[0].attrs.get("value") return None def _get_constant_conv_params( conv_node: gs.Node, ) -> Optional[tuple[gs.Constant, Optional[gs.Constant], Optional[gs.Constant]]]: if conv_node.op != "Conv": raise ValueError( f"Expected a `Conv` operation but received `{conv_node.op}`" ) # weight is required field for conv conv_weight = conv_node.inputs[1] # bias is optional input for conv conv_bias = conv_node.inputs[2] if len(conv_node.inputs) == 3 else None # we do not consider zero point for now quantizer_step_size = None if ( isinstance(conv_weight, gs.Variable) and get_defining_op_type(conv_weight) == "DequantizeLinear" ): dequantize_node = conv_weight.inputs[0] if get_defining_op_type(dequantize_node.inputs[0]) != "QuantizeLinear": # parent node of DequantizeLinear is not QuantizeLinear return None quantizer_step_size = dequantize_node.inputs[1] if len(quantizer_step_size.outputs) != 2: # quantizer step size used somewhere else than current quantizers, # note that QuantizeLinear and DequantizeLinear from same quantizer shares the same tensor return None quantize_node = dequantize_node.inputs[0].inputs[0] if quantize_node.inputs[1] is not quantizer_step_size: # QuantizeLinear does not share the same tensor as step size with DequantizeLinear return None quantizer_step_size = _get_constant_or_none(quantizer_step_size) if quantizer_step_size is None: # quantizer step size is variable return None conv_weight = quantize_node.inputs[0] conv_weight = _get_constant_or_none(conv_weight) if conv_weight is None: return None if conv_bias is not None: conv_bias = _get_constant_or_none(conv_bias) if conv_bias is None: return None assert ( isinstance(conv_weight, gs.Constant) and isinstance(conv_bias, (gs.Constant, type(None))) and isinstance(quantizer_step_size, (gs.Constant, type(None))) ) return conv_weight, conv_bias, quantizer_step_size def _get_constant_param_to_fold(node_to_fold: gs.Node) -> Optional[gs.Constant]: parameter_to_fold = [ _get_constant_or_none(tensor) for tensor in node_to_fold.inputs ] parameter_to_fold = [ tensor for tensor in parameter_to_fold if tensor is not None ] if len(parameter_to_fold) == 1: return parameter_to_fold[0] return None def _is_foldable(conv_output_tensor: gs.Variable) -> bool: # convolution output is dependant to other node than conv or convolution output is used more than once if len(conv_output_tensor.inputs) != 1 or len(conv_output_tensor.outputs) != 1: return False conv_node: gs.Node = conv_output_tensor.inputs[0] node_to_fold: gs.Node = conv_output_tensor.outputs[0] # only the element-wise operations are foldable, and we cannot fold Div(param, Conv(x, w, b)) if node_to_fold.op not in ("Add", "Sub", "Mul", "Div") or ( node_to_fold.op == "Div" and node_to_fold.inputs[1] is conv_output_tensor ): return False # all involved tensors should be constant parameter_to_fold = _get_constant_param_to_fold(node_to_fold) conv_node_params = _get_constant_conv_params(conv_node) if parameter_to_fold is None or conv_node_params is None: return False conv_weight, conv_bias, quantizer_step_size = conv_node_params # disclaimer: we now only consider 2d convolution, with this removed, conditions below should be revisited if conv_weight.values.ndim != 4 or ( conv_bias is not None and conv_bias.values.ndim != 1 ): return False # cannot broadcast parameter to fold to convolution output channel dimension if ( parameter_to_fold.values.shape.count(1) < len(parameter_to_fold.values.shape) - 1 and parameter_to_fold.values.size != conv_weight.values.shape[0] ): return False # cannot broadcast parameter to fold to per-tensor quantization step size if ( quantizer_step_size is not None and parameter_to_fold.values.size != 1 and quantizer_step_size.values.size == 1 ): return False return True def _fold(conv_node: gs.Node, node_to_fold: gs.Node) -> None: def _fold_mul_or_div(conv_node: gs.Node, mul_or_div_node: gs.Node) -> None: assert conv_node.op == "Conv" and mul_or_div_node.op in ("Mul", "Div") conv_params = _get_constant_conv_params(conv_node) assert conv_params is not None conv_weight, conv_bias, quantizer_step_size = conv_params param_to_fold = _get_constant_param_to_fold(mul_or_div_node) assert param_to_fold is not None value_to_fold: np.ndarray = ( param_to_fold.values if mul_or_div_node.op == "Mul" else (param_to_fold.values**-1) ) value_to_fold = np.broadcast_to( value_to_fold.squeeze(), conv_weight.values.shape[0] ) if conv_bias is not None: conv_bias.values *= value_to_fold if quantizer_step_size is not None: if quantizer_step_size.values.size == 1: assert np.all(value_to_fold == value_to_fold[0]) quantizer_step_size.values *= np.abs(value_to_fold)[0] else: quantizer_step_size.values *= np.abs(value_to_fold) target_shape = ( value_to_fold.shape[0], 1, 1, 1, ) conv_weight.values *= value_to_fold.reshape(target_shape) conv_node.outputs = mul_or_div_node.outputs mul_or_div_node.outputs.clear() def _fold_add_or_sub(conv_node: gs.Node, add_or_sub_node: gs.Node) -> None: assert conv_node.op == "Conv" and add_or_sub_node.op in ("Add", "Sub") conv_params = _get_constant_conv_params(conv_node) assert conv_params is not None conv_weight, conv_bias, _ = conv_params param_to_fold = _get_constant_param_to_fold(add_or_sub_node) assert param_to_fold is not None value_to_fold: np.ndarray = param_to_fold.values value_to_fold = np.broadcast_to( value_to_fold.squeeze(), conv_weight.values.shape[0] ) if add_or_sub_node.op == "Sub": if ( add_or_sub_node.inputs[1] is conv_node.outputs[0] ): # Sub(param, Conv(x, w, b)) conv_weight.values = -conv_weight.values if conv_bias is not None: conv_bias.values = -conv_bias.values else: # Sub(Conv(x, w, b), param) value_to_fold = -value_to_fold if conv_bias is not None: conv_bias.values += value_to_fold else: new_bias = gs.Constant( param_to_fold.name, value_to_fold, param_to_fold.data_location ) conv_node.inputs.append(new_bias) conv_node.outputs = add_or_sub_node.outputs add_or_sub_node.outputs.clear() if node_to_fold.op in ("Mul", "Div"): _fold_mul_or_div(conv_node, node_to_fold) elif node_to_fold.op in ("Add", "Sub"): _fold_add_or_sub(conv_node, node_to_fold) else: # for future extensibility, we might be able to fold more operations raise NotImplementedError() for node in graph.nodes: if node.op == "Conv": i = 0 while i < MAXIMUM_ITERATION: if _is_foldable(node.outputs[0]): log.debug( f"Folding {nodestr(node.outputs[0].outputs[0])} into {nodestr(node)}" ) _fold(node, node.outputs[0].outputs[0]) i += 1 continue break return graph # pylint: disable=missing-function-docstring def remove_if_dropout_op_with_ratio_zero(node: gs.Node, graph: gs.Graph) -> None: if node.op != "Dropout": return ratio_input_node = input_node_of(node, 1, 0) if ratio_input_node is None or "value" not in ratio_input_node.attrs: return if ratio_input_node.attrs["value"].values.item() != 0.0: return remove_if_has_unique_non_optional_input_and_unique_used_output(node, graph) def remove_if_cast_op_with_no_effect(node: gs.Node, graph: gs.Graph) -> None: if node.op != "Cast": return if "to" not in node.attrs: log.debug_warning(f'Missing required attribute "to" in {nodestr(node)}') return if len(node.inputs) != 1: log.debug_warning( f"{nodestr(node)} must have 1 input but {len(node.inputs)} found: {node.inputs}" ) return if len(node.outputs) != 1: log.debug_warning( f"{nodestr(node)} must have 1 output but {len(node.outputs)} found: {node.outputs}" ) return the_input = node.inputs[0] the_output = node.outputs[0] data_type = cast(TensorProto.DataType, node.attrs["to"]) dtype = get_numpy_type(data_type) if not isinstance(dtype, np.dtype): log.debug_warning( f'Failed to convert attribute "to": {TensorProto.DataType.Name(data_type)}' " of {nodestr(node)} into numpy type" ) return if the_input.dtype in (dtype, the_output.dtype): remove_if_has_unique_non_optional_input_and_unique_used_output(node, graph) def cast_constant_input_fp_tensors_of(node: gs.Node, dtype: np.dtype) -> None:
onnx_op = ONNXOp(node.op)
4
2023-12-08 06:41:50+00:00
12k
bolna-ai/bolna
bolna/agent_manager/assistant_manager.py
[ { "identifier": "BaseManager", "path": "bolna/agent_manager/base_manager.py", "snippet": "class BaseManager:\n def __init__(self):\n self.agent = \"bolna-agent\"" }, { "identifier": "TaskManager", "path": "bolna/agent_manager/task_manager.py", "snippet": "class TaskManager(Base...
import asyncio import uvloop import time import os import requests import tiktoken from twilio.rest import Client from .base_manager import BaseManager from .task_manager import TaskManager from bolna.helpers.logger_config import configure_logger
7,770
logger = configure_logger(__name__) # Find your Account SID and Auth Token at twilio.com/console # and set the environment variables. See http://twil.io/secure account_sid = os.environ['TWILIO_ACCOUNT_SID'] auth_token = os.environ['TWILIO_AUTH_TOKEN'] client = Client(account_sid, auth_token) enc = tiktoken.get_encoding("cl100k_base")
logger = configure_logger(__name__) # Find your Account SID and Auth Token at twilio.com/console # and set the environment variables. See http://twil.io/secure account_sid = os.environ['TWILIO_ACCOUNT_SID'] auth_token = os.environ['TWILIO_AUTH_TOKEN'] client = Client(account_sid, auth_token) enc = tiktoken.get_encoding("cl100k_base")
class AssistantManager(BaseManager):
0
2023-12-13 09:07:35+00:00
12k
qitan/devops-backend-lite
apps/ucenter/views.py
[ { "identifier": "FEISHU_SYNC_USER_JOB_CACHE_KEY", "path": "common/variables.py", "snippet": "FEISHU_SYNC_USER_JOB_CACHE_KEY = 'celery_job:feishu_user_sync'" }, { "identifier": "Menu", "path": "dbapp/models.py", "snippet": "" }, { "identifier": "CustomModelViewSet", "path": "c...
import hashlib import django_filters import datetime import time import shortuuid import json import logging from django.core.cache import cache from rest_framework import viewsets, status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import action from rest_framework import pagination from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView from rest_framework_simplejwt.exceptions import TokenError, InvalidToken from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework_simplejwt.tokens import RefreshToken, Token, OutstandingToken from rest_framework.filters import SearchFilter, OrderingFilter from django_q.tasks import async_task, result from django.contrib.auth.models import update_last_login from django.db.models import Q from django.contrib.auth import logout from common.variables import FEISHU_SYNC_USER_JOB_CACHE_KEY from dbapp.models import Menu, Permission, Role, Organization, UserProfile, AuditLog, SystemConfig, DataDict from ucenter.serializers import MenuSerializers, MenuListSerializers, PermissionListSerializers, PermissionSerializers, \ RoleListSerializers, \ RoleSerializers, OrganizationSerializers, \ UserProfileListSerializers, UserProfileSerializers, UserProfileDetailSerializers, AuditLogSerializers, \ AuditLogActivitySerializers, SystemConfigSerializers, \ SystemConfigListSerializers, DataDictSerializers from common.extends.viewsets import CustomModelViewSet, CustomModelParentViewSet from common.extends.permissions import RbacPermission from common.extends.JwtAuth import CustomInvalidToken, TokenObtainPairSerializer, TokenRefreshSerializer from common.extends.handler import log_audit from common.extends.filters import AuditLogFilter, CustomSearchFilter from common.utils.JenkinsAPI import GlueJenkins from common.get_ip import user_ip from common.ext_fun import ThirdPartyUser, set_redis_data, get_redis_data, timeline_generate, time_period, \ node_filter from qtasks.tasks import test_notify from django.conf import settings from django.contrib.auth import login, REDIRECT_FIELD_NAME from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.cache import never_cache
9,520
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author : Charles Lai @Contact : qqing_lai@hotmail.com @Time : 2020/9/15 下午4:08 @FileName: views.py @Blog :https://imaojia.com """ logger = logging.getLogger('drf') DEFAULT_SESSION_TIMEOUT = None
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author : Charles Lai @Contact : qqing_lai@hotmail.com @Time : 2020/9/15 下午4:08 @FileName: views.py @Blog :https://imaojia.com """ logger = logging.getLogger('drf') DEFAULT_SESSION_TIMEOUT = None
class DataDictViewSet(CustomModelParentViewSet):
3
2023-12-13 03:09:32+00:00
12k
AdaCheng/EgoThink
models/instruct_blip/models/blip2_models/blip2_t5_instruct.py
[ { "identifier": "registry", "path": "models/instruct_blip/common/registry.py", "snippet": "class Registry:\n def register_model(cls, name):\n def wrap(model_cls):\n def register_processor(cls, name):\n def wrap(processor_cls):\n def register_lr_scheduler(cls, name):\n def w...
import logging import string import random import copy import torch import torch.nn as nn import spacy from torch.cuda.amp import autocast as autocast from transformers import T5TokenizerFast from ...common.registry import registry from .blip2 import Blip2Base, disabled_train from .modeling_t5 import T5Config, T5ForConditionalGeneration from transformers.modeling_outputs import BaseModelOutput
7,305
""" Copyright (c) 2023, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ @registry.register_model("blip2_t5_instruct") class Blip2T5Instruct(Blip2Base): """ BLIP2 T5 model. Supported model types: - flant5xl - flant5xxl Usage: >>> from lavis.models import load_model >>> model = load_model("blip2_t5_instruct", "flant5xl") """ PRETRAINED_MODEL_CONFIG_DICT = { "flant5xl": "configs/models/blip2/blip2_instruct_flant5xl.yaml", "flant5xxl": "configs/models/blip2/blip2_instruct_flant5xxl.yaml", } def __init__( self, vit_model="eva_clip_g", img_size=224, drop_path_rate=0, use_grad_checkpoint=False, vit_precision="fp16", freeze_vit=True, num_query_token=32, t5_model="google/flan-t5-xl", prompt="", max_txt_len=128, max_output_txt_len=256, apply_lemmatizer=False, num_few_shot_examples=0, few_shot_prob=0, qformer_text_input=True, ): """ apply_lemmatizer: when set to True, postprocess predict_answers() result with lemmas. """ super().__init__() self.tokenizer = self.init_tokenizer(truncation_side="left") self.visual_encoder, self.ln_vision = self.init_vision_encoder( vit_model, img_size, drop_path_rate, use_grad_checkpoint, vit_precision ) if freeze_vit: for name, param in self.visual_encoder.named_parameters(): param.requires_grad = False self.visual_encoder = self.visual_encoder.eval()
""" Copyright (c) 2023, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ @registry.register_model("blip2_t5_instruct") class Blip2T5Instruct(Blip2Base): """ BLIP2 T5 model. Supported model types: - flant5xl - flant5xxl Usage: >>> from lavis.models import load_model >>> model = load_model("blip2_t5_instruct", "flant5xl") """ PRETRAINED_MODEL_CONFIG_DICT = { "flant5xl": "configs/models/blip2/blip2_instruct_flant5xl.yaml", "flant5xxl": "configs/models/blip2/blip2_instruct_flant5xxl.yaml", } def __init__( self, vit_model="eva_clip_g", img_size=224, drop_path_rate=0, use_grad_checkpoint=False, vit_precision="fp16", freeze_vit=True, num_query_token=32, t5_model="google/flan-t5-xl", prompt="", max_txt_len=128, max_output_txt_len=256, apply_lemmatizer=False, num_few_shot_examples=0, few_shot_prob=0, qformer_text_input=True, ): """ apply_lemmatizer: when set to True, postprocess predict_answers() result with lemmas. """ super().__init__() self.tokenizer = self.init_tokenizer(truncation_side="left") self.visual_encoder, self.ln_vision = self.init_vision_encoder( vit_model, img_size, drop_path_rate, use_grad_checkpoint, vit_precision ) if freeze_vit: for name, param in self.visual_encoder.named_parameters(): param.requires_grad = False self.visual_encoder = self.visual_encoder.eval()
self.visual_encoder.train = disabled_train
2
2023-12-05 14:17:17+00:00
12k
modelscope/llmuses
llmuses/run_ms.py
[ { "identifier": "DATASET_ID", "path": "llmuses/benchmarks/ceval/ceval_adapter.py", "snippet": "DATASET_ID = 'modelscope/ceval-exam'" }, { "identifier": "DATASET_ID", "path": "llmuses/benchmarks/mmlu/mmlu_adapter.py", "snippet": "DATASET_ID = 'modelscope/mmlu'" }, { "identifier": ...
import argparse import torch from llmuses.benchmarks.ceval import DATASET_ID as CEVAL_EXAM from llmuses.benchmarks.mmlu import DATASET_ID as MMLU from llmuses.benchmarks.hellaswag import DATASET_ID as HELLA_SWAG from llmuses.benchmarks.arc import DATASET_ID as ARC from llmuses.benchmarks.truthful_qa import DATASET_ID as TRUTHFUL_QA from llmuses.constants import DEFAULT_ROOT_CACHE_DIR from llmuses.evaluator import Evaluator from llmuses.models.model_adapter import MultiChoiceModelAdapter, ContinuationLogitsModelAdapter from llmuses.utils.logger import get_logger from llmuses.models.dummy_chat_model import DummyChatModel from llmuses.benchmarks.ceval import CEVALAdapter from llmuses.benchmarks.mmlu import MMLUAdapter from llmuses.benchmarks.arc import ARCAdapter from llmuses.benchmarks.hellaswag import HellaSwagAdapter from llmuses.benchmarks.truthful_qa import TruthfulQaAdapter
7,598
# Copyright (c) Alibaba, Inc. and its affiliates. # flake8: noqa logger = get_logger() # TODO: add more precision MODEL_PRECISION_MAP = {'fp16': torch.float16, 'fp32': torch.float32, 'bf16': torch.bfloat16} """ Run evaluation process for ModelScope Leaderboard. """ def parse_args(): parser = argparse.ArgumentParser(description='Run evaluation on a model') parser.add_argument('--model', help='Model id from modelscope or huggingface.', required=True) parser.add_argument('--revision', help='Model revision.', required=False, default=None) parser.add_argument('--precision', help='Model precision.', default='bf16') parser.add_argument('--work-dir', help='root work cache dir.', default=None) parser.add_argument('--outputs-dir', help='Outputs dir.', default='outputs') parser.add_argument('--datasets-dir', help='Datasets dir.', default=DEFAULT_ROOT_CACHE_DIR) parser.add_argument('--device-map', help='device map.', default='auto') parser.add_argument('--max-eval-size', type=int, help='Max evaluation samples num for each subset', default=None) parser.add_argument('--dataset-id', help='Dataset id on modelscope', required=False, default=None) parser.add_argument('--debug', help='Debug mode, will print information for debugging.', action='store_true', default=False) parser.add_argument('--dry-run', help='Dry run in single processing mode.', action='store_true', default=False) parser.add_argument('--mem-cache', help='To use memory cache or not.', action='store_true', default=False) args = parser.parse_args() return args def main(): args = parse_args() logger.info(args) # Customize your target datasets here all_benchmarks = [CEVAL_EXAM, MMLU, ARC, HELLA_SWAG, TRUTHFUL_QA] dataset_id = args.dataset_id if dataset_id is None: datasets = all_benchmarks elif dataset_id in all_benchmarks: datasets = [dataset_id] else: raise ValueError(f'Unknown dataset: {dataset_id}, Supported datasets: {all_benchmarks}') # Get model instance if args.dry_run: model_adapter = DummyChatModel(model_cfg=dict()) # TODO model_id: str = 'dummy' model_revision: str = 'v1.0.0' model_precision = MODEL_PRECISION_MAP.get(args.precision, torch.bfloat16) else: model_id: str = args.model model_revision: str = args.revision model_precision = MODEL_PRECISION_MAP.get(args.precision, torch.bfloat16) model_adapter = MultiChoiceModelAdapter(model_id=model_id, device_map=args.device_map, torch_dtype=model_precision, model_revision=model_revision,) # Evaluate on each dataset for dataset_name in datasets: if dataset_name == CEVAL_EXAM: data_adapter = CEVALAdapter() elif dataset_name == MMLU: data_adapter = MMLUAdapter() elif dataset_name == ARC: data_adapter = ARCAdapter() elif dataset_name == HELLA_SWAG: # Note: HellaSwag should run few-shot eval data_adapter = HellaSwagAdapter() elif dataset_name == TRUTHFUL_QA: data_adapter = TruthfulQaAdapter() # TODO: add more datasets here else: raise ValueError(f'Unknown dataset: {dataset_name}') # TODO: add mapping if dataset_name in {TRUTHFUL_QA, HELLA_SWAG} and not args.dry_run:
# Copyright (c) Alibaba, Inc. and its affiliates. # flake8: noqa logger = get_logger() # TODO: add more precision MODEL_PRECISION_MAP = {'fp16': torch.float16, 'fp32': torch.float32, 'bf16': torch.bfloat16} """ Run evaluation process for ModelScope Leaderboard. """ def parse_args(): parser = argparse.ArgumentParser(description='Run evaluation on a model') parser.add_argument('--model', help='Model id from modelscope or huggingface.', required=True) parser.add_argument('--revision', help='Model revision.', required=False, default=None) parser.add_argument('--precision', help='Model precision.', default='bf16') parser.add_argument('--work-dir', help='root work cache dir.', default=None) parser.add_argument('--outputs-dir', help='Outputs dir.', default='outputs') parser.add_argument('--datasets-dir', help='Datasets dir.', default=DEFAULT_ROOT_CACHE_DIR) parser.add_argument('--device-map', help='device map.', default='auto') parser.add_argument('--max-eval-size', type=int, help='Max evaluation samples num for each subset', default=None) parser.add_argument('--dataset-id', help='Dataset id on modelscope', required=False, default=None) parser.add_argument('--debug', help='Debug mode, will print information for debugging.', action='store_true', default=False) parser.add_argument('--dry-run', help='Dry run in single processing mode.', action='store_true', default=False) parser.add_argument('--mem-cache', help='To use memory cache or not.', action='store_true', default=False) args = parser.parse_args() return args def main(): args = parse_args() logger.info(args) # Customize your target datasets here all_benchmarks = [CEVAL_EXAM, MMLU, ARC, HELLA_SWAG, TRUTHFUL_QA] dataset_id = args.dataset_id if dataset_id is None: datasets = all_benchmarks elif dataset_id in all_benchmarks: datasets = [dataset_id] else: raise ValueError(f'Unknown dataset: {dataset_id}, Supported datasets: {all_benchmarks}') # Get model instance if args.dry_run: model_adapter = DummyChatModel(model_cfg=dict()) # TODO model_id: str = 'dummy' model_revision: str = 'v1.0.0' model_precision = MODEL_PRECISION_MAP.get(args.precision, torch.bfloat16) else: model_id: str = args.model model_revision: str = args.revision model_precision = MODEL_PRECISION_MAP.get(args.precision, torch.bfloat16) model_adapter = MultiChoiceModelAdapter(model_id=model_id, device_map=args.device_map, torch_dtype=model_precision, model_revision=model_revision,) # Evaluate on each dataset for dataset_name in datasets: if dataset_name == CEVAL_EXAM: data_adapter = CEVALAdapter() elif dataset_name == MMLU: data_adapter = MMLUAdapter() elif dataset_name == ARC: data_adapter = ARCAdapter() elif dataset_name == HELLA_SWAG: # Note: HellaSwag should run few-shot eval data_adapter = HellaSwagAdapter() elif dataset_name == TRUTHFUL_QA: data_adapter = TruthfulQaAdapter() # TODO: add more datasets here else: raise ValueError(f'Unknown dataset: {dataset_name}') # TODO: add mapping if dataset_name in {TRUTHFUL_QA, HELLA_SWAG} and not args.dry_run:
model_adapter = ContinuationLogitsModelAdapter(model_id=model_id,
8
2023-12-07 06:10:49+00:00
12k
liujin112/PortraitDiffusion
main.py
[ { "identifier": "MasaCtrlPipeline", "path": "utils/pipeline.py", "snippet": "class MasaCtrlPipeline(StableDiffusionPipeline):\n\n def next_step(\n self,\n model_output: torch.FloatTensor,\n timestep: int,\n x: torch.FloatTensor,\n eta=0.,\n verbose=False\n ...
import os import sys import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import argparse import numpy as np from tqdm import tqdm from diffusers import DDIMScheduler,LCMScheduler from torchvision.utils import save_image from torchvision.io import read_image from PIL import Image from utils.pipeline import MasaCtrlPipeline from utils.masactrl_utils import AttentionBase, regiter_attention_editor_diffusers from utils.style_attn_control import MaskPromptedStyleAttentionControl
8,005
def load_image(image_path, res, device, gray=False): image = Image.open(image_path).convert('RGB') if not gray else Image.open(image_path).convert('L') image = torch.tensor(np.array(image)).float() if gray: image = image.unsqueeze(-1).repeat(1,1,3) image = image.permute(2, 0, 1) image = image[:3].unsqueeze_(0).float() / 127.5 - 1. # [-1, 1] image = F.interpolate(image, (res, res)) image = image.to(device) return image def load_mask(image_path, res, device): if image_path != '': image = Image.open(image_path).convert('RGB') image = torch.tensor(np.array(image)).float() image = image.permute(2, 0, 1) image = image[:3].unsqueeze_(0).float() / 127.5 - 1. # [-1, 1] image = F.interpolate(image, (res, res)) image = image.to(device) image = image[:, :1, :, :] else: return None return image def main(): args = argparse.ArgumentParser() args.add_argument("--step", type=int, default=0) args.add_argument("--layer", type=int, default=10) args.add_argument("--res", type=int, default=512) args.add_argument("--style_guidance", type=float, default=1.5) args.add_argument("--content", type=str, default=None) args.add_argument("--style", type=str, default=None) args.add_argument("--content_mask", type=str, default='') args.add_argument("--style_mask", type=str, default='') args.add_argument("--output", type=str, default='./results/') args.add_argument("--only_mask_region", action="store_true") args.add_argument("--model_path", type=str, default='runwayml/stable-diffusion-v1-5') args.add_argument("--SAC_step", type=int, default=35) args.add_argument("--num_inference_steps", type=int, default=50) args.add_argument("--LCM_lora", action="store_true") args = args.parse_args() STEP = args.step LAYPER = args.layer only_mask_region = args.only_mask_region out_dir = args.output style_guidance = args.style_guidance num_inference_steps = args.num_inference_steps SAC_step = args.SAC_step device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") Guidance_scale = 0.0 model_path = args.model_path model = MasaCtrlPipeline.from_pretrained(model_path).to(device) if args.LCM_lora: model.scheduler = LCMScheduler.from_config(model.scheduler.config) # load LCM-LoRA model.load_lora_weights("latent-consistency/lcm-lora-sdv1-5") else: model.scheduler = DDIMScheduler.from_config(model.scheduler.config) source_image = load_image(args.content, args.res, device) style_image = load_image(args.style, args.res, device) style_mask = load_mask(args.style_mask, res=64, device=device) source_mask = load_mask(args.content_mask, res=args.res, device=device) with torch.no_grad(): style_content = torch.cat([style_image, source_image], dim=0) source_prompt = ['head', 'head'] prompts = source_prompt + ['head']
def load_image(image_path, res, device, gray=False): image = Image.open(image_path).convert('RGB') if not gray else Image.open(image_path).convert('L') image = torch.tensor(np.array(image)).float() if gray: image = image.unsqueeze(-1).repeat(1,1,3) image = image.permute(2, 0, 1) image = image[:3].unsqueeze_(0).float() / 127.5 - 1. # [-1, 1] image = F.interpolate(image, (res, res)) image = image.to(device) return image def load_mask(image_path, res, device): if image_path != '': image = Image.open(image_path).convert('RGB') image = torch.tensor(np.array(image)).float() image = image.permute(2, 0, 1) image = image[:3].unsqueeze_(0).float() / 127.5 - 1. # [-1, 1] image = F.interpolate(image, (res, res)) image = image.to(device) image = image[:, :1, :, :] else: return None return image def main(): args = argparse.ArgumentParser() args.add_argument("--step", type=int, default=0) args.add_argument("--layer", type=int, default=10) args.add_argument("--res", type=int, default=512) args.add_argument("--style_guidance", type=float, default=1.5) args.add_argument("--content", type=str, default=None) args.add_argument("--style", type=str, default=None) args.add_argument("--content_mask", type=str, default='') args.add_argument("--style_mask", type=str, default='') args.add_argument("--output", type=str, default='./results/') args.add_argument("--only_mask_region", action="store_true") args.add_argument("--model_path", type=str, default='runwayml/stable-diffusion-v1-5') args.add_argument("--SAC_step", type=int, default=35) args.add_argument("--num_inference_steps", type=int, default=50) args.add_argument("--LCM_lora", action="store_true") args = args.parse_args() STEP = args.step LAYPER = args.layer only_mask_region = args.only_mask_region out_dir = args.output style_guidance = args.style_guidance num_inference_steps = args.num_inference_steps SAC_step = args.SAC_step device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") Guidance_scale = 0.0 model_path = args.model_path model = MasaCtrlPipeline.from_pretrained(model_path).to(device) if args.LCM_lora: model.scheduler = LCMScheduler.from_config(model.scheduler.config) # load LCM-LoRA model.load_lora_weights("latent-consistency/lcm-lora-sdv1-5") else: model.scheduler = DDIMScheduler.from_config(model.scheduler.config) source_image = load_image(args.content, args.res, device) style_image = load_image(args.style, args.res, device) style_mask = load_mask(args.style_mask, res=64, device=device) source_mask = load_mask(args.content_mask, res=args.res, device=device) with torch.no_grad(): style_content = torch.cat([style_image, source_image], dim=0) source_prompt = ['head', 'head'] prompts = source_prompt + ['head']
editor = AttentionBase()
1
2023-12-06 01:18:39+00:00
12k
MarilynKeller/aitviewer-skel
aitviewer/streamables/webcam.py
[ { "identifier": "Node", "path": "aitviewer/scene/node.py", "snippet": "class Node(object):\n \"\"\"Interface for nodes.\"\"\"\n\n def __init__(\n self,\n name=None,\n icon=None,\n position=None,\n rotation=None,\n scale=1.0,\n color=(0.5, 0.5, 0.5, ...
import cv2 import numpy as np from moderngl_window import geometry from aitviewer.scene.node import Node from aitviewer.shaders import get_screen_texture_program from aitviewer.streamables.streamable import Streamable
7,350
# Copyright (C) 2023 ETH Zurich, Manuel Kaufmann, Velko Vechev, Dario Mylonopoulos class Webcam(Streamable): """ Renders webcam stream to a quad. Quad is positioned in screen coordinates. """ def __init__( self, src=0, size=(2.0, 2.0), pos=(0.0, 0.0), transparency=1.0, icon="\u0088", **kwargs, ): """ :param src: integer denotes device source id, i.e. webcam 0. """ super(Webcam, self).__init__(icon=icon, **kwargs) # Capture source self._cap = None # Set after cv reads video file or webcam self.width = None self.height = None self.pos = pos self.size = size self.fps = None self.frame_count = None self.transparency = transparency self.src = src # Render into a quad in screen space (z=0) self._texture = None @Node.once def make_renderable(self, ctx): self.ctx = ctx self.quad = geometry.quad_2d( pos=self.pos, size=self.size, normals=False ) # (2,2) is Full Screen i.e. -1 to 1 in x/y
# Copyright (C) 2023 ETH Zurich, Manuel Kaufmann, Velko Vechev, Dario Mylonopoulos class Webcam(Streamable): """ Renders webcam stream to a quad. Quad is positioned in screen coordinates. """ def __init__( self, src=0, size=(2.0, 2.0), pos=(0.0, 0.0), transparency=1.0, icon="\u0088", **kwargs, ): """ :param src: integer denotes device source id, i.e. webcam 0. """ super(Webcam, self).__init__(icon=icon, **kwargs) # Capture source self._cap = None # Set after cv reads video file or webcam self.width = None self.height = None self.pos = pos self.size = size self.fps = None self.frame_count = None self.transparency = transparency self.src = src # Render into a quad in screen space (z=0) self._texture = None @Node.once def make_renderable(self, ctx): self.ctx = ctx self.quad = geometry.quad_2d( pos=self.pos, size=self.size, normals=False ) # (2,2) is Full Screen i.e. -1 to 1 in x/y
self.prog = get_screen_texture_program()
1
2023-12-07 16:13:50+00:00
12k
nexB/dejacode
workflow/models.py
[ { "identifier": "LastModifiedByField", "path": "dje/fields.py", "snippet": "class LastModifiedByField(models.ForeignKey):\n def __init__(self, *args, **kwargs):\n help_text = _(\"The application user who last modified the object.\")\n\n kwargs.update(\n {\n \"t...
import json import logging import os import markdown from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.postgres.fields import ArrayField from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.db.models import Q from django.dispatch import receiver from django.urls import reverse from django.utils import timezone from django.utils.functional import cached_property from django.utils.html import escape from django.utils.html import format_html from django.utils.translation import gettext_lazy as _ from bleach import Cleaner from bleach.linkifier import LinkifyFilter from bleach_allowlist import markdown_attrs from bleach_allowlist import markdown_tags from dje.fields import LastModifiedByField from dje.models import DataspacedManager from dje.models import DataspacedModel from dje.models import DataspacedQuerySet from dje.models import HistoryDateFieldsMixin from dje.models import HistoryFieldsMixin from dje.models import get_unsecured_manager from workflow.notification import request_comment_slack_payload from workflow.notification import request_slack_payload from workflow.api import RequestSerializer from workflow.api import RequestCommentSerializer from workflow.api import RequestSerializer
8,196
def __str__(self): return self.name def get_absolute_url(self): return reverse("workflow:request_add", args=[self.uuid]) @staticmethod def get_extra_relational_fields(): return ["questions"] def create_request(self, **kwargs): if "assignee" not in kwargs and self.default_assignee: kwargs["assignee"] = self.default_assignee return Request.objects.create( request_template=self, content_type=self.content_type, dataspace=self.dataspace, **kwargs, ) class Question(DataspacedModel): """ Represent one field of a RequestTemplate Form. WARNING: Modifying the schema of this model will require data migration (next to the usual schema migration). """ template = models.ForeignKey( to="workflow.RequestTemplate", on_delete=models.CASCADE, related_name="questions", ) label = models.CharField( max_length=255, help_text=_("Label for the form input."), ) help_text = models.TextField( blank=True, help_text=_( "Descriptive text (instructions) to display to the Requestor below the " "question." ), ) # (django.forms.fields.Field class, description) INPUT_TYPE_CHOICES = ( ("CharField", _("Text")), ("TextField", _("Paragraph text")), ("BooleanField", _("Yes/No")), ("DateField", _("Date")), ) input_type = models.CharField( max_length=30, choices=INPUT_TYPE_CHOICES, ) is_required = models.BooleanField( default=False, help_text=_("Indicate if the requestor must enter a value in the answer"), ) position = models.PositiveSmallIntegerField() class Meta: ordering = ["position"] unique_together = ("dataspace", "uuid") def __str__(self): return self.label class RequestMixin(models.Model): """Provide fields and methods for Request related models.""" request_count = models.PositiveSmallIntegerField( blank=True, null=True, ) class Meta: abstract = True def get_requests(self, user): """ We could use django.contrib.contenttypes.fields.GenericRelation instead but we don't want to avoid the cascade-deletion behavior. Private requests are included in the QuerySet but their content is not displayed. """ return Request.objects.for_activity_tab(self, user) def count_requests(self): """ Return the count of Request objects attached to this instance. Bypass the Product secured system since we need the proper count but do not have a user to provide. """ return Request.objects.for_content_object(self).count() def update_request_count(self): """ Update the `request_count` field on the instance. Using update() rather than save() to avoid noise in the history. The update is only applied if the current stored count is not the true database count. Return True if the request_count was updated. """ model_class = self.__class__ # We should have default=0 on the `request_count` field instead strored_count = self.request_count or 0 true_count = self.count_requests() if strored_count != true_count: # Use the unsecured_manager to bypass the security system and get the proper count
# # Copyright (c) nexB Inc. and others. All rights reserved. # DejaCode is a trademark of nexB Inc. # SPDX-License-Identifier: AGPL-3.0-only # See https://github.com/nexB/dejacode for support or download. # See https://aboutcode.org for more information about AboutCode FOSS projects. # logger = logging.getLogger("dje") # Add `RequestMixin` to the following Model classes. # Also add a `display_name` on the Model API Serializer. CONTENT_TYPES = ( models.Q(app_label="component_catalog", model="component") | models.Q(app_label="component_catalog", model="package") | models.Q(app_label="license_library", model="license") | models.Q(app_label="product_portfolio", model="product") ) class Priority(DataspacedModel): label = models.CharField( max_length=50, help_text=_("Concise name to identify the Priority."), ) position = models.PositiveSmallIntegerField( null=True, blank=True, db_index=True, help_text=_( "A number to control the sequence of the Priorities presented to " "the user when selecting one from the dropdown list." ), ) color_code = models.CharField( max_length=7, blank=True, help_text=_( "You can specify a valid HTML color code (e.g. #FFFFFF) to apply " "to your Priority." ), ) class Meta: unique_together = (("dataspace", "label"), ("dataspace", "uuid")) ordering = ["position", "label"] verbose_name_plural = _("priorities") def __str__(self): return self.label class RequestQuerySet(DataspacedQuerySet): BASE_SELECT_RELATED = [ "request_template", "requester", "assignee", "priority", "product_context", "last_modified_by", ] def product_secured(self, user): if not user: return self.none() product_ct = ContentType.objects.get_by_natural_key("product_portfolio", "product") product_qs = product_ct.model_class().objects.get_queryset(user=user) return ( self.scope(user.dataspace) .filter( # If a product_context is set, Limit to authorized Products Q(product_context__isnull=True) | Q(product_context__in=product_qs), ) .exclude( # If a Product type content_object is set, excludes non-authorized Products Q(content_type=product_ct) & Q(object_id__isnull=False) & ~Q(object_id__in=product_qs), ) ) def unassigned(self): """Limit the QuerySet to unassigned Requests.""" return self.filter(assignee__isnull=True) def assigned_to(self, user): """Limit the QuerySet to Requests assigned to the given user.""" return self.filter(assignee=user) def created_by(self, user): """Limit the QuerySet to Requests created by the given user.""" return self.filter(requester=user) def followed_by(self, user): """ Limit the QuerySet to Requests followed by the given user: requester, assignee, commented or attached a file. """ return self.filter( Q(requester=user) | Q(assignee=user) | Q(comments__user=user) | Q(attachments__uploader=user) ) def open(self): return self.filter(status=Request.Status.OPEN) def closed(self): return self.filter(status=Request.Status.CLOSED) def with_comments_attachments_counts(self): return self.annotate( attachments_count=models.Count("attachments", distinct=True), comments_count=models.Count("comments", distinct=True), ) def for_list_view(self, user): return ( self.product_secured(user) .with_comments_attachments_counts() .select_related(*self.BASE_SELECT_RELATED) .prefetch_related( "content_object__dataspace", "product_context__dataspace", ) .distinct() ) def for_details_view(self, user): return ( self.product_secured(user) .select_related(*self.BASE_SELECT_RELATED) .prefetch_related( "attachments__uploader", "comments__user", ) ) def for_edit_view(self, user): return self.product_secured(user).select_related(*self.BASE_SELECT_RELATED) def for_content_object(self, content_object, user=None): """Limit the QuerySet to Requests attach to given `content_object`.""" base_qs = self.product_secured(user) if user else self return base_qs.filter( content_type=ContentType.objects.get_for_model(content_object), object_id=content_object.id, ) def for_activity_tab(self, content_object, user): return ( self.for_content_object(content_object, user) .with_comments_attachments_counts() .select_related(*self.BASE_SELECT_RELATED) ) class Request(HistoryDateFieldsMixin, DataspacedModel): request_template = models.ForeignKey( to="workflow.RequestTemplate", related_name="requests", on_delete=models.PROTECT, editable=False, ) class Status(models.TextChoices): OPEN = "open", _("Open") CLOSED = "closed", _("Closed") DRAFT = "draft", _("Draft") status = models.CharField( max_length=10, choices=Status.choices, default=Status.OPEN, db_index=True, help_text=_( 'Status of the request. "Draft" indicates that the request is not ' "yet ready for action, pending further details from the requestor. " '"Open" indicates that the assignee has not finished the requested ' "actions, and also that comments from all interested parties are " 'welcome. "Closed" indicates that no further actions or comments ' "are needed or expected." ), ) is_private = models.BooleanField( default=False, db_index=True, help_text=_( "When checked, the details of this request are visible only" " to the original requester and to request reviewers, and " "other users only see a limited summary. As an " "administrator, you can check or un-check this indicator to" " make a request private or public." ), ) notes = models.TextField( blank=True, help_text=_( "Notes from one or more request reviewers regarding " "research, issues, and conclusions related to the " "request." ), ) requester = models.ForeignKey( to=settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="request_as_requester", editable=False, help_text=_("Creator of the request."), ) assignee = models.ForeignKey( to=settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="request_as_assignee", limit_choices_to={"is_staff": True, "is_active": True}, null=True, blank=True, help_text=_( "The application user currently assigned to review the " "request and take appropriate action." ), ) product_context = models.ForeignKey( to="product_portfolio.Product", on_delete=models.SET_NULL, null=True, blank=True, # Bypass the validation in ForeignKey.validate() # Required since we do not have control over the QuerySet in that method. parent_link=True, help_text=_("Identify the Product impacted by your Request."), ) serialized_data = models.TextField( blank=True, help_text=_( "Optional data provided by the User making the request. " "Can be used by an Admin to pre-fill a form. Stored as " "JSON format." ), ) content_type = models.ForeignKey( to=ContentType, on_delete=models.PROTECT, limit_choices_to=CONTENT_TYPES, help_text=_( "Stores the type of the object requested. Supported types " "are Component, Package, License and Product" ), ) object_id = models.PositiveIntegerField( null=True, blank=True, db_index=True, help_text=_( "ID of the object attached to this request. This is used " "in combination with the content_type for the " "content_object field." ), ) # No need to be explicit about the content_type abd object_id field names as # we are using the default ones. content_object = GenericForeignKey() content_object_repr = models.CharField( max_length=1000, blank=True, help_text=_( "String representation of the attached content_object if any. " "This is useful for search purposes and not intended for display." ), ) priority = models.ForeignKey( to="workflow.Priority", on_delete=models.PROTECT, null=True, blank=True, help_text=_( "The priority is intended to provide team members with a guideline " "for selecting and assigning requests for additional action, based on the " "criticality of the request." ), ) title = models.CharField( max_length=255, db_index=True, help_text=_("The Request Title is a concise statement of the Request purpose and content."), ) cc_emails = ArrayField( base_field=models.EmailField(), null=True, blank=True, help_text=_( "You can provide a comma-separated list of email addresses to publish email " "notifications to any users that should be aware of the progress of this request." ), ) last_modified_by = LastModifiedByField() objects = DataspacedManager.from_queryset(RequestQuerySet)() class Meta: ordering = ["-last_modified_date"] unique_together = ("dataspace", "uuid") def __str__(self): return f"#{self.pk}" def save(self, *args, **kwargs): """Add the `update_request_count` logic on the related `content_object`.""" self.content_type = self.request_template.content_type # Store the repr of the content_object for search purposes. if self.object_id: # Bypass the broken GenericForeignKey.__get__ introduced in # https://github.com/django/django/commit/cc4cb95 try: self.content_object = self.content_type.get_object_for_this_type( id=self.object_id, ) except ObjectDoesNotExist: pass else: self.content_object_repr = str(self.content_object) # `previous_object_id` logic is only required on edition. previous_object_id = None is_addition = self.pk if is_addition: previous_object_id = self.__class__.objects.get(pk=self.pk).object_id super().save(*args, **kwargs) # Need to be post-save so the current Request exists in the DB before the count() if self.content_object and not self.is_draft: self.content_object.update_request_count() # The `content_object` was changed or removed, we need to update the `request_count` # of the previous object instance too. Warning: The previous object may not exist anymore. if previous_object_id and previous_object_id != self.object_id: try: previous_object = self.content_type.get_object_for_this_type(id=previous_object_id) except ObjectDoesNotExist: return previous_object.update_request_count() def get_absolute_url(self): return reverse("workflow:request_details", args=[self.uuid]) @property def details_url(self): return self.get_absolute_url() def get_serialized_data(self): if not self.serialized_data: return {} try: serialized_data = json.loads(self.serialized_data) except (ValueError, TypeError): return {} if not isinstance(serialized_data, dict): return {} return serialized_data def get_serialized_data_as_list(self): """Return a python iterable from the serialized_data field.""" serialized_data = self.get_serialized_data() if not serialized_data: return [] return [ { "label": question.label, "input_type": question.input_type, "value": serialized_data.get(question.label), } for question in self.request_template.questions.all() ] def get_serialized_data_as_html(self, html_template="{label}: {value}", separator="<br>"): """Return a HTML content of the serialized_data.""" serialized_data = [] for data in self.get_serialized_data_as_list(): try: value = data["value"] if data["input_type"] == "BooleanField": value = "Yes" if bool(data.get("value")) == 1 else "No" line = str(html_template).format(label=data["label"], value=escape(value)) except KeyError: return 'Error in the "Serialized data" value.' else: serialized_data.append(line) return format_html(separator.join(serialized_data)) @property def serialized_data_html(self): return self.get_serialized_data_as_html() @property def is_open(self): return self.status == self.Status.OPEN @property def is_closed(self): return self.status == self.Status.CLOSED @property def is_draft(self): return self.status == self.Status.DRAFT def has_details_permission(self, user): """ Private Requests are not available to regular user unless he is the requester or is an administrator. """ return user == self.requester or user.is_staff or not self.is_private def has_edit_permission(self, user): """ Only the requester or an administrator can edit a Request, unless the Request is closed already. """ return (user == self.requester or user.is_staff) and not self.is_closed def has_close_permission(self, user): """Only the requester can close a Request if not closed already.""" return user == self.requester and not self.is_closed def get_involved_users(self, exclude=None): """ Return the set of users involved is the Requests: - requestor - assignee - edited by (multiple) - commented by (multiple) """ users = { self.requester, *(event.user for event in self.events.all()), *(comment.user for comment in self.comments.all()), } # The assignee is now required on the RequestForm but not on the Request model. # Keeping this condition for compatibility with old Request instances. if self.assignee: users.add(self.assignee) if exclude: users.discard(exclude) return users def serialize_hook(self, hook): if "hooks.slack.com" in hook.target: return request_slack_payload(self, created="added" in hook.event) serializer = RequestSerializer(self, context={"request": None}) return { "hook": hook.dict(), "data": serializer.data, } @receiver(models.signals.post_delete, sender=Request) def update_request_count_on_delete(sender, instance=None, **kwargs): """ Update the `request_count` on the content_object after deleting the Request instance. Using the `post_delete` signal instead of overriding the `delete()` method as it ensure this logic gets executed on bulk deletion as well. See https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods """ if instance.object_id and instance.content_object: instance.content_object.update_request_count() class AbstractRequestEvent(HistoryDateFieldsMixin, DataspacedModel): user = models.ForeignKey( to=settings.AUTH_USER_MODEL, on_delete=models.PROTECT, editable=False, ) text = models.TextField() class Meta: abstract = True class RequestEvent(AbstractRequestEvent): request = models.ForeignKey( to="workflow.Request", on_delete=models.CASCADE, related_name="events", ) EDIT = 1 ATTACHMENT = 2 CLOSED = 3 EVENT_TYPE_CHOICES = ( (EDIT, "Edition"), (ATTACHMENT, "Attachment"), (CLOSED, "Closed"), ) event_type = models.IntegerField( choices=EVENT_TYPE_CHOICES, ) class Meta: ordering = ["created_date"] unique_together = ("dataspace", "uuid") def __str__(self): return f"{self.get_event_type_display()} by {self.user.username}" class RequestComment(AbstractRequestEvent): request = models.ForeignKey( to="workflow.Request", on_delete=models.CASCADE, related_name="comments", ) class Meta: ordering = ["created_date"] unique_together = ("dataspace", "uuid") def __str__(self): return f"{self.user.username}: {self.text[:50]}..." def has_delete_permission(self, user): """ Only the Commenter or an administrator with the proper permissions can delete a Comment. """ return user == self.user or ( user.is_staff and user.has_perm("workflow.delete_requestcomment") ) def as_html(self): """ Convert user provided commented content into HTML using markdown. The URLs are converted into links using the bleach Linkify feature. The HTML code is sanitized using bleach to prevent XSS attacks. The clean needs to be applied to the Markdown’s output, not the input. See https://michelf.ca/blog/2010/markdown-and-xss/ for details. See also the chapter about safe mode in https://python-markdown.github.io/change_log/release-3.0/ """ unsafe_html = markdown.markdown( text=self.text, extensions=["markdown.extensions.nl2br"], ) # Using `Cleaner()` with the 1LinkifyFilter1 to clean and linkify in one pass. # See https://bleach.readthedocs.io/en/latest/linkify.html notes cleaner = Cleaner( tags=markdown_tags, attributes=markdown_attrs, filters=[LinkifyFilter], ) html = cleaner.clean(unsafe_html) return format_html(html) def serialize_hook(self, hook): if "hooks.slack.com" in hook.target: return request_comment_slack_payload(self) comment_serializer = RequestCommentSerializer(self, context={"request": None}) request_serializer = RequestSerializer(self.request, context={"request": None}) data = comment_serializer.data data["request"] = request_serializer.data return { "hook": hook.dict(), "data": data, } class RequestTemplateQuerySet(DataspacedQuerySet): def actives(self): return self.filter(is_active=True) def for_content_type(self, content_type): """ Return the active RequestTemplate instances within a given dataspace for a given model class using the content_type. """ return self.filter(content_type=content_type) class RequestTemplate(HistoryFieldsMixin, DataspacedModel): """ WARNING: Modifying the schema of this model will require data migration (next to the usual schema migration). """ name = models.CharField( max_length=100, help_text=_("Unique name of the template."), ) description = models.TextField( verbose_name=_("Request header text"), help_text=_( "Provide a title and/or general instructions to the Requestor about this " "Request form." ), ) content_type = models.ForeignKey( to=ContentType, on_delete=models.PROTECT, verbose_name=_("object type"), limit_choices_to=CONTENT_TYPES, help_text=_("You can define one Request Template for each application object."), ) is_active = models.BooleanField( default=False, db_index=True, help_text=_( "Enable this to set the current form active. " "Only one Form can be active per content type." ), ) include_applies_to = models.BooleanField( default=True, help_text=_( 'Enable this to present an "Applies to" field to a requester creating a ' "request based on this template, or anyone subsequently editing that request. " 'Disable it for a request that does not need an "Applies to" reference.' ), ) include_product = models.BooleanField( default=False, help_text=_( "Enable this to present a Product choice to a requester using this template. " "Disable it for a request that does not need a Product context." ), ) default_assignee = models.ForeignKey( to=settings.AUTH_USER_MODEL, limit_choices_to={"is_staff": True, "is_active": True}, on_delete=models.SET_NULL, null=True, blank=True, serialize=False, help_text=_( "Optionally specify the application user that should be the first to review " "a request using this template, and should receive an email when the request " "is submitted." ), ) objects = DataspacedManager.from_queryset(RequestTemplateQuerySet)() class Meta: unique_together = (("dataspace", "name"), ("dataspace", "uuid")) ordering = ["name"] def __str__(self): return self.name def get_absolute_url(self): return reverse("workflow:request_add", args=[self.uuid]) @staticmethod def get_extra_relational_fields(): return ["questions"] def create_request(self, **kwargs): if "assignee" not in kwargs and self.default_assignee: kwargs["assignee"] = self.default_assignee return Request.objects.create( request_template=self, content_type=self.content_type, dataspace=self.dataspace, **kwargs, ) class Question(DataspacedModel): """ Represent one field of a RequestTemplate Form. WARNING: Modifying the schema of this model will require data migration (next to the usual schema migration). """ template = models.ForeignKey( to="workflow.RequestTemplate", on_delete=models.CASCADE, related_name="questions", ) label = models.CharField( max_length=255, help_text=_("Label for the form input."), ) help_text = models.TextField( blank=True, help_text=_( "Descriptive text (instructions) to display to the Requestor below the " "question." ), ) # (django.forms.fields.Field class, description) INPUT_TYPE_CHOICES = ( ("CharField", _("Text")), ("TextField", _("Paragraph text")), ("BooleanField", _("Yes/No")), ("DateField", _("Date")), ) input_type = models.CharField( max_length=30, choices=INPUT_TYPE_CHOICES, ) is_required = models.BooleanField( default=False, help_text=_("Indicate if the requestor must enter a value in the answer"), ) position = models.PositiveSmallIntegerField() class Meta: ordering = ["position"] unique_together = ("dataspace", "uuid") def __str__(self): return self.label class RequestMixin(models.Model): """Provide fields and methods for Request related models.""" request_count = models.PositiveSmallIntegerField( blank=True, null=True, ) class Meta: abstract = True def get_requests(self, user): """ We could use django.contrib.contenttypes.fields.GenericRelation instead but we don't want to avoid the cascade-deletion behavior. Private requests are included in the QuerySet but their content is not displayed. """ return Request.objects.for_activity_tab(self, user) def count_requests(self): """ Return the count of Request objects attached to this instance. Bypass the Product secured system since we need the proper count but do not have a user to provide. """ return Request.objects.for_content_object(self).count() def update_request_count(self): """ Update the `request_count` field on the instance. Using update() rather than save() to avoid noise in the history. The update is only applied if the current stored count is not the true database count. Return True if the request_count was updated. """ model_class = self.__class__ # We should have default=0 on the `request_count` field instead strored_count = self.request_count or 0 true_count = self.count_requests() if strored_count != true_count: # Use the unsecured_manager to bypass the security system and get the proper count
get_unsecured_manager(model_class).filter(pk=self.pk).update(request_count=true_count)
6
2023-12-07 16:57:42+00:00
12k
wusize/CLIM
src/open_clip/eva_clip/model.py
[ { "identifier": "ModifiedResNet", "path": "src/open_clip/eva_clip/modified_resnet.py", "snippet": "class ModifiedResNet(nn.Module):\n \"\"\"\n A ResNet class that is similar to torchvision's but contains the following changes:\n - There are now 3 \"stem\" convolutions as opposed to 1, with an a...
import os import numpy as np import torch import torch.nn.functional as F import xformers.ops as xops from dataclasses import dataclass from typing import Optional, Tuple, Union from functools import partial from torch import nn from .hf_model import HFTextEncoder from .modified_resnet import ModifiedResNet from .timm_model import TimmModel from .eva_vit_model import EVAVisionTransformer from .transformer import LayerNorm, QuickGELU, Attention, VisionTransformer, TextTransformer from apex.normalization import FusedLayerNorm
10,187
""" CLIP Model Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. """ try: except: HFTextEncoder = None try: except: FusedLayerNorm = LayerNorm print("Please 'pip install apex'") try: except ImportError: xops = None print("Please 'pip install xformers'") @dataclass class CLIPVisionCfg: layers: Union[Tuple[int, int, int, int], int] = 12 width: int = 768 head_width: int = 64 mlp_ratio: float = 4.0 patch_size: int = 16 image_size: Union[Tuple[int, int], int] = 224 ls_init_value: Optional[float] = None # layer scale initial value patch_dropout: float = 0. # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580) drop_path_rate: Optional[float] = None # drop path rate timm_model_name: str = None # a valid model name overrides layers, width, patch_size timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model timm_pool: str = 'avg' # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '') timm_proj: str = 'linear' # linear projection for timm model output ('linear', 'mlp', '') timm_proj_bias: bool = False # enable bias final projection eva_model_name: str = None # a valid eva model name overrides layers, width, patch_size qkv_bias: bool = True fusedLN: bool = False xattn: bool = False postnorm: bool = False rope: bool = False pt_hw_seq_len: int = 16 # 224/14 intp_freq: bool = False naiveswiglu: bool = False subln: bool = False @dataclass class CLIPTextCfg: context_length: int = 77 vocab_size: int = 49408 width: int = 512 heads: int = 8 layers: int = 12 ls_init_value: Optional[float] = None # layer scale initial value hf_model_name: str = None hf_tokenizer_name: str = None hf_model_pretrained: bool = True proj: str = 'mlp' pooler_type: str = 'mean_pooler' masked_language_modeling: bool = False fusedLN: bool = False xattn: bool = False attn_mask: bool = True def get_cast_dtype(precision: str): cast_dtype = None if precision == 'bf16': cast_dtype = torch.bfloat16 elif precision == 'fp16': cast_dtype = torch.float16 return cast_dtype def _build_vision_tower( embed_dim: int, vision_cfg: CLIPVisionCfg, quick_gelu: bool = False, cast_dtype: Optional[torch.dtype] = None ): if isinstance(vision_cfg, dict): vision_cfg = CLIPVisionCfg(**vision_cfg) # OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more # memory efficient in recent PyTorch releases (>= 1.10). # NOTE: timm models always use native GELU regardless of quick_gelu flag. act_layer = QuickGELU if quick_gelu else nn.GELU if vision_cfg.eva_model_name: vision_heads = vision_cfg.width // vision_cfg.head_width norm_layer = LayerNorm
""" CLIP Model Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. """ try: except: HFTextEncoder = None try: except: FusedLayerNorm = LayerNorm print("Please 'pip install apex'") try: except ImportError: xops = None print("Please 'pip install xformers'") @dataclass class CLIPVisionCfg: layers: Union[Tuple[int, int, int, int], int] = 12 width: int = 768 head_width: int = 64 mlp_ratio: float = 4.0 patch_size: int = 16 image_size: Union[Tuple[int, int], int] = 224 ls_init_value: Optional[float] = None # layer scale initial value patch_dropout: float = 0. # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580) drop_path_rate: Optional[float] = None # drop path rate timm_model_name: str = None # a valid model name overrides layers, width, patch_size timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model timm_pool: str = 'avg' # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '') timm_proj: str = 'linear' # linear projection for timm model output ('linear', 'mlp', '') timm_proj_bias: bool = False # enable bias final projection eva_model_name: str = None # a valid eva model name overrides layers, width, patch_size qkv_bias: bool = True fusedLN: bool = False xattn: bool = False postnorm: bool = False rope: bool = False pt_hw_seq_len: int = 16 # 224/14 intp_freq: bool = False naiveswiglu: bool = False subln: bool = False @dataclass class CLIPTextCfg: context_length: int = 77 vocab_size: int = 49408 width: int = 512 heads: int = 8 layers: int = 12 ls_init_value: Optional[float] = None # layer scale initial value hf_model_name: str = None hf_tokenizer_name: str = None hf_model_pretrained: bool = True proj: str = 'mlp' pooler_type: str = 'mean_pooler' masked_language_modeling: bool = False fusedLN: bool = False xattn: bool = False attn_mask: bool = True def get_cast_dtype(precision: str): cast_dtype = None if precision == 'bf16': cast_dtype = torch.bfloat16 elif precision == 'fp16': cast_dtype = torch.float16 return cast_dtype def _build_vision_tower( embed_dim: int, vision_cfg: CLIPVisionCfg, quick_gelu: bool = False, cast_dtype: Optional[torch.dtype] = None ): if isinstance(vision_cfg, dict): vision_cfg = CLIPVisionCfg(**vision_cfg) # OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more # memory efficient in recent PyTorch releases (>= 1.10). # NOTE: timm models always use native GELU regardless of quick_gelu flag. act_layer = QuickGELU if quick_gelu else nn.GELU if vision_cfg.eva_model_name: vision_heads = vision_cfg.width // vision_cfg.head_width norm_layer = LayerNorm
visual = EVAVisionTransformer(
2
2023-12-09 05:43:08+00:00
12k
moonshot-admin/moonshot
third-party/pathspec-0.12.1/pathspec/gitignore.py
[ { "identifier": "PathSpec", "path": "third-party/pathspec-0.12.1/pathspec/pathspec.py", "snippet": "class PathSpec(object):\n\t\"\"\"\n\tThe :class:`PathSpec` class is a wrapper around a list of compiled\n\t:class:`.Pattern` instances.\n\t\"\"\"\n\n\tdef __init__(self, patterns: Iterable[Pattern]) -> No...
from typing import ( AnyStr, Callable, # Replaced by `collections.abc.Callable` in 3.9. Iterable, # Replaced by `collections.abc.Iterable` in 3.9. Optional, # Replaced by `X | None` in 3.10. Tuple, # Replaced by `tuple` in 3.9. Type, # Replaced by `type` in 3.9. TypeVar, Union, # Replaced by `X | Y` in 3.10. cast, overload) from .pathspec import ( PathSpec) from .pattern import ( Pattern) from .patterns.gitwildmatch import ( GitWildMatchPattern, _DIR_MARK) from .util import ( _is_iterable)
9,145
""" This module provides :class:`.GitIgnoreSpec` which replicates *.gitignore* behavior. """ Self = TypeVar("Self", bound="GitIgnoreSpec") """ :class:`GitIgnoreSpec` self type hint to support Python v<3.11 using PEP 673 recommendation. """ class GitIgnoreSpec(PathSpec): """ The :class:`GitIgnoreSpec` class extends :class:`pathspec.pathspec.PathSpec` to replicate *.gitignore* behavior. """ def __eq__(self, other: object) -> bool: """ Tests the equality of this gitignore-spec with *other* (:class:`GitIgnoreSpec`) by comparing their :attr:`~pathspec.pattern.Pattern` attributes. A non-:class:`GitIgnoreSpec` will not compare equal. """ if isinstance(other, GitIgnoreSpec): return super().__eq__(other) elif isinstance(other, PathSpec): return False else: return NotImplemented # Support reversed order of arguments from PathSpec. @overload @classmethod def from_lines( cls: Type[Self], pattern_factory: Union[str, Callable[[AnyStr], Pattern]], lines: Iterable[AnyStr], ) -> Self: ... @overload @classmethod def from_lines( cls: Type[Self], lines: Iterable[AnyStr], pattern_factory: Union[str, Callable[[AnyStr], Pattern], None] = None, ) -> Self: ... @classmethod def from_lines( cls: Type[Self], lines: Iterable[AnyStr], pattern_factory: Union[str, Callable[[AnyStr], Pattern], None] = None, ) -> Self: """ Compiles the pattern lines. *lines* (:class:`~collections.abc.Iterable`) yields each uncompiled pattern (:class:`str`). This simply has to yield each line so it can be a :class:`io.TextIOBase` (e.g., from :func:`open` or :class:`io.StringIO`) or the result from :meth:`str.splitlines`. *pattern_factory* can be :data:`None`, the name of a registered pattern factory (:class:`str`), or a :class:`~collections.abc.Callable` used to compile patterns. The callable must accept an uncompiled pattern (:class:`str`) and return the compiled pattern (:class:`pathspec.pattern.Pattern`). Default is :data:`None` for :class:`.GitWildMatchPattern`). Returns the :class:`GitIgnoreSpec` instance. """ if pattern_factory is None: pattern_factory = GitWildMatchPattern elif (isinstance(lines, (str, bytes)) or callable(lines)) and _is_iterable(pattern_factory): # Support reversed order of arguments from PathSpec. pattern_factory, lines = lines, pattern_factory self = super().from_lines(pattern_factory, lines) return cast(Self, self) @staticmethod def _match_file( patterns: Iterable[Tuple[int, GitWildMatchPattern]], file: str, ) -> Tuple[Optional[bool], Optional[int]]: """ Check the file against the patterns. .. NOTE:: Subclasses of :class:`~pathspec.pathspec.PathSpec` may override this method as an instance method. It does not have to be a static method. The signature for this method is subject to change. *patterns* (:class:`~collections.abc.Iterable`) yields each indexed pattern (:class:`tuple`) which contains the pattern index (:class:`int`) and actual pattern (:class:`~pathspec.pattern.Pattern`). *file* (:class:`str`) is the normalized file path to be matched against *patterns*. Returns a :class:`tuple` containing whether to include *file* (:class:`bool` or :data:`None`), and the index of the last matched pattern (:class:`int` or :data:`None`). """ out_include: Optional[bool] = None out_index: Optional[int] = None out_priority = 0 for index, pattern in patterns: if pattern.include is not None: match = pattern.match_file(file) if match is not None: # Pattern matched. # Check for directory marker.
""" This module provides :class:`.GitIgnoreSpec` which replicates *.gitignore* behavior. """ Self = TypeVar("Self", bound="GitIgnoreSpec") """ :class:`GitIgnoreSpec` self type hint to support Python v<3.11 using PEP 673 recommendation. """ class GitIgnoreSpec(PathSpec): """ The :class:`GitIgnoreSpec` class extends :class:`pathspec.pathspec.PathSpec` to replicate *.gitignore* behavior. """ def __eq__(self, other: object) -> bool: """ Tests the equality of this gitignore-spec with *other* (:class:`GitIgnoreSpec`) by comparing their :attr:`~pathspec.pattern.Pattern` attributes. A non-:class:`GitIgnoreSpec` will not compare equal. """ if isinstance(other, GitIgnoreSpec): return super().__eq__(other) elif isinstance(other, PathSpec): return False else: return NotImplemented # Support reversed order of arguments from PathSpec. @overload @classmethod def from_lines( cls: Type[Self], pattern_factory: Union[str, Callable[[AnyStr], Pattern]], lines: Iterable[AnyStr], ) -> Self: ... @overload @classmethod def from_lines( cls: Type[Self], lines: Iterable[AnyStr], pattern_factory: Union[str, Callable[[AnyStr], Pattern], None] = None, ) -> Self: ... @classmethod def from_lines( cls: Type[Self], lines: Iterable[AnyStr], pattern_factory: Union[str, Callable[[AnyStr], Pattern], None] = None, ) -> Self: """ Compiles the pattern lines. *lines* (:class:`~collections.abc.Iterable`) yields each uncompiled pattern (:class:`str`). This simply has to yield each line so it can be a :class:`io.TextIOBase` (e.g., from :func:`open` or :class:`io.StringIO`) or the result from :meth:`str.splitlines`. *pattern_factory* can be :data:`None`, the name of a registered pattern factory (:class:`str`), or a :class:`~collections.abc.Callable` used to compile patterns. The callable must accept an uncompiled pattern (:class:`str`) and return the compiled pattern (:class:`pathspec.pattern.Pattern`). Default is :data:`None` for :class:`.GitWildMatchPattern`). Returns the :class:`GitIgnoreSpec` instance. """ if pattern_factory is None: pattern_factory = GitWildMatchPattern elif (isinstance(lines, (str, bytes)) or callable(lines)) and _is_iterable(pattern_factory): # Support reversed order of arguments from PathSpec. pattern_factory, lines = lines, pattern_factory self = super().from_lines(pattern_factory, lines) return cast(Self, self) @staticmethod def _match_file( patterns: Iterable[Tuple[int, GitWildMatchPattern]], file: str, ) -> Tuple[Optional[bool], Optional[int]]: """ Check the file against the patterns. .. NOTE:: Subclasses of :class:`~pathspec.pathspec.PathSpec` may override this method as an instance method. It does not have to be a static method. The signature for this method is subject to change. *patterns* (:class:`~collections.abc.Iterable`) yields each indexed pattern (:class:`tuple`) which contains the pattern index (:class:`int`) and actual pattern (:class:`~pathspec.pattern.Pattern`). *file* (:class:`str`) is the normalized file path to be matched against *patterns*. Returns a :class:`tuple` containing whether to include *file* (:class:`bool` or :data:`None`), and the index of the last matched pattern (:class:`int` or :data:`None`). """ out_include: Optional[bool] = None out_index: Optional[int] = None out_priority = 0 for index, pattern in patterns: if pattern.include is not None: match = pattern.match_file(file) if match is not None: # Pattern matched. # Check for directory marker.
dir_mark = match.match.groupdict().get(_DIR_MARK)
3
2023-12-14 07:43:03+00:00
12k
pan-x-c/EE-LLM
tests/unit_tests/transformer/test_spec_customization.py
[ { "identifier": "get_bias_dropout_add", "path": "megatron/core/fusions/fused_bias_dropout.py", "snippet": "def get_bias_dropout_add(training, fused):\n if fused:\n # jit scripting for a nn.module (with dropout) is not\n # triggering the fusion kernel. For now, we use two\n # diff...
from dataclasses import dataclass, fields from megatron.core.fusions.fused_bias_dropout import get_bias_dropout_add from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed from megatron.core.transformer.attention import SelfAttention, SelfAttentionSubmodules from megatron.core.transformer.custom_layers.transformer_engine import ( TEDotProductAttention, TELayerNormColumnParallelLinear, TENorm, TERowParallelLinear, ) from megatron.core.transformer.enums import AttnMaskType from megatron.core.transformer.identity_op import IdentityFuncOp, IdentityOp from megatron.core.transformer.spec_utils import ModuleSpec, build_module, import_module from megatron.core.transformer.transformer_config import TransformerConfig from megatron.core.transformer.transformer_layer import TransformerLayerSubmodules from tests.unit_tests.test_utilities import Utils import pytest import torch import transformer_engine as te
7,730
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. class TestSpecCustomization: def setup_method(self, method): Utils.initialize_model_parallel(1, 1) model_parallel_cuda_manual_seed(123) self.config = TransformerConfig( num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True ) # specify Transformer Layer spec with all identity ops self.transformer_layer_spec = TransformerLayerSubmodules() # specify attention spec using already imported class self.attention_spec = ModuleSpec( module=SelfAttention, params={"attn_mask_type": AttnMaskType.causal},
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. class TestSpecCustomization: def setup_method(self, method): Utils.initialize_model_parallel(1, 1) model_parallel_cuda_manual_seed(123) self.config = TransformerConfig( num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True ) # specify Transformer Layer spec with all identity ops self.transformer_layer_spec = TransformerLayerSubmodules() # specify attention spec using already imported class self.attention_spec = ModuleSpec( module=SelfAttention, params={"attn_mask_type": AttnMaskType.causal},
submodules=SelfAttentionSubmodules(
3
2023-12-07 08:29:38+00:00
12k
mitrefireline/simharness
main.py
[ { "identifier": "RenderEnv", "path": "simharness2/callbacks/render_env.py", "snippet": "class RenderEnv(DefaultCallbacks):\n \"\"\"To use this callback, set {\"callbacks\": RenderEnv} in the algo config.\"\"\"\n\n def on_algorithm_init(\n self,\n *,\n algorithm: \"Algorithm\",...
import logging import os import hydra import numpy as np import ray import simharness2.models # noqa from importlib import import_module from typing import Any, Dict, Tuple from hydra.core.hydra_config import HydraConfig from hydra.utils import instantiate from omegaconf import DictConfig, OmegaConf from ray import air, tune from ray.rllib.algorithms.algorithm import Algorithm from ray.rllib.algorithms.algorithm_config import AlgorithmConfig from ray.tune.logger import pretty_print from ray.tune.registry import get_trainable_cls, register_env from ray.tune.result_grid import ResultGrid from simfire.enums import BurnStatus from simharness2.callbacks.render_env import RenderEnv from simharness2.logger.aim import AimLoggerCallback
8,062
for i in range(stop_cond.training_iteration): LOGGER.info(f"Training iteration {i}.") result = algo.train() LOGGER.info(f"{pretty_print(result)}\n") if i % cfg.checkpoint.checkpoint_frequency == 0: ckpt_path = algo.save() log_str = f"A checkpoint has been created inside directory: {ckpt_path}.\n" LOGGER.info(log_str) if ( result["timesteps_total"] >= stop_cond.timesteps_total or result["episode_reward_mean"] >= stop_cond.episode_reward_mean ): LOGGER.warning(f"Training stopped short at iteration {i}.\n") ts = result["timesteps_total"] mean_rew = result["episode_reward_mean"] LOGGER.info(f"Timesteps: {ts}\nEpisode_Mean_Rewards: {mean_rew}\n") break model_path = algo.save() LOGGER.info(f"The final model has been saved inside directory: {model_path}.") algo.stop() def _instantiate_config( cfg: DictConfig, ) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any], Dict[str, Any]]: """Instantiate the algorithm config used to build the RLlib training algorithm. Args: cfg (DictConfig): Hydra config with all required parameters. Returns: Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any], Dict[str, Any]]: env_settings: Parameters needed for instantiating the environment eval_settings: Parameters needed for running the evaluation code. debug_settings: Settings needed for debugging. exploration_cfg: RLlib exploration configurations. """ # Instantiate the env and eval settings objects from the config. # NOTE: We are instantiating to a NEW object on purpose; otherwise a # `TypeError` will be raised when attempting to log the cfg to Aim. env_settings = instantiate(cfg.environment, _convert_="partial") eval_settings = instantiate(cfg.evaluation, _convert_="partial") # FIXME: Fire scenario configuration disabled for now. Fix this in new MR. # Get the operational fires we want to run evaluation with # operational_fires = get_default_operational_fires(cfg) # Inject operational fires into the evaluation settings # eval_settings["evaluation_config"]["env_config"].update( # {"scenarios": operational_fires} # ) # Prepare exploration options for the algorithm exploration_cfg = OmegaConf.to_container( cfg=cfg.exploration.exploration_config, resolve=True ) # If no `type` is given, tune's `UnifiedLogger` is used as follows: # DEFAULT_LOGGERS = (JsonLogger, CSVLogger, TBXLogger) # `UnifiedLogger(config, self._logdir, loggers=DEFAULT_LOGGERS)` # - The `logger_config` defined below is used here: # https://github.com/ray-project/ray/blob/863928c4f13b66465399d63e01df3c446b4536d9/rllib/algorithms/algorithm.py#L423 # - The `Trainable._create_logger` method can be found here: # https://github.com/ray-project/ray/blob/8d2dc9a3997482100034b60568b06aad7fd9fc59/python/ray/tune/trainable/trainable.py#L1067 debug_settings = instantiate(cfg.debugging, _convert_="partial") # Register the environment with Ray # NOTE: Assume that same environment cls is used for training and evaluation. # TODO: This blocks us from being able to have `view()` can we change this? env_module, env_cls = cfg.environment.env.rsplit(".", 1) env_cls = getattr(import_module(env_module), env_cls) register_env(cfg.environment.env, lambda config: env_cls(**config)) return env_settings, eval_settings, debug_settings, exploration_cfg def _build_algo_cfg(cfg: DictConfig) -> Tuple[Algorithm, AlgorithmConfig]: """Build the algorithm config and object for training an RLlib model. Args: cfg (DictConfig): Hydra config with all required parameters. Returns: Tuple(Algorithm, AlgorithmConfig): Training algorithm and associated config. """ # Instantiate everything necessary for creating the algorithm config. env_settings, eval_settings, debug_settings, explor_cfg = _instantiate_config(cfg) # Manually prepare agent_ids using same logic as within environments/rl_harness.py num_agents = env_settings["env_config"].get("num_agents", 1) interacts = env_settings["env_config"]["interactions"] # map sh2 interactions to underlying BurnStatus category interacts_map = { "fireline": BurnStatus.FIRELINE, "wetline": BurnStatus.WETLINE, "scratchline": BurnStatus.SCRATCHLINE, } agent_id_start = ( max(set([int(v) for k, v in interacts_map.items() if k in interacts])) + 1 ) agent_id_stop = agent_id_start + num_agents sim_agent_ids = np.arange(agent_id_start, agent_id_stop) # FIXME: Usage of "agent_{}" doesn't allow us to delineate agents groups. agent_ids = {f"agent_{i}" for i in sim_agent_ids} algo_cfg = ( get_trainable_cls(cfg.algo.name) .get_default_config() .training(**cfg.training) .environment(**env_settings) .framework(**cfg.framework) .rollouts(**cfg.rollouts) .evaluation(**eval_settings) .exploration(explore=cfg.exploration.explore, exploration_config=explor_cfg) .resources(**cfg.resources) .debugging(**debug_settings)
"""FIXME: A one line summary of the module or program. Leave one blank line. The rest of this docstring should contain an overall description of the module or program. Optionally, it may also contain a brief description of exported classes and functions and/or usage examples. Typical usage example: foo = ClassFoo() bar = foo.FunctionBar() """ # from simharness2.utils.evaluation_fires import get_default_operational_fires # from simharness2.callbacks.set_env_seeds_callback import SetEnvSeedsCallback os.environ["HYDRA_FULL_ERROR"] = "1" # Register custom resolvers that are used within the config files OmegaConf.register_new_resolver("operational_screen_size", lambda x: int(x * 39)) OmegaConf.register_new_resolver("calculate_half", lambda x: int(x / 2)) OmegaConf.register_new_resolver("square", lambda x: x**2) LOGGER = logging.getLogger(__name__) def _set_variable_hyperparameters(algo_cfg: AlgorithmConfig, cfg: DictConfig) -> None: """Override the algo_cfg hyperparameters we would like to tune over. Args: algo_cfg (AlgorithmConfig): Config used for training our model. cfg (DictConfig): Hydra config with all required parameters. """ tunables = OmegaConf.to_container(cfg.tunables, resolve=True) for section_key, param_dict in tunables.items(): for key, value in param_dict.items(): if value["type"] == "loguniform": sampler = tune.loguniform(value["values"][0], value["values"][1]) elif value["type"] == "uniform": sampler = tune.uniform(value["values"][0], value["values"][1]) elif value["type"] == "random": sampler = tune.randint(value["values"][0], value["values"][1]) elif value["type"] == "choice": sampler = tune.choice(value["values"]) else: LOGGER.error(f"Invalid value type {value['type']} given - skipping.") tunables[section_key][key] = sampler algo_cfg.training(**tunables["training"]) def train_with_tune(algo_cfg: AlgorithmConfig, cfg: DictConfig) -> ResultGrid: """Iterate through combinations of hyperparameters to find optimal training runs. Args: algo_cfg (AlgorithmConfig): Algorithm config for RLlib. cfg (DictConfig): Hydra config with all required parameters. Returns: ResultGrid: Set of Results objects from running Tuner.fit() """ trainable_algo_str = cfg.algo.name param_space = algo_cfg # Override the variables we want to tune on ()`param_space` is updated in-place). if cfg.tunables: _set_variable_hyperparameters(algo_cfg=param_space, cfg=cfg) # Configs for this specific trial run run_config = air.RunConfig( name=cfg.run.name or None, storage_path=cfg.run.storage_path, stop={**cfg.stop_conditions}, callbacks=[AimLoggerCallback(cfg=cfg, **cfg.aim)], failure_config=None, sync_config=tune.SyncConfig(syncer=None), # Disable syncing checkpoint_config=air.CheckpointConfig(**cfg.checkpoint), log_to_file=cfg.run.log_to_file, ) # TODO make sure 'reward' is reported with tune.report() # TODO add this to config # Config for the tuning process (used for all trial runs) # tune_config = tune.TuneConfig(num_samples=4) # Create a Tuner tuner = tune.Tuner( trainable=trainable_algo_str, param_space=param_space, run_config=run_config, # tune_config=tune_config, ) results = tuner.fit() result_df = results.get_dataframe() logging.debug(result_df) return results def train(algo: Algorithm, cfg: DictConfig) -> None: """Train the given algorithm within RLlib. Args: algo (Algorithm): Algorithm to train with. cfg (DictConfig): Hydra config with all required parameters for training. """ stop_cond = cfg.stop_conditions # Run training loop and print results after each iteration for i in range(stop_cond.training_iteration): LOGGER.info(f"Training iteration {i}.") result = algo.train() LOGGER.info(f"{pretty_print(result)}\n") if i % cfg.checkpoint.checkpoint_frequency == 0: ckpt_path = algo.save() log_str = f"A checkpoint has been created inside directory: {ckpt_path}.\n" LOGGER.info(log_str) if ( result["timesteps_total"] >= stop_cond.timesteps_total or result["episode_reward_mean"] >= stop_cond.episode_reward_mean ): LOGGER.warning(f"Training stopped short at iteration {i}.\n") ts = result["timesteps_total"] mean_rew = result["episode_reward_mean"] LOGGER.info(f"Timesteps: {ts}\nEpisode_Mean_Rewards: {mean_rew}\n") break model_path = algo.save() LOGGER.info(f"The final model has been saved inside directory: {model_path}.") algo.stop() def _instantiate_config( cfg: DictConfig, ) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any], Dict[str, Any]]: """Instantiate the algorithm config used to build the RLlib training algorithm. Args: cfg (DictConfig): Hydra config with all required parameters. Returns: Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any], Dict[str, Any]]: env_settings: Parameters needed for instantiating the environment eval_settings: Parameters needed for running the evaluation code. debug_settings: Settings needed for debugging. exploration_cfg: RLlib exploration configurations. """ # Instantiate the env and eval settings objects from the config. # NOTE: We are instantiating to a NEW object on purpose; otherwise a # `TypeError` will be raised when attempting to log the cfg to Aim. env_settings = instantiate(cfg.environment, _convert_="partial") eval_settings = instantiate(cfg.evaluation, _convert_="partial") # FIXME: Fire scenario configuration disabled for now. Fix this in new MR. # Get the operational fires we want to run evaluation with # operational_fires = get_default_operational_fires(cfg) # Inject operational fires into the evaluation settings # eval_settings["evaluation_config"]["env_config"].update( # {"scenarios": operational_fires} # ) # Prepare exploration options for the algorithm exploration_cfg = OmegaConf.to_container( cfg=cfg.exploration.exploration_config, resolve=True ) # If no `type` is given, tune's `UnifiedLogger` is used as follows: # DEFAULT_LOGGERS = (JsonLogger, CSVLogger, TBXLogger) # `UnifiedLogger(config, self._logdir, loggers=DEFAULT_LOGGERS)` # - The `logger_config` defined below is used here: # https://github.com/ray-project/ray/blob/863928c4f13b66465399d63e01df3c446b4536d9/rllib/algorithms/algorithm.py#L423 # - The `Trainable._create_logger` method can be found here: # https://github.com/ray-project/ray/blob/8d2dc9a3997482100034b60568b06aad7fd9fc59/python/ray/tune/trainable/trainable.py#L1067 debug_settings = instantiate(cfg.debugging, _convert_="partial") # Register the environment with Ray # NOTE: Assume that same environment cls is used for training and evaluation. # TODO: This blocks us from being able to have `view()` can we change this? env_module, env_cls = cfg.environment.env.rsplit(".", 1) env_cls = getattr(import_module(env_module), env_cls) register_env(cfg.environment.env, lambda config: env_cls(**config)) return env_settings, eval_settings, debug_settings, exploration_cfg def _build_algo_cfg(cfg: DictConfig) -> Tuple[Algorithm, AlgorithmConfig]: """Build the algorithm config and object for training an RLlib model. Args: cfg (DictConfig): Hydra config with all required parameters. Returns: Tuple(Algorithm, AlgorithmConfig): Training algorithm and associated config. """ # Instantiate everything necessary for creating the algorithm config. env_settings, eval_settings, debug_settings, explor_cfg = _instantiate_config(cfg) # Manually prepare agent_ids using same logic as within environments/rl_harness.py num_agents = env_settings["env_config"].get("num_agents", 1) interacts = env_settings["env_config"]["interactions"] # map sh2 interactions to underlying BurnStatus category interacts_map = { "fireline": BurnStatus.FIRELINE, "wetline": BurnStatus.WETLINE, "scratchline": BurnStatus.SCRATCHLINE, } agent_id_start = ( max(set([int(v) for k, v in interacts_map.items() if k in interacts])) + 1 ) agent_id_stop = agent_id_start + num_agents sim_agent_ids = np.arange(agent_id_start, agent_id_stop) # FIXME: Usage of "agent_{}" doesn't allow us to delineate agents groups. agent_ids = {f"agent_{i}" for i in sim_agent_ids} algo_cfg = ( get_trainable_cls(cfg.algo.name) .get_default_config() .training(**cfg.training) .environment(**env_settings) .framework(**cfg.framework) .rollouts(**cfg.rollouts) .evaluation(**eval_settings) .exploration(explore=cfg.exploration.explore, exploration_config=explor_cfg) .resources(**cfg.resources) .debugging(**debug_settings)
.callbacks(RenderEnv)
0
2023-12-08 19:13:31+00:00
12k
racinette/querky
querky/querky.py
[ { "identifier": "one_", "path": "querky/result_shape.py", "snippet": "def one_(typename: str | None, *, optional: bool = True) -> typing.Callable[[Query], ResultShape]:\n def late_binding(query: Query) -> One:\n return One(query, typename, optional=optional)\n return late_binding" }, { ...
import importlib import types import typing import inspect import os import logging from types import ModuleType from os import path from querky.result_shape import one_, all_, value_, status_, column_, One, All, ResultShape from querky.conn_param_config import ConnParamConfig, First from querky.annotation_generator import AnnotationGenerator from querky.type_constructor import TypeConstructor from querky.module_constructor import ModuleConstructor from querky.base_types import TypeMetaData from querky.query import Query from querky.contract import Contract
7,218
conn_param_config: ConnParamConfig | None = None, type_factory: typing.Callable[[Query, str], TypeConstructor] | None = None, subdir: str | None = "queries", on_before_func_code_emit: typing.Optional[typing.Callable[[typing.List[str], Query], typing.List[str]]] = None, on_before_type_code_emit: typing.Optional[typing.Callable[[typing.List[str], Query], typing.List[str]]] = None, imports: typing.Optional[typing.Set[str]] = None, indent: str = ' ', query_class: typing.Type[Query] = Query ): self.basedir = basedir self.on_before_func_code_emit = on_before_func_code_emit self.on_before_type_code_emit = on_before_type_code_emit self.query_class = query_class self.imports = imports or set() self.indent = indent self.annotation_generator = annotation_generator self.module_ctors: dict[types.ModuleType, ModuleConstructor] = dict() self.type_factory = type_factory if conn_param_config is None: conn_param_config = First(name='__conn', positional=True) self.conn_param_config = conn_param_config self.contract = contract self.subdir = subdir if self.subdir and not str.isidentifier(self.subdir): raise ValueError("subdir must be a valid python identifier") self.file_signature = "# ~ AUTOGENERATED BY QUERKY ~ #" def get_indent(self, i: int): return self.indent * i def create_query( self, fn: typing.Callable[[...], str], shape: typing.Callable[[Query], ResultShape], conn_param_config: ConnParamConfig | None, explicit_name: str | None, parent_query: typing.Optional[Query], kwargs: typing.Optional[typing.Dict[str, typing.Any]] ) -> Query: module = inspect.getmodule(fn) if module in self.module_ctors: module_ctor = self.module_ctors[module] else: filename = self.generate_filename(module) if not str.isidentifier(filename): raise ValueError(f"Generated a filename which is not a valid python identifier: {filename}") filedir = path.dirname(module.__file__) new_module_name = module.__name__.rsplit('.', maxsplit=1)[0] if self.subdir: filedir = path.join(filedir, self.subdir) new_module_name = f"{new_module_name}.{self.subdir}" fullpath = path.join(filedir, f'{filename}.py') new_module_name = f"{new_module_name}.{filename}" module_ctor = ModuleConstructor(self, module, fullpath, new_module_name, filedir) self.module_ctors[module] = module_ctor return self.query_class( fn, shape, module_ctor, self.conn_param_config or conn_param_config, explicit_name, parent_query, kwargs ) def query( self, arg: str | TypeMetaData | Query | typing.Callable[[...], str] | None = None, *, shape: ShapeStringRepr = 'status', optional: bool | None = None, **kwargs ) -> QueryDef | Query: def wrapper(fn: typing.Callable[[...], str]) -> Query: nonlocal optional if shape in ['many', 'one']: if isinstance(arg, TypeMetaData): raise ValueError( "TypeMetaData is not supported for `many` or `one` constructors. " "Use it only for `one` and `column` constructors." ) if not isinstance(arg, Query): if arg is None: # if we don't have a name provided for us, we're gonna create it out of the function name type_name = to_camel_case(fn.__name__) else: type_name = arg if not type_name.isidentifier(): raise ValueError(f"Name type should be a valid python identifier. You provided: {type_name}") else: type_name = None type_name: str | None if shape == 'many': if optional is not None: raise TypeError( 'ALL constructor does not accept `optional` flag -- ' 'at least an empty set will always be returned' ) created_shape = all_(type_name) else: if optional is None: optional = True
from __future__ import annotations logger = logging.getLogger("querky") def to_camel_case(snake_str): return "".join(x.capitalize() for x in snake_str.lower().split("_")) ShapeStringRepr = typing.Literal["one", "many", "column", "value", "status"] QueryDef = typing.Callable[[typing.Callable[[...], str]], Query] class Querky: def __init__( self, basedir: str | None = None, annotation_generator: AnnotationGenerator | None = None, contract: Contract | None = None, conn_param_config: ConnParamConfig | None = None, type_factory: typing.Callable[[Query, str], TypeConstructor] | None = None, subdir: str | None = "queries", on_before_func_code_emit: typing.Optional[typing.Callable[[typing.List[str], Query], typing.List[str]]] = None, on_before_type_code_emit: typing.Optional[typing.Callable[[typing.List[str], Query], typing.List[str]]] = None, imports: typing.Optional[typing.Set[str]] = None, indent: str = ' ', query_class: typing.Type[Query] = Query ): self.basedir = basedir self.on_before_func_code_emit = on_before_func_code_emit self.on_before_type_code_emit = on_before_type_code_emit self.query_class = query_class self.imports = imports or set() self.indent = indent self.annotation_generator = annotation_generator self.module_ctors: dict[types.ModuleType, ModuleConstructor] = dict() self.type_factory = type_factory if conn_param_config is None: conn_param_config = First(name='__conn', positional=True) self.conn_param_config = conn_param_config self.contract = contract self.subdir = subdir if self.subdir and not str.isidentifier(self.subdir): raise ValueError("subdir must be a valid python identifier") self.file_signature = "# ~ AUTOGENERATED BY QUERKY ~ #" def get_indent(self, i: int): return self.indent * i def create_query( self, fn: typing.Callable[[...], str], shape: typing.Callable[[Query], ResultShape], conn_param_config: ConnParamConfig | None, explicit_name: str | None, parent_query: typing.Optional[Query], kwargs: typing.Optional[typing.Dict[str, typing.Any]] ) -> Query: module = inspect.getmodule(fn) if module in self.module_ctors: module_ctor = self.module_ctors[module] else: filename = self.generate_filename(module) if not str.isidentifier(filename): raise ValueError(f"Generated a filename which is not a valid python identifier: {filename}") filedir = path.dirname(module.__file__) new_module_name = module.__name__.rsplit('.', maxsplit=1)[0] if self.subdir: filedir = path.join(filedir, self.subdir) new_module_name = f"{new_module_name}.{self.subdir}" fullpath = path.join(filedir, f'{filename}.py') new_module_name = f"{new_module_name}.{filename}" module_ctor = ModuleConstructor(self, module, fullpath, new_module_name, filedir) self.module_ctors[module] = module_ctor return self.query_class( fn, shape, module_ctor, self.conn_param_config or conn_param_config, explicit_name, parent_query, kwargs ) def query( self, arg: str | TypeMetaData | Query | typing.Callable[[...], str] | None = None, *, shape: ShapeStringRepr = 'status', optional: bool | None = None, **kwargs ) -> QueryDef | Query: def wrapper(fn: typing.Callable[[...], str]) -> Query: nonlocal optional if shape in ['many', 'one']: if isinstance(arg, TypeMetaData): raise ValueError( "TypeMetaData is not supported for `many` or `one` constructors. " "Use it only for `one` and `column` constructors." ) if not isinstance(arg, Query): if arg is None: # if we don't have a name provided for us, we're gonna create it out of the function name type_name = to_camel_case(fn.__name__) else: type_name = arg if not type_name.isidentifier(): raise ValueError(f"Name type should be a valid python identifier. You provided: {type_name}") else: type_name = None type_name: str | None if shape == 'many': if optional is not None: raise TypeError( 'ALL constructor does not accept `optional` flag -- ' 'at least an empty set will always be returned' ) created_shape = all_(type_name) else: if optional is None: optional = True
created_shape = one_(type_name, optional=optional)
0
2023-12-13 15:16:34+00:00
12k
javrtg/C2P
tests/test_constraints.py
[ { "identifier": "constraints", "path": "nonmin_pose/constraints/constraints.py", "snippet": "def assert_smaller_idxes(param1i, param2i):\n def __init__(self, name: str, block: int, block_ids: List[int]):\n def __init__(\n self,\n params: dict,\n idx_first_el: int,\n idx...
import numpy as np from nonmin_pose.constraints import constraints from nonmin_pose.constraints.constraints import Parameter from tests.testing_utils import ( SyntheticData, adjoint_of_3x3_mat, sdpa2mat, skew, so3_orbitope, )
7,353
CFG_DATASET = { "seed": 0, "min_depth": 4.0, "max_depth": 8.0, "focal": 800.0, } CFG_DATA = { "transl_magnitude": 1.0, "euler_ang_magnitude": 0.5, "max_npoints": 100, "noise_level": 0.0, } def create_parameters(): params = [ Parameter("E", 1, list(range(1, 10))), Parameter("t", 1, list(range(10, 13))), Parameter("q", 1, list(range(13, 16))), Parameter("h", 1, [16]), Parameter("R", 1, list(range(17, 26))), Parameter("sct", 1, [26]), Parameter("scr", 1, [27]), Parameter("scr2", 1, [28]), Parameter("scm1", 1, [29]), Parameter("scm2", 1, [30]), Parameter("Zc", 1, list(range(31, 47))), ] return {p.name: p for p in params} def sample_data(): dataset = SyntheticData(**CFG_DATASET) data = dataset.generate_data(**CFG_DATA) h, sct, scr, scr2, scm1, scm2 = 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 q = data["R01"].T @ data["t01_unit"] x = np.concatenate( ( data["E01"].ravel(), data["t01_unit"].ravel(), q.ravel(), [h], data["R01"].ravel(), [sct, scr, scr2, scm1, scm2], so3_orbitope(data["R01"]).ravel(), ) ) return x[:, None], data def gather_errors(x, A, constraint, constraint_num, is_inequality): values = constraint.values if is_inequality: cond_sdpa_sdpa = np.allclose(values, np.zeros_like(values)) cond_data_sdpa = np.allclose((x.T @ A @ x).squeeze(), constraint_num) else: cond_sdpa_sdpa = np.allclose((x.T @ A @ x).squeeze(), values) cond_data_sdpa = np.allclose(constraint_num, values) errors = [] if not cond_sdpa_sdpa: if is_inequality: errors.append("SDPA coefficients are not zero.") else: errors.append("SDPA coefficients lead to different SDPA values.") if not cond_data_sdpa: errors.append( "SDPA values are different than those derived from data." f"\n{(x.T @ A @ x).squeeze()}\n{constraint_num}" ) success = len(errors) == 0 err_msg = "Errors:\n{}".format("\n".join(errors)) return success, err_msg def obtain_errors(constraint_class, x, constraint_num, f0=None, f1=None): params = create_parameters() constraint = constraint_class(params, 0, 0, None) is_inequality = constraint.__class__.__name__.startswith("Cheirality") if is_inequality: constraint.compute_coeffs(constraint.coeffs, f0, f1) A = sdpa2mat(constraint, block_sizes=[len(x)], ndim=len(x)) errors = gather_errors(x, A, constraint, constraint_num, is_inequality) return errors def test_manif_def_left(): x, data = sample_data() E01, t01_unit = data["E01"], data["t01_unit"]
CFG_DATASET = { "seed": 0, "min_depth": 4.0, "max_depth": 8.0, "focal": 800.0, } CFG_DATA = { "transl_magnitude": 1.0, "euler_ang_magnitude": 0.5, "max_npoints": 100, "noise_level": 0.0, } def create_parameters(): params = [ Parameter("E", 1, list(range(1, 10))), Parameter("t", 1, list(range(10, 13))), Parameter("q", 1, list(range(13, 16))), Parameter("h", 1, [16]), Parameter("R", 1, list(range(17, 26))), Parameter("sct", 1, [26]), Parameter("scr", 1, [27]), Parameter("scr2", 1, [28]), Parameter("scm1", 1, [29]), Parameter("scm2", 1, [30]), Parameter("Zc", 1, list(range(31, 47))), ] return {p.name: p for p in params} def sample_data(): dataset = SyntheticData(**CFG_DATASET) data = dataset.generate_data(**CFG_DATA) h, sct, scr, scr2, scm1, scm2 = 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 q = data["R01"].T @ data["t01_unit"] x = np.concatenate( ( data["E01"].ravel(), data["t01_unit"].ravel(), q.ravel(), [h], data["R01"].ravel(), [sct, scr, scr2, scm1, scm2], so3_orbitope(data["R01"]).ravel(), ) ) return x[:, None], data def gather_errors(x, A, constraint, constraint_num, is_inequality): values = constraint.values if is_inequality: cond_sdpa_sdpa = np.allclose(values, np.zeros_like(values)) cond_data_sdpa = np.allclose((x.T @ A @ x).squeeze(), constraint_num) else: cond_sdpa_sdpa = np.allclose((x.T @ A @ x).squeeze(), values) cond_data_sdpa = np.allclose(constraint_num, values) errors = [] if not cond_sdpa_sdpa: if is_inequality: errors.append("SDPA coefficients are not zero.") else: errors.append("SDPA coefficients lead to different SDPA values.") if not cond_data_sdpa: errors.append( "SDPA values are different than those derived from data." f"\n{(x.T @ A @ x).squeeze()}\n{constraint_num}" ) success = len(errors) == 0 err_msg = "Errors:\n{}".format("\n".join(errors)) return success, err_msg def obtain_errors(constraint_class, x, constraint_num, f0=None, f1=None): params = create_parameters() constraint = constraint_class(params, 0, 0, None) is_inequality = constraint.__class__.__name__.startswith("Cheirality") if is_inequality: constraint.compute_coeffs(constraint.coeffs, f0, f1) A = sdpa2mat(constraint, block_sizes=[len(x)], ndim=len(x)) errors = gather_errors(x, A, constraint, constraint_num, is_inequality) return errors def test_manif_def_left(): x, data = sample_data() E01, t01_unit = data["E01"], data["t01_unit"]
constraint_num = E01 @ E01.T - skew(t01_unit) @ skew(t01_unit).T
5
2023-12-10 18:25:10+00:00
12k
Jack24658735/FedLGT
fed_main.py
[ { "identifier": "get_data", "path": "load_data.py", "snippet": "def get_data(args, curr_user=None):\n dataset = args.dataset\n data_root = args.dataroot\n batch_size = args.batch_size\n\n rescale = args.scale_size\n random_crop = args.crop_size\n attr_group_dict = args.attr_group_dict\...
import torch import argparse import numpy as np import utils.evaluate as evaluate import utils.logger as logger import logging import datetime import os import random import clip import json from load_data import get_data from models import CTranModel from config_args import get_args from optim_schedule import WarmupLinearSchedule from run_epoch import run_epoch from tqdm import tqdm from scipy.special import softmax
10,388
def init_nets(args, is_global=False, state_weight=None, label_weight=None): if is_global: n_parties = 1 else: n_parties = args.n_parties nets = {net_i: None for net_i in range(n_parties)} ### FLAIR for net_i in range(n_parties): model = CTranModel(args.num_labels,args.use_lmt,args.pos_emb,args.layers,args.heads,args.dropout,args.no_x_features, state_weight=state_weight, label_weight=label_weight) nets[net_i] = model model_meta_data = [] layer_type = [] for (k, v) in nets[0].state_dict().items(): model_meta_data.append(v.shape) layer_type.append(k) return nets, model_meta_data, layer_type def local_train_net(nets, args, u_id, test_dl = None, device="cpu", g_model=None, emb_feat=None, clip_model=None): data_pts = 0 net_dataidx_map = {} loss_based_agg_list = [] for net_id, net in nets.items(): net.to(device) # TODO: for COCO-dataset, just use indexing of the original dataset to have new subset dataset # TODO: VOC dataset is similar if args.dataset == 'coco' or args.dataset == 'voc': sub_dst = torch.utils.data.Subset(train_dl_global.dataset, partition_idx_map[net_id]) train_dl_local = torch.utils.data.DataLoader(sub_dst, batch_size=args.batch_size,shuffle=True, num_workers=args.workers,drop_last=False) net_dataidx_map[net_id] = len(sub_dst) data_pts += len(sub_dst) else: train_dl_local, test_dl, _, train_dataset = get_data(args, curr_user=u_id[net_id]) # for fedavg net_dataidx_map[net_id] = len(train_dataset) data_pts += len(train_dataset) n_epoch = args.epochs train_metrics, testacc = train_net(net_id, net, train_dl_local, test_dl, n_epoch, args, device=device, g_model=g_model, emb_feat=emb_feat, clip_model=clip_model) # for loss-based agg. loss_based_agg_list.append(train_metrics['loss']) return data_pts, net_dataidx_map, loss_based_agg_list def train_net(net_id, model, train_dataloader, valid_dataloader, epochs, args, device="cpu", g_model=None, emb_feat=None, clip_model=None): fl_logger.info('Training network %s' % str(net_id)) loss_logger = logger.LossLogger(args.model_name) if args.optim == 'adam': optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()),lr=args.lr)#, weight_decay=0.0004) elif args.optim == 'adamw': optimizer = torch.optim.AdamW(filter(lambda p: p.requires_grad, model.parameters()),lr=args.lr) else: optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr, momentum=0.9, weight_decay=1e-4) if args.warmup_scheduler: step_scheduler = None scheduler_warmup = WarmupLinearSchedule(optimizer, 1, 300000) else: scheduler_warmup = None if args.scheduler_type == 'plateau': step_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,mode='min',factor=0.1,patience=5) elif args.scheduler_type == 'step': step_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.scheduler_step, gamma=args.scheduler_gamma) else: step_scheduler = None test_loader = None for epoch in range(epochs): all_preds, all_targs, all_masks, all_ids, train_loss, train_loss_unk = run_epoch(args,model,train_dataloader,optimizer,epoch,'Training',train=True,warmup_scheduler=scheduler_warmup,global_model=g_model,emb_feat=emb_feat, clip_model=clip_model) train_metrics = evaluate.compute_metrics(args,all_preds,all_targs,all_masks,train_loss,train_loss_unk,0,args.train_known_labels, verbose=False) loss_logger.log_losses('train.log',epoch,train_loss,train_metrics,train_loss_unk) if step_scheduler is not None: if args.scheduler_type == 'step': step_scheduler.step(epoch) elif args.scheduler_type == 'plateau': step_scheduler.step(train_loss_unk) fl_logger.info(f'{train_metrics["mAP"]}, {train_metrics["CF1"]}, {train_metrics["loss"]:.3f}') test_acc = 0 fl_logger.info(' ** Training complete **') return train_metrics, test_acc if __name__ == '__main__':
def init_nets(args, is_global=False, state_weight=None, label_weight=None): if is_global: n_parties = 1 else: n_parties = args.n_parties nets = {net_i: None for net_i in range(n_parties)} ### FLAIR for net_i in range(n_parties): model = CTranModel(args.num_labels,args.use_lmt,args.pos_emb,args.layers,args.heads,args.dropout,args.no_x_features, state_weight=state_weight, label_weight=label_weight) nets[net_i] = model model_meta_data = [] layer_type = [] for (k, v) in nets[0].state_dict().items(): model_meta_data.append(v.shape) layer_type.append(k) return nets, model_meta_data, layer_type def local_train_net(nets, args, u_id, test_dl = None, device="cpu", g_model=None, emb_feat=None, clip_model=None): data_pts = 0 net_dataidx_map = {} loss_based_agg_list = [] for net_id, net in nets.items(): net.to(device) # TODO: for COCO-dataset, just use indexing of the original dataset to have new subset dataset # TODO: VOC dataset is similar if args.dataset == 'coco' or args.dataset == 'voc': sub_dst = torch.utils.data.Subset(train_dl_global.dataset, partition_idx_map[net_id]) train_dl_local = torch.utils.data.DataLoader(sub_dst, batch_size=args.batch_size,shuffle=True, num_workers=args.workers,drop_last=False) net_dataidx_map[net_id] = len(sub_dst) data_pts += len(sub_dst) else: train_dl_local, test_dl, _, train_dataset = get_data(args, curr_user=u_id[net_id]) # for fedavg net_dataidx_map[net_id] = len(train_dataset) data_pts += len(train_dataset) n_epoch = args.epochs train_metrics, testacc = train_net(net_id, net, train_dl_local, test_dl, n_epoch, args, device=device, g_model=g_model, emb_feat=emb_feat, clip_model=clip_model) # for loss-based agg. loss_based_agg_list.append(train_metrics['loss']) return data_pts, net_dataidx_map, loss_based_agg_list def train_net(net_id, model, train_dataloader, valid_dataloader, epochs, args, device="cpu", g_model=None, emb_feat=None, clip_model=None): fl_logger.info('Training network %s' % str(net_id)) loss_logger = logger.LossLogger(args.model_name) if args.optim == 'adam': optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()),lr=args.lr)#, weight_decay=0.0004) elif args.optim == 'adamw': optimizer = torch.optim.AdamW(filter(lambda p: p.requires_grad, model.parameters()),lr=args.lr) else: optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr, momentum=0.9, weight_decay=1e-4) if args.warmup_scheduler: step_scheduler = None scheduler_warmup = WarmupLinearSchedule(optimizer, 1, 300000) else: scheduler_warmup = None if args.scheduler_type == 'plateau': step_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,mode='min',factor=0.1,patience=5) elif args.scheduler_type == 'step': step_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.scheduler_step, gamma=args.scheduler_gamma) else: step_scheduler = None test_loader = None for epoch in range(epochs): all_preds, all_targs, all_masks, all_ids, train_loss, train_loss_unk = run_epoch(args,model,train_dataloader,optimizer,epoch,'Training',train=True,warmup_scheduler=scheduler_warmup,global_model=g_model,emb_feat=emb_feat, clip_model=clip_model) train_metrics = evaluate.compute_metrics(args,all_preds,all_targs,all_masks,train_loss,train_loss_unk,0,args.train_known_labels, verbose=False) loss_logger.log_losses('train.log',epoch,train_loss,train_metrics,train_loss_unk) if step_scheduler is not None: if args.scheduler_type == 'step': step_scheduler.step(epoch) elif args.scheduler_type == 'plateau': step_scheduler.step(train_loss_unk) fl_logger.info(f'{train_metrics["mAP"]}, {train_metrics["CF1"]}, {train_metrics["loss"]:.3f}') test_acc = 0 fl_logger.info(' ** Training complete **') return train_metrics, test_acc if __name__ == '__main__':
args = get_args(argparse.ArgumentParser())
2
2023-12-09 09:16:59+00:00
12k
AgriCodeHub/dairy-django-backend
tests/health/tests/conftest.py
[ { "identifier": "CowAvailabilityChoices", "path": "core/choices.py", "snippet": "class CowAvailabilityChoices(models.TextChoices):\n \"\"\"\n Choices for the availability status of a cow.\n\n Choices:\n - `ALIVE`: Cow is alive and active.\n - `SOLD`: Cow has been sold.\n - `DEAD`: Cow ...
from datetime import timedelta from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from core.choices import ( CowAvailabilityChoices, CowBreedChoices, CowCategoryChoices, CowPregnancyChoices, CowProductionStatusChoices, ) from core.serializers import CowSerializer from health.choices import ( CullingReasonChoices, SymptomLocationChoices, SymptomSeverityChoices, SymptomTypeChoices, PathogenChoices, DiseaseCategoryChoices, TreatmentStatusChoices, ) from health.models import Pathogen, DiseaseCategory, Symptoms from health.serializers import DiseaseSerializer from users.choices import SexChoices from core.utils import todays_date import pytest
7,951
quarantine_data = { "cow": cow.id, "reason": "Calving", "start_date": todays_date - timedelta(days=30), "end_date": todays_date, "notes": "Some notes", } return quarantine_data @pytest.fixture def setup_symptom_data(): symptom_data = { "name": "Fever", "symptom_type": SymptomTypeChoices.RESPIRATORY, "date_observed": todays_date, "severity": SymptomSeverityChoices.MILD, "location": SymptomLocationChoices.WHOLE_BODY, } return symptom_data @pytest.fixture def setup_disease_data(): pathogen = Pathogen.objects.create(name=PathogenChoices.UNKNOWN) disease_category = DiseaseCategory.objects.create( name=DiseaseCategoryChoices.NUTRITION ) general_cow = { "name": "General Cow", "breed": {"name": CowBreedChoices.AYRSHIRE}, "date_of_birth": todays_date - timedelta(days=650), "gender": SexChoices.FEMALE, "availability_status": CowAvailabilityChoices.ALIVE, "current_pregnancy_status": CowPregnancyChoices.PREGNANT, "category": CowCategoryChoices.HEIFER, "current_production_status": CowProductionStatusChoices.PREGNANT_NOT_LACTATING, } serializer1 = CowSerializer(data=general_cow) serializer2 = CowSerializer(data=general_cow) assert serializer1.is_valid() assert serializer2.is_valid() cow1 = serializer1.save() cow2 = serializer2.save() symptom_data = { "name": "Fever", "symptom_type": SymptomTypeChoices.RESPIRATORY, "date_observed": todays_date, "severity": SymptomSeverityChoices.MILD, "location": SymptomLocationChoices.WHOLE_BODY, } symptom = Symptoms.objects.create(**symptom_data) disease_data = { "name": "Brucellosis", "pathogen": pathogen.id, "category": disease_category.id, "occurrence_date": todays_date, "cows": [cow1.id, cow2.id], "symptoms": [symptom.id], } return disease_data @pytest.fixture def setup_treatment_data(): pathogen = Pathogen.objects.create(name=PathogenChoices.UNKNOWN) disease_category = DiseaseCategory.objects.create( name=DiseaseCategoryChoices.NUTRITION ) general_cow = { "name": "General Cow", "breed": {"name": CowBreedChoices.AYRSHIRE}, "date_of_birth": todays_date - timedelta(days=650), "gender": SexChoices.FEMALE, "availability_status": CowAvailabilityChoices.ALIVE, "current_pregnancy_status": CowPregnancyChoices.PREGNANT, "category": CowCategoryChoices.HEIFER, "current_production_status": CowProductionStatusChoices.PREGNANT_NOT_LACTATING, } serializer1 = CowSerializer(data=general_cow) serializer2 = CowSerializer(data=general_cow) assert serializer1.is_valid() assert serializer2.is_valid() cow1 = serializer1.save() cow2 = serializer2.save() symptom_data = { "name": "Fever", "symptom_type": SymptomTypeChoices.RESPIRATORY, "date_observed": todays_date, "severity": SymptomSeverityChoices.MILD, "location": SymptomLocationChoices.WHOLE_BODY, } symptom = Symptoms.objects.create(**symptom_data) disease_data = { "name": "Brucellosis", "pathogen": pathogen.id, "category": disease_category.id, "occurrence_date": todays_date, "cows": [cow1.id, cow2.id], "symptoms": [symptom.id], } serializer3 = DiseaseSerializer(data=disease_data) serializer3.is_valid() disease = serializer3.save() treatment_data = { "disease": disease.id, "cow": cow1.id, "treatment_method": "Intravenous injection on the thighs", "notes": "Fully treated cow",
@pytest.fixture() @pytest.mark.django_db def setup_users(): client = APIClient() # Create farm owner user farm_owner_data = { "username": "owner@example.com", "email": "abc1@gmail.com", "password": "testpassword", "first_name": "Farm", "last_name": "Owner", "phone_number": "+254787654321", "sex": SexChoices.MALE, "is_farm_owner": True, } farm_owner_login_data = { "username": "owner@example.com", "password": "testpassword", } response = client.post("/auth/users/", farm_owner_data) # Retrieve the token after login response = client.post(reverse("users:login"), farm_owner_login_data) farm_owner_token = response.data["auth_token"] # Create farm manager user farm_manager_data = { "username": "manager@example.com", "email": "abc2@gmail.com", "password": "testpassword", "first_name": "Farm", "last_name": "Manager", "phone_number": "+254755555555", "sex": SexChoices.MALE, "is_farm_manager": True, } farm_manager_login_data = { "username": "manager@example.com", "password": "testpassword", } response = client.post("/auth/users/", farm_manager_data) # Retrieve the token after login response = client.post(reverse("users:login"), farm_manager_login_data) farm_manager_token = response.data["auth_token"] # Create assistant farm manager user asst_farm_manager_data = { "username": "assistant@example.com", "email": "abc3@gmail.com", "password": "testpassword", "first_name": "Assistant", "last_name": "Farm Manager", "phone_number": "+254744444444", "sex": SexChoices.FEMALE, "is_assistant_farm_manager": True, } asst_farm_manager_login_data = { "username": "assistant@example.com", "password": "testpassword", } response = client.post("/auth/users/", asst_farm_manager_data) # Retrieve the token after login response = client.post(reverse("users:login"), asst_farm_manager_login_data) asst_farm_manager_token = response.data["auth_token"] # Create team leader user team_leader_data = { "username": "leader@example.com", "email": "abc4@gmail.com", "password": "testpassword", "first_name": "Team", "last_name": "Leader", "phone_number": "+254733333333", "sex": SexChoices.MALE, "is_team_leader": True, } team_leader_login_data = { "username": "leader@example.com", "password": "testpassword", } response = client.post("/auth/users/", team_leader_data) # Retrieve the token after login response = client.post(reverse("users:login"), team_leader_login_data) assert response.status_code == status.HTTP_200_OK team_leader_token = response.data["auth_token"] # Create farm worker user farm_worker_data = { "username": "worker@example.com", "email": "abc5@gmail.com", "password": "testpassword", "first_name": "Farm", "last_name": "Worker", "phone_number": "+254722222222", "sex": SexChoices.FEMALE, "is_farm_worker": True, } farm_worker_login_data = { "username": "worker@example.com", "password": "testpassword", } response = client.post("/auth/users/", farm_worker_data) # Retrieve the token after login response = client.post(reverse("users:login"), farm_worker_login_data) farm_worker_token = response.data["auth_token"] return { "client": client, "farm_owner_token": farm_owner_token, "farm_manager_token": farm_manager_token, "asst_farm_manager_token": asst_farm_manager_token, "team_leader_token": team_leader_token, "farm_worker_token": farm_worker_token, } @pytest.fixture @pytest.mark.django_db def setup_weight_record_data(): general_cow = { "name": "General Cow", "breed": {"name": CowBreedChoices.AYRSHIRE}, "date_of_birth": todays_date - timedelta(days=650), "gender": SexChoices.FEMALE, "availability_status": CowAvailabilityChoices.ALIVE, "current_pregnancy_status": CowPregnancyChoices.OPEN, "category": CowCategoryChoices.HEIFER, "current_production_status": CowProductionStatusChoices.OPEN, } serializer = CowSerializer(data=general_cow) assert serializer.is_valid() cow = serializer.save() weight_data = {"cow": cow.id, "weight_in_kgs": 1150} return weight_data @pytest.fixture @pytest.mark.django_db def setup_culling_record_data(): general_cow = { "name": "General Cow", "breed": {"name": CowBreedChoices.AYRSHIRE}, "date_of_birth": todays_date - timedelta(days=370), "gender": SexChoices.FEMALE, "availability_status": CowAvailabilityChoices.ALIVE, "current_pregnancy_status": CowPregnancyChoices.PREGNANT, "category": CowCategoryChoices.HEIFER, "current_production_status": CowProductionStatusChoices.PREGNANT_NOT_LACTATING, } serializer = CowSerializer(data=general_cow) assert serializer.is_valid() cow = serializer.save() culling_data = { "cow": cow.id, "reason": CullingReasonChoices.COST_OF_CARE, } return culling_data @pytest.fixture @pytest.mark.django_db def setup_quarantine_record_data(): general_cow = { "name": "General Cow", "breed": {"name": CowBreedChoices.AYRSHIRE}, "date_of_birth": todays_date - timedelta(days=650), "gender": SexChoices.FEMALE, "availability_status": CowAvailabilityChoices.ALIVE, "current_pregnancy_status": CowPregnancyChoices.PREGNANT, "category": CowCategoryChoices.HEIFER, "current_production_status": CowProductionStatusChoices.PREGNANT_NOT_LACTATING, } serializer = CowSerializer(data=general_cow) if not serializer.is_valid(): print(serializer.errors) assert serializer.is_valid() cow = serializer.save() quarantine_data = { "cow": cow.id, "reason": "Calving", "start_date": todays_date - timedelta(days=30), "end_date": todays_date, "notes": "Some notes", } return quarantine_data @pytest.fixture def setup_symptom_data(): symptom_data = { "name": "Fever", "symptom_type": SymptomTypeChoices.RESPIRATORY, "date_observed": todays_date, "severity": SymptomSeverityChoices.MILD, "location": SymptomLocationChoices.WHOLE_BODY, } return symptom_data @pytest.fixture def setup_disease_data(): pathogen = Pathogen.objects.create(name=PathogenChoices.UNKNOWN) disease_category = DiseaseCategory.objects.create( name=DiseaseCategoryChoices.NUTRITION ) general_cow = { "name": "General Cow", "breed": {"name": CowBreedChoices.AYRSHIRE}, "date_of_birth": todays_date - timedelta(days=650), "gender": SexChoices.FEMALE, "availability_status": CowAvailabilityChoices.ALIVE, "current_pregnancy_status": CowPregnancyChoices.PREGNANT, "category": CowCategoryChoices.HEIFER, "current_production_status": CowProductionStatusChoices.PREGNANT_NOT_LACTATING, } serializer1 = CowSerializer(data=general_cow) serializer2 = CowSerializer(data=general_cow) assert serializer1.is_valid() assert serializer2.is_valid() cow1 = serializer1.save() cow2 = serializer2.save() symptom_data = { "name": "Fever", "symptom_type": SymptomTypeChoices.RESPIRATORY, "date_observed": todays_date, "severity": SymptomSeverityChoices.MILD, "location": SymptomLocationChoices.WHOLE_BODY, } symptom = Symptoms.objects.create(**symptom_data) disease_data = { "name": "Brucellosis", "pathogen": pathogen.id, "category": disease_category.id, "occurrence_date": todays_date, "cows": [cow1.id, cow2.id], "symptoms": [symptom.id], } return disease_data @pytest.fixture def setup_treatment_data(): pathogen = Pathogen.objects.create(name=PathogenChoices.UNKNOWN) disease_category = DiseaseCategory.objects.create( name=DiseaseCategoryChoices.NUTRITION ) general_cow = { "name": "General Cow", "breed": {"name": CowBreedChoices.AYRSHIRE}, "date_of_birth": todays_date - timedelta(days=650), "gender": SexChoices.FEMALE, "availability_status": CowAvailabilityChoices.ALIVE, "current_pregnancy_status": CowPregnancyChoices.PREGNANT, "category": CowCategoryChoices.HEIFER, "current_production_status": CowProductionStatusChoices.PREGNANT_NOT_LACTATING, } serializer1 = CowSerializer(data=general_cow) serializer2 = CowSerializer(data=general_cow) assert serializer1.is_valid() assert serializer2.is_valid() cow1 = serializer1.save() cow2 = serializer2.save() symptom_data = { "name": "Fever", "symptom_type": SymptomTypeChoices.RESPIRATORY, "date_observed": todays_date, "severity": SymptomSeverityChoices.MILD, "location": SymptomLocationChoices.WHOLE_BODY, } symptom = Symptoms.objects.create(**symptom_data) disease_data = { "name": "Brucellosis", "pathogen": pathogen.id, "category": disease_category.id, "occurrence_date": todays_date, "cows": [cow1.id, cow2.id], "symptoms": [symptom.id], } serializer3 = DiseaseSerializer(data=disease_data) serializer3.is_valid() disease = serializer3.save() treatment_data = { "disease": disease.id, "cow": cow1.id, "treatment_method": "Intravenous injection on the thighs", "notes": "Fully treated cow",
"treatment_status": TreatmentStatusChoices.COMPLETED,
12
2023-12-09 06:56:42+00:00
12k
facebookresearch/chat2map-official
chat2map/mapping/passive_mapping/policy.py
[ { "identifier": "VisualEnc", "path": "chat2map/mapping/mapping_models/visual_cnn.py", "snippet": "class VisualEnc(nn.Module):\n \"\"\"Visual encoder\"\"\"\n\n def __init__(self, cfg=None):\n \"\"\"Takes in RGB images and 90 degree FoV local egocentric map inputs and encodes them\"\"\"\n ...
import os import pickle import math import numpy as np import torch import torch.nn as nn from torchsummary import summary from chat2map.mapping.mapping_models.visual_cnn import VisualEnc, OccMapDec from chat2map.mapping.mapping_models.audio_cnn import AudioEnc from chat2map.mapping.mapping_models.modality_tag_type_net import ModalityTagTypeNet from chat2map.mapping.mapping_models.positional_net import PositionalNet, PatchPositionalNet from chat2map.mapping.mapping_models.fusion_net import FusionNet from chat2map.mapping.mapping_models.memory_net import TransformerMemory
10,165
# B x max_query_length x ... -> (B * max_query_length) x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_views_pose = query_views_pose.reshape((-1, *query_views_pose.size()[2:])) query_views_poseFeats = self.pose_net({"positional_obs": query_views_pose}) query_feats.append(query_views_poseFeats) query_views_posePatchFeats = self.patchPose_net({"positional_obs": query_views_pose}) query_feats.append(query_views_posePatchFeats) """fusion net""" query_fusedFeats = self.fusion_net(query_feats) query_fusedFeats = query_fusedFeats.permute((0, 2, 3, 1)) query_fusedFeats = query_fusedFeats.reshape((B, self.max_query_length, query_fusedFeats.size(1), query_fusedFeats.size(2), query_fusedFeats.size(3))) assert query_fusedFeats.size(2) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[0] assert query_fusedFeats.size(3) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[1] query_fusedFeats = query_fusedFeats.reshape((B, self.max_query_length *\ query_fusedFeats.size(2) *\ query_fusedFeats.size(3), -1)) # B x max_query_length x ... -> max_query_length x B x -1; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_fusedFeats = query_fusedFeats.permute(1, 0, 2) """query key padding mask""" assert "query_views_mask" in observations query_key_padding_mask = observations["query_views_mask"] assert len(query_key_padding_mask.size()) == 2 query_key_padding_mask = query_key_padding_mask.unsqueeze(-1).unsqueeze(-1) query_key_padding_mask = query_key_padding_mask.repeat((1, 1, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1])) query_key_padding_mask = query_key_padding_mask.reshape((query_key_padding_mask.size(0), query_key_padding_mask.size(1) *\ query_key_padding_mask.size(2) *\ query_key_padding_mask.size(3))) """memory encoding: context aggregation""" memory_outFeats =\ self.memory_net( { "src_feats": context_fusedFeats, "tgt_feats": query_fusedFeats, "src_key_padding_mask": context_key_padding_mask, "tgt_key_padding_mask": query_key_padding_mask, "memory_key_padding_mask": memory_key_padding_mask, } ) # max_query_length x B x ... -> B x max_query_length x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) memory_outFeats = memory_outFeats.permute(1, 0, 2) memory_outFeats = memory_outFeats.reshape((B, self.max_query_length, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1], memory_outFeats.size(2))) memory_outFeats = memory_outFeats.reshape((B * self.max_query_length, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0] *\ self._passive_mapping_cfg.PositionalNet.patch_hwCh[1] *\ memory_outFeats.size(4))) """query occMap decoder""" query_occMap_pred = self.query_occMap_dec({"memory_outFeats": memory_outFeats}) # (B * max_query_length) x ... -> B x max_query_length x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_occMap_pred = query_occMap_pred.reshape((B, self.max_query_length, *query_occMap_pred.size()[1:])) return query_occMap_pred class PassiveMappingPolicy(Policy): """ Model for passive mapping """ def __init__( self, cfg, ): passive_mapping_cfg = cfg.PassiveMapping task_cfg = cfg.TASK_CONFIG sim_cfg = task_cfg.SIMULATOR # --------------------------------------------- context encoders ----------------------------------------------- """pose net""" pose_net = PositionalNet( passive_mapping_cfg=passive_mapping_cfg, ) patchPose_net = PatchPositionalNet( passive_mapping_cfg=passive_mapping_cfg, ) """modality tag type lookup table""" modality_tag_type_lookup_dict = ModalityTagTypeNet( n_modality_tag_types=3, passive_mapping_cfg=passive_mapping_cfg, ) """views encoder""" context_views_enc = VisualEnc( cfg=cfg, ) """audio encoder""" context_audio_enc = AudioEnc( cfg=cfg, ) """fusion net"""
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. class Policy(nn.Module): """ Parent class of model for passive mapping """ def __init__(self, context_views_enc, context_audio_enc, pose_net, patchPose_net, modality_tag_type_lookup_dict, fusion_net, memory_net, query_occMap_dec, cfg ): """Given the audio streams and sampled frames during a conversation, the model predicts estimates of target occupancy maps""" super().__init__() self.context_views_enc = context_views_enc self.context_audio_enc = context_audio_enc self.pose_net = pose_net self.patchPose_net = patchPose_net self.modality_tag_type_lookup_dict = modality_tag_type_lookup_dict self.fusion_net = fusion_net self.memory_net = memory_net self.query_occMap_dec = query_occMap_dec self._cfg = cfg self._task_cfg = cfg.TASK_CONFIG self._env_cfg = self._task_cfg.ENVIRONMENT self._sim_cfg = self._task_cfg.SIMULATOR self._audio_cfg = self._sim_cfg.AUDIO self._passive_mapping_cfg = cfg.PassiveMapping self.max_context_length = self._env_cfg.MAX_CONTEXT_LENGTH self.max_query_length = self._env_cfg.MAX_QUERY_LENGTH def forward(self, observations): """Given the audio streams and sampled frames during a conversation, predicts estimates of target occupancy maps""" # --------------------------------------------- context encoding ------------------------------------------------ context_feats = [] for feat_idx in range(3): context_feats.append([]) context_key_padding_mask = [] """views encoder""" assert "context_maps" in observations context_maps = observations["context_maps"] assert "context_views_pose" in observations context_views_pose = observations["context_views_pose"] assert "context_views_mask" in observations context_views_mask = observations["context_views_mask"] assert len(context_views_mask.size()) == 3 B = context_maps.size(0) num_agents = context_maps.size(1) context_maps = context_maps.reshape((-1, *context_maps.size()[3:])) context_views_dct = {"occ_map": context_maps} if "RGB_SENSOR" in self._cfg.SENSORS: assert "context_rgbs" in observations context_rgbs = observations["context_rgbs"] context_rgbs = context_rgbs.reshape((-1, *context_rgbs.size()[3:])) context_views_dct["rgb"] = context_rgbs context_views_feats = self.context_views_enc(context_views_dct) context_feats[0].append(context_views_feats) # B x num_agents x max_context_length x ... -> (B * num_agents * max_context_length) x ...; B: batch size, # max_context_length: transformer source sequence length S (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) context_views_pose = context_views_pose.reshape((-1, *context_views_pose.size()[3:])) context_views_poseFeats = self.pose_net({"positional_obs": context_views_pose}) context_feats[0].append(context_views_poseFeats) context_views_posePatchFeats = self.patchPose_net({"positional_obs": context_views_pose}) context_feats[0].append(context_views_posePatchFeats) context_views_modalityType = torch.LongTensor([0]).to(context_views_poseFeats.device) context_views_modalityTypeFeats = self.modality_tag_type_lookup_dict(context_views_modalityType) context_views_modalityTypeFeats =\ context_views_modalityTypeFeats.repeat((context_views_posePatchFeats.size(0), 1, 1, 1)) context_feats[0].append(context_views_modalityTypeFeats) # B x num_agents x max_context_length -> B x (num_agents * max_context_length); B: batch size, context_views_mask = context_views_mask.reshape((context_views_mask.size(0), -1)) context_views_mask = context_views_mask.unsqueeze(-1).unsqueeze(-1) context_views_mask = context_views_mask.repeat((1, 1, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1])) context_views_mask = context_views_mask.reshape((context_views_mask.size(0), context_views_mask.size(1) *\ context_views_mask.size(2) *\ context_views_mask.size(3))) context_key_padding_mask.append(context_views_mask) """self audio encoder""" assert "context_selfAudio" in observations context_selfAudio = observations["context_selfAudio"] assert "context_selfAudio_pose" in observations context_selfAudio_pose = observations["context_selfAudio_pose"] assert "context_selfAudio_mask" in observations context_selfAudio_mask = observations["context_selfAudio_mask"] assert len(context_selfAudio_mask.size()) == 3 assert "context_otherAudio" in observations context_otherAudio = observations["context_otherAudio"] context_selfAudio = context_selfAudio.reshape((-1, *context_selfAudio.size()[3:])) context_otherAudio = context_otherAudio.reshape((-1, *context_otherAudio.size()[3:])) context_audio = torch.cat([context_selfAudio, context_otherAudio], dim=0) context_audio_feats = self.context_audio_enc({"audio": context_audio}) context_selfAudio_feats = context_audio_feats[:context_selfAudio.size(0)] context_feats[1].append(context_selfAudio_feats) # B x num_agents x max_context_length x ... -> (B * num_agents * max_context_length) x ...; B: batch size, # max_context_length: transformer source sequence length S (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) context_selfAudio_pose = context_selfAudio_pose.reshape((-1, *context_selfAudio_pose.size()[3:])) context_selfAudio_poseFeats = self.pose_net({"positional_obs": context_selfAudio_pose}) context_feats[1].append(context_selfAudio_poseFeats) context_selfAudio_posePatchFeats = self.patchPose_net({"positional_obs": context_selfAudio_pose}) context_feats[1].append(context_selfAudio_posePatchFeats) context_selfAudio_modalityType = torch.LongTensor([1]).to(context_selfAudio_poseFeats.device) context_selfAudio_modalityTypeFeats = self.modality_tag_type_lookup_dict(context_selfAudio_modalityType) context_selfAudio_modalityTypeFeats =\ context_selfAudio_modalityTypeFeats.repeat((context_selfAudio_modalityTypeFeats.size(0), 1, 1, 1)) context_feats[1].append(context_selfAudio_modalityTypeFeats) # B x num_agents x max_context_length -> B x (num_agents * max_context_length); B: batch size, context_selfAudio_mask = context_selfAudio_mask.reshape((context_selfAudio_mask.size(0), -1)) context_selfAudio_mask = context_selfAudio_mask.unsqueeze(-1).unsqueeze(-1) context_selfAudio_mask = context_selfAudio_mask.repeat((1, 1, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1])) context_selfAudio_mask = context_selfAudio_mask.reshape((context_selfAudio_mask.size(0), context_selfAudio_mask.size(1) *\ context_selfAudio_mask.size(2) *\ context_selfAudio_mask.size(3))) context_key_padding_mask.append(context_selfAudio_mask) """audio from other ego encoder""" context_otherAudio_feats = context_audio_feats[context_otherAudio.size(0):] assert "context_otherAudio_pose" in observations context_otherAudio_pose = observations["context_otherAudio_pose"] assert "context_otherAudio_mask" in observations context_otherAudio_mask = observations["context_otherAudio_mask"] assert len(context_otherAudio_mask.size()) == 3 context_feats[2].append(context_otherAudio_feats) # B x num_agents x max_context_length x ... -> (B * num_agents * max_context_length) x ...; B: batch size, # max_context_length: transformer source sequence length S (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) context_otherAudio_pose = context_otherAudio_pose.reshape((-1, *context_otherAudio_pose.size()[3:])) context_otherAudio_poseFeats = self.pose_net({"positional_obs": context_otherAudio_pose}) context_feats[2].append(context_otherAudio_poseFeats) context_otherAudio_posePatchFeats = self.patchPose_net({"positional_obs": context_otherAudio_pose}) context_feats[2].append(context_otherAudio_posePatchFeats) context_otherAudio_modalityType =\ torch.LongTensor([2]).to(context_otherAudio_poseFeats.device) context_otherAudio_modalityTypeFeats = self.modality_tag_type_lookup_dict(context_otherAudio_modalityType) context_otherAudio_modalityTypeFeats =\ context_otherAudio_modalityTypeFeats.repeat((context_otherAudio_modalityTypeFeats.size(0), 1, 1, 1)) context_feats[2].append(context_otherAudio_modalityTypeFeats) # B x num_agents x max_context_length -> B x (num_agents * max_context_length); B: batch size, context_otherAudio_mask = context_otherAudio_mask.reshape((context_otherAudio_mask.size(0), -1)) context_otherAudio_mask = context_otherAudio_mask.unsqueeze(-1).unsqueeze(-1) context_otherAudio_mask = context_otherAudio_mask.repeat((1, 1, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1])) context_otherAudio_mask = context_otherAudio_mask.reshape((context_otherAudio_mask.size(0), context_otherAudio_mask.size(1) *\ context_otherAudio_mask.size(2) *\ context_otherAudio_mask.size(3))) context_key_padding_mask.append(context_otherAudio_mask) """fusion net""" context_fusedFeats = [] for idx_contextFeats in range(len(context_feats)): temp_context_fusedFeats = self.fusion_net(context_feats[idx_contextFeats]) temp_context_fusedFeats = temp_context_fusedFeats.permute((0, 2, 3, 1)) temp_context_fusedFeats = temp_context_fusedFeats.reshape((B, num_agents * self.max_context_length, temp_context_fusedFeats.size(1), temp_context_fusedFeats.size(2), temp_context_fusedFeats.size(3))) assert temp_context_fusedFeats.size(2) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[0] assert temp_context_fusedFeats.size(3) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[1] temp_context_fusedFeats = temp_context_fusedFeats.reshape((B, num_agents * self.max_context_length *\ temp_context_fusedFeats.size(2) *\ temp_context_fusedFeats.size(3), -1)) temp_context_fusedFeats = temp_context_fusedFeats.permute(1, 0, 2) context_fusedFeats.append(temp_context_fusedFeats) context_fusedFeats = torch.cat(context_fusedFeats, dim=0) """context and memory key padding masks""" context_key_padding_mask = torch.cat(context_key_padding_mask, dim=-1) memory_key_padding_mask = context_key_padding_mask.clone() # --------------------------------------------- query encoding -------------------------------------------------- query_feats = [] """pose encoder""" assert "query_views_pose" in observations query_views_pose = observations["query_views_pose"] # B x max_query_length x ... -> (B * max_query_length) x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_views_pose = query_views_pose.reshape((-1, *query_views_pose.size()[2:])) query_views_poseFeats = self.pose_net({"positional_obs": query_views_pose}) query_feats.append(query_views_poseFeats) query_views_posePatchFeats = self.patchPose_net({"positional_obs": query_views_pose}) query_feats.append(query_views_posePatchFeats) """fusion net""" query_fusedFeats = self.fusion_net(query_feats) query_fusedFeats = query_fusedFeats.permute((0, 2, 3, 1)) query_fusedFeats = query_fusedFeats.reshape((B, self.max_query_length, query_fusedFeats.size(1), query_fusedFeats.size(2), query_fusedFeats.size(3))) assert query_fusedFeats.size(2) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[0] assert query_fusedFeats.size(3) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[1] query_fusedFeats = query_fusedFeats.reshape((B, self.max_query_length *\ query_fusedFeats.size(2) *\ query_fusedFeats.size(3), -1)) # B x max_query_length x ... -> max_query_length x B x -1; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_fusedFeats = query_fusedFeats.permute(1, 0, 2) """query key padding mask""" assert "query_views_mask" in observations query_key_padding_mask = observations["query_views_mask"] assert len(query_key_padding_mask.size()) == 2 query_key_padding_mask = query_key_padding_mask.unsqueeze(-1).unsqueeze(-1) query_key_padding_mask = query_key_padding_mask.repeat((1, 1, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1])) query_key_padding_mask = query_key_padding_mask.reshape((query_key_padding_mask.size(0), query_key_padding_mask.size(1) *\ query_key_padding_mask.size(2) *\ query_key_padding_mask.size(3))) """memory encoding: context aggregation""" memory_outFeats =\ self.memory_net( { "src_feats": context_fusedFeats, "tgt_feats": query_fusedFeats, "src_key_padding_mask": context_key_padding_mask, "tgt_key_padding_mask": query_key_padding_mask, "memory_key_padding_mask": memory_key_padding_mask, } ) # max_query_length x B x ... -> B x max_query_length x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) memory_outFeats = memory_outFeats.permute(1, 0, 2) memory_outFeats = memory_outFeats.reshape((B, self.max_query_length, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1], memory_outFeats.size(2))) memory_outFeats = memory_outFeats.reshape((B * self.max_query_length, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0] *\ self._passive_mapping_cfg.PositionalNet.patch_hwCh[1] *\ memory_outFeats.size(4))) """query occMap decoder""" query_occMap_pred = self.query_occMap_dec({"memory_outFeats": memory_outFeats}) # (B * max_query_length) x ... -> B x max_query_length x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_occMap_pred = query_occMap_pred.reshape((B, self.max_query_length, *query_occMap_pred.size()[1:])) return query_occMap_pred class PassiveMappingPolicy(Policy): """ Model for passive mapping """ def __init__( self, cfg, ): passive_mapping_cfg = cfg.PassiveMapping task_cfg = cfg.TASK_CONFIG sim_cfg = task_cfg.SIMULATOR # --------------------------------------------- context encoders ----------------------------------------------- """pose net""" pose_net = PositionalNet( passive_mapping_cfg=passive_mapping_cfg, ) patchPose_net = PatchPositionalNet( passive_mapping_cfg=passive_mapping_cfg, ) """modality tag type lookup table""" modality_tag_type_lookup_dict = ModalityTagTypeNet( n_modality_tag_types=3, passive_mapping_cfg=passive_mapping_cfg, ) """views encoder""" context_views_enc = VisualEnc( cfg=cfg, ) """audio encoder""" context_audio_enc = AudioEnc( cfg=cfg, ) """fusion net"""
fusion_net = FusionNet()
6
2023-12-06 01:20:37+00:00
12k
PeriniM/Rotary-Pendulum-RL
control/reinforcement_learning/src/main.py
[ { "identifier": "RealPendulumEnv", "path": "control/reinforcement_learning/Environments/RealPendulumEnv.py", "snippet": "class RealPendulumEnv(gym.Env):\n \"\"\"\n Real rotary pendulum with ESP32\n \"\"\"\n\n metadata = {\"render_modes\": [\"human\"]}\n\n def __init__(self, port, baudrate...
from ..Environments import RealPendulumEnv as real from ..Environments import PyBulletPendulumEnv as pb from ..Environments import FakeEnv as fake from ..DQN.Agent import Agent
10,484
isFake = False isPyBullet = True isReal = False train = True plot_colormaps = False # select the environment if isFake: env = fake.FakeEnv(1) elif isPyBullet: env = pb.PyBulletPendulumEnv(render_mode='human') elif isReal: env = real.RealPendulumEnv("COM3", 115200) else: raise Exception("No environment selected!") # create the agent
isFake = False isPyBullet = True isReal = False train = True plot_colormaps = False # select the environment if isFake: env = fake.FakeEnv(1) elif isPyBullet: env = pb.PyBulletPendulumEnv(render_mode='human') elif isReal: env = real.RealPendulumEnv("COM3", 115200) else: raise Exception("No environment selected!") # create the agent
dqn_agent = Agent(env)
3
2023-12-09 11:22:54+00:00
12k
JayYik/GAN_implementations
utils/get_model.py
[ { "identifier": "DCGAN", "path": "models/DCGAN.py", "snippet": "class DCGAN(nn.Module):\n def __init__(self, args):\n super(DCGAN, self).__init__()\n self.G=DCGAN_G(args.hw,args.z_dim,args.in_channels)\n self.D=DCGAN_D(args.hw,args.in_channels)\n # self.G.weight_init()\n ...
import torch from models.DCGAN import DCGAN from models.GAN import GAN from models.WGAN import WGAN_CP from models.WGAN_GP import WGAN_GP
7,217
def get_model(args): if args.model == 'DCGAN': net=DCGAN(args) elif args.model == 'GAN': net=GAN(args) elif args.model == 'WGAN-CP': net=WGAN_CP(args) elif args.model == 'WGAN-GP':
def get_model(args): if args.model == 'DCGAN': net=DCGAN(args) elif args.model == 'GAN': net=GAN(args) elif args.model == 'WGAN-CP': net=WGAN_CP(args) elif args.model == 'WGAN-GP':
net=WGAN_GP(args)
3
2023-12-12 06:24:31+00:00
12k
tommy-xq/SA2VP
vpt_main/src/models/build_model.py
[ { "identifier": "ResNet", "path": "vpt_main/src/models/resnet.py", "snippet": "class ResNet(nn.Module):\n \"\"\"ResNet model.\"\"\"\n\n def __init__(self, cfg):\n super(ResNet, self).__init__()\n self.cfg = cfg\n\n model_type = cfg.DATA.FEATURE\n model = self.get_pretra...
from tabnanny import verbose from .resnet import ResNet from .convnext import ConvNeXt from .vit_models import ViT, Swin, SSLViT from ..utils import logging import torch
10,093
#!/usr/bin/env python3 """ Model construction functions. """ logger = logging.get_logger("visual_prompt") # Supported model types _MODEL_TYPES = {
#!/usr/bin/env python3 """ Model construction functions. """ logger = logging.get_logger("visual_prompt") # Supported model types _MODEL_TYPES = {
"resnet": ResNet,
0
2023-12-12 13:19:17+00:00
12k
KULL-Centre/_2023_Blaabjerg_SSEmb
src/models/msa_transformer/modules.py
[ { "identifier": "MultiheadAttention", "path": "src/models/msa_transformer/multihead_attention.py", "snippet": "class MultiheadAttention(nn.Module):\n \"\"\"Multi-headed attention.\n\n See \"Attention Is All You Need\" for more details.\n \"\"\"\n\n def __init__(\n self,\n embed...
import math import torch import torch.nn as nn import torch.nn.functional as F from typing import Tuple, Optional from .multihead_attention import MultiheadAttention # noqa from .axial_attention import ColumnSelfAttention, RowSelfAttention from apex.normalization import FusedLayerNorm as _FusedLayerNorm from torch.nn import LayerNorm as ESM1bLayerNorm
7,565
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. def gelu(x): """Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) """ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) def symmetrize(x): "Make layer symmetric in final two dimensions, used for contact prediction." return x + x.transpose(-1, -2) def apc(x): "Perform average product correct, used for contact prediction." a1 = x.sum(-1, keepdims=True) a2 = x.sum(-2, keepdims=True) a12 = x.sum((-1, -2), keepdims=True) avg = a1 * a2 avg.div_(a12) # in-place to reduce memory normalized = x - avg return normalized class ESM1LayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12, affine=True): """Construct a layernorm layer in the TF style (eps inside the sqrt).""" super().__init__() self.hidden_size = (hidden_size,) if isinstance(hidden_size, int) else tuple(hidden_size) self.eps = eps self.affine = bool(affine) if self.affine: self.weight = nn.Parameter(torch.ones(hidden_size)) self.bias = nn.Parameter(torch.zeros(hidden_size)) else: self.weight, self.bias = None, None def forward(self, x): dims = tuple(-(i + 1) for i in range(len(self.hidden_size))) means = x.mean(dims, keepdim=True) x_zeromean = x - means variances = x_zeromean.pow(2).mean(dims, keepdim=True) x = x_zeromean / torch.sqrt(variances + self.eps) if self.affine: x = (self.weight * x) + self.bias return x try: class ESM1bLayerNorm(_FusedLayerNorm): @torch.jit.unused def forward(self, x): if not x.is_cuda: return super().forward(x) else: with torch.cuda.device(x.device): return super().forward(x) except ImportError: class TransformerLayer(nn.Module): """Transformer layer block.""" def __init__( self, embed_dim, ffn_embed_dim, attention_heads, add_bias_kv=True, use_esm1b_layer_norm=False, use_rotary_embeddings: bool = False, ): super().__init__() self.embed_dim = embed_dim self.ffn_embed_dim = ffn_embed_dim self.attention_heads = attention_heads self.use_rotary_embeddings = use_rotary_embeddings self._init_submodules(add_bias_kv, use_esm1b_layer_norm) def _init_submodules(self, add_bias_kv, use_esm1b_layer_norm): BertLayerNorm = ESM1bLayerNorm if use_esm1b_layer_norm else ESM1LayerNorm
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. def gelu(x): """Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) """ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) def symmetrize(x): "Make layer symmetric in final two dimensions, used for contact prediction." return x + x.transpose(-1, -2) def apc(x): "Perform average product correct, used for contact prediction." a1 = x.sum(-1, keepdims=True) a2 = x.sum(-2, keepdims=True) a12 = x.sum((-1, -2), keepdims=True) avg = a1 * a2 avg.div_(a12) # in-place to reduce memory normalized = x - avg return normalized class ESM1LayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12, affine=True): """Construct a layernorm layer in the TF style (eps inside the sqrt).""" super().__init__() self.hidden_size = (hidden_size,) if isinstance(hidden_size, int) else tuple(hidden_size) self.eps = eps self.affine = bool(affine) if self.affine: self.weight = nn.Parameter(torch.ones(hidden_size)) self.bias = nn.Parameter(torch.zeros(hidden_size)) else: self.weight, self.bias = None, None def forward(self, x): dims = tuple(-(i + 1) for i in range(len(self.hidden_size))) means = x.mean(dims, keepdim=True) x_zeromean = x - means variances = x_zeromean.pow(2).mean(dims, keepdim=True) x = x_zeromean / torch.sqrt(variances + self.eps) if self.affine: x = (self.weight * x) + self.bias return x try: class ESM1bLayerNorm(_FusedLayerNorm): @torch.jit.unused def forward(self, x): if not x.is_cuda: return super().forward(x) else: with torch.cuda.device(x.device): return super().forward(x) except ImportError: class TransformerLayer(nn.Module): """Transformer layer block.""" def __init__( self, embed_dim, ffn_embed_dim, attention_heads, add_bias_kv=True, use_esm1b_layer_norm=False, use_rotary_embeddings: bool = False, ): super().__init__() self.embed_dim = embed_dim self.ffn_embed_dim = ffn_embed_dim self.attention_heads = attention_heads self.use_rotary_embeddings = use_rotary_embeddings self._init_submodules(add_bias_kv, use_esm1b_layer_norm) def _init_submodules(self, add_bias_kv, use_esm1b_layer_norm): BertLayerNorm = ESM1bLayerNorm if use_esm1b_layer_norm else ESM1LayerNorm
self.self_attn = MultiheadAttention(
0
2023-12-09 11:42:34+00:00
12k
ChatClue/ChatClue
osiris.py
[ { "identifier": "OSHelper", "path": "utils/os/helpers.py", "snippet": "class OSHelper:\n \"\"\"\n Provides utility methods for operating system level operations, particularly file management.\n\n This class includes static methods for performing various file system tasks such as cleaning up orp...
from config import CELERY_CONFIG, LOG_LEVEL, VIDEO_SETTINGS from utils.os.helpers import OSHelper from celery import Celery from celery_config import get_celery_app from database.setup import DatabaseSetup from broadcast.broadcaster import broadcaster from audio.audio_processor import AudioProcessor from video.video_processor import VideoProcessor from audio.audio_out import get_audio_out from utils.os.helpers import OSHelper from utils.text.welcome import welcome_message from utils.logging.colors import ColorFormatter from background.memory.tasks import * from tools import * # Import all openai tool functions import logging import subprocess import atexit import sys import threading import time import cv2 import queue
7,450
# Configure basic logging for the application logging.basicConfig(level=LOG_LEVEL) root_logger = logging.getLogger() for handler in root_logger.handlers: handler.setFormatter(ColorFormatter('%(asctime)s - %(levelname)s - %(message)s')) # Ensure the necessary tmp/ directories exist OSHelper.configure_tmp_directories() # Configure background processor / subconcious systems celery_app = get_celery_app() # Configure audio output audio_out = get_audio_out() def start_celery_worker(): """ Starts a Celery worker as a subprocess. This method initiates a Celery worker using the subprocess module. The worker runs asynchronously and executes tasks defined in the Celery application. The worker is configured to log at the 'info' level for better visibility of its operations. The function also ensures that the Celery worker is terminated gracefully when the Python script exits. This is achieved using the `atexit` module, which registers a function to terminate the worker as part of the script's cleanup process. Returns: subprocess.Popen: The subprocess object representing the Celery worker. """ # Get the log level from configuration, default to 'info' log_level = CELERY_CONFIG.get('LOCAL_LOG_LEVEL', 'info') # Start Celery worker celery_worker = subprocess.Popen(['celery', '-A', 'osiris.celery_app', 'worker', f'--loglevel={log_level}']) # Register function to terminate worker on exit atexit.register(lambda: celery_worker.terminate()) return celery_worker def stop_celery_worker(celery_worker): """ Stops the Celery worker gracefully. Args: celery_worker (subprocess.Popen): The subprocess object representing the Celery worker. """ if celery_worker: # Send SIGTERM signal to gracefully terminate the worker celery_worker.terminate() # Wait for the worker to exit try: celery_worker.wait(timeout=0.5) # Adjust the timeout as needed except subprocess.TimeoutExpired: # If the worker doesn't terminate within the timeout, kill it logging.info("Forcibly terminating the Celery worker.") celery_worker.kill() def main(): """ Main function to initialize the application. Configures celery background worker, database, broadcaster, and audio settings. """ welcome_message() # Optionally start Celery worker celery_worker = None if CELERY_CONFIG.get("RUN_LOCALLY_AUTOMATICALLY", True): logging.info("ROBOT THOUGHT: Starting subconscious systems locally") celery_worker = start_celery_worker() logging.info("ROBOT THOUGHT: Subconscious systems activated") # Setup the database DatabaseSetup.initial_setup() try: # Initialize the audio processor with the configuration settings logging.info("ROBOT THOUGHT: I am ready to begin.") audio_out.add_to_queue("Welcome to Chat Clue's Project Osiris. I am ready to begin.") # Start Audio processing audio_processor = AudioProcessor() audio_thread = threading.Thread(target=audio_processor.process_stream) audio_thread.start() # Start Video processing
# Configure basic logging for the application logging.basicConfig(level=LOG_LEVEL) root_logger = logging.getLogger() for handler in root_logger.handlers: handler.setFormatter(ColorFormatter('%(asctime)s - %(levelname)s - %(message)s')) # Ensure the necessary tmp/ directories exist OSHelper.configure_tmp_directories() # Configure background processor / subconcious systems celery_app = get_celery_app() # Configure audio output audio_out = get_audio_out() def start_celery_worker(): """ Starts a Celery worker as a subprocess. This method initiates a Celery worker using the subprocess module. The worker runs asynchronously and executes tasks defined in the Celery application. The worker is configured to log at the 'info' level for better visibility of its operations. The function also ensures that the Celery worker is terminated gracefully when the Python script exits. This is achieved using the `atexit` module, which registers a function to terminate the worker as part of the script's cleanup process. Returns: subprocess.Popen: The subprocess object representing the Celery worker. """ # Get the log level from configuration, default to 'info' log_level = CELERY_CONFIG.get('LOCAL_LOG_LEVEL', 'info') # Start Celery worker celery_worker = subprocess.Popen(['celery', '-A', 'osiris.celery_app', 'worker', f'--loglevel={log_level}']) # Register function to terminate worker on exit atexit.register(lambda: celery_worker.terminate()) return celery_worker def stop_celery_worker(celery_worker): """ Stops the Celery worker gracefully. Args: celery_worker (subprocess.Popen): The subprocess object representing the Celery worker. """ if celery_worker: # Send SIGTERM signal to gracefully terminate the worker celery_worker.terminate() # Wait for the worker to exit try: celery_worker.wait(timeout=0.5) # Adjust the timeout as needed except subprocess.TimeoutExpired: # If the worker doesn't terminate within the timeout, kill it logging.info("Forcibly terminating the Celery worker.") celery_worker.kill() def main(): """ Main function to initialize the application. Configures celery background worker, database, broadcaster, and audio settings. """ welcome_message() # Optionally start Celery worker celery_worker = None if CELERY_CONFIG.get("RUN_LOCALLY_AUTOMATICALLY", True): logging.info("ROBOT THOUGHT: Starting subconscious systems locally") celery_worker = start_celery_worker() logging.info("ROBOT THOUGHT: Subconscious systems activated") # Setup the database DatabaseSetup.initial_setup() try: # Initialize the audio processor with the configuration settings logging.info("ROBOT THOUGHT: I am ready to begin.") audio_out.add_to_queue("Welcome to Chat Clue's Project Osiris. I am ready to begin.") # Start Audio processing audio_processor = AudioProcessor() audio_thread = threading.Thread(target=audio_processor.process_stream) audio_thread.start() # Start Video processing
video_processor = VideoProcessor()
5
2023-12-06 09:10:06+00:00
12k
lumina-test/lumina
lumina/e2e_test/test_cnp.py
[ { "identifier": "get_qp_info_list", "path": "lumina/analyzer/main.py", "snippet": "LOG_FILENAME = \"analysis.log\"\nRESULT_FILENAME = \"result.out\"\ndef get_qp_info_list(switch_msg_snapshot):\ndef main(args):\ndef parse_args():" }, { "identifier": "Orchestrator", "path": "lumina/orchestrato...
import argparse, os, glob, logging, time import lumina.analyzer.checker.integrity_check as integrity_check import lumina.analyzer.checker.host_check as host_check import lumina.analyzer.checker.cnp_check as cnp_check import lumina.orchestrator.host as host import lumina.orchestrator.switch as switch from lumina.analyzer.main import get_qp_info_list, get_packet_list from lumina.orchestrator.main import Orchestrator from lumina.analyzer.counter.switch_counter import SwitchCounter from lumina.analyzer.counter.host_counter import MLNXHostCounter, IntelHostCounter from lumina.analyzer.pcap_processor.pcap_process import get_packet_list from lumina.utils.config_loggers import config_stream_handler, config_file_handler
8,032
## All logs will be logged into file LOG_FILENAME LOG_FILENAME = "test_cnp.log" ## Results (checkers and measurements) will also be dumped into file RESULT_FILENAME RESULT_FILENAME = "result.log" ## Max # of retries for each experiment iteration MAX_NB_EXP_RETRIES = 3 def setup_root_logger(orchestrator): """ Setup the root logger Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations """ root_logger = logging.getLogger() root_logger.handlers.clear() config_stream_handler(root_logger)
## All logs will be logged into file LOG_FILENAME LOG_FILENAME = "test_cnp.log" ## Results (checkers and measurements) will also be dumped into file RESULT_FILENAME RESULT_FILENAME = "result.log" ## Max # of retries for each experiment iteration MAX_NB_EXP_RETRIES = 3 def setup_root_logger(orchestrator): """ Setup the root logger Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations """ root_logger = logging.getLogger() root_logger.handlers.clear() config_stream_handler(root_logger)
config_file_handler(logger=root_logger,
7
2023-12-09 08:21:14+00:00
12k
Tlntin/booking_simulator
apps/agentfabric/user_core.py
[ { "identifier": "parse_configuration", "path": "config_utils.py", "snippet": "def parse_configuration(uuid_str=''):\n \"\"\"parse configuration\n\n Args:\n\n Returns:\n dict: parsed configuration\n\n \"\"\"\n model_cfg_file = os.getenv('MODEL_CONFIG_FILE', DEFAULT_MODEL_CONFIG_FILE...
import copy import os import gradio as gr from config_utils import parse_configuration from custom_prompt import (DEFAULT_EXEC_TEMPLATE, DEFAULT_SYSTEM_TEMPLATE, DEFAULT_USER_TEMPLATE, CustomPromptGenerator, parse_role_config) from langchain.embeddings import ModelScopeEmbeddings from langchain.vectorstores import FAISS from modelscope_agent.agent import AgentExecutor from modelscope_agent.agent_types import AgentType from modelscope_agent.llm import LLMFactory from modelscope_agent.retrieve import KnowledgeRetrieval from modelscope_agent.tools.openapi_plugin import OpenAPIPluginTool
8,583
# init user chatbot_agent def init_user_chatbot_agent(uuid_str=''): builder_cfg, model_cfg, tool_cfg, available_tool_list, plugin_cfg, available_plugin_list = parse_configuration( uuid_str) # set top_p and stop_words for role play model_cfg[builder_cfg.model]['generate_cfg']['top_p'] = 0.5 model_cfg[builder_cfg.model]['generate_cfg']['stop'] = 'Observation' # build model print(f'using model {builder_cfg.model}') print(f'model config {model_cfg[builder_cfg.model]}') # # check configuration # if builder_cfg.model in ['qwen-max', 'qwen-72b-api', 'qwen-14b-api', 'qwen-plus']: # if 'DASHSCOPE_API_KEY' not in os.environ: # raise gr.Error('DASHSCOPE_API_KEY should be set via setting environment variable') try: llm = LLMFactory.build_llm(builder_cfg.model, model_cfg) except Exception as e: raise gr.Error(str(e)) # build prompt with zero shot react template instruction_template = parse_role_config(builder_cfg) prompt_generator = CustomPromptGenerator( system_template=DEFAULT_SYSTEM_TEMPLATE, user_template=DEFAULT_USER_TEMPLATE,
# init user chatbot_agent def init_user_chatbot_agent(uuid_str=''): builder_cfg, model_cfg, tool_cfg, available_tool_list, plugin_cfg, available_plugin_list = parse_configuration( uuid_str) # set top_p and stop_words for role play model_cfg[builder_cfg.model]['generate_cfg']['top_p'] = 0.5 model_cfg[builder_cfg.model]['generate_cfg']['stop'] = 'Observation' # build model print(f'using model {builder_cfg.model}') print(f'model config {model_cfg[builder_cfg.model]}') # # check configuration # if builder_cfg.model in ['qwen-max', 'qwen-72b-api', 'qwen-14b-api', 'qwen-plus']: # if 'DASHSCOPE_API_KEY' not in os.environ: # raise gr.Error('DASHSCOPE_API_KEY should be set via setting environment variable') try: llm = LLMFactory.build_llm(builder_cfg.model, model_cfg) except Exception as e: raise gr.Error(str(e)) # build prompt with zero shot react template instruction_template = parse_role_config(builder_cfg) prompt_generator = CustomPromptGenerator( system_template=DEFAULT_SYSTEM_TEMPLATE, user_template=DEFAULT_USER_TEMPLATE,
exec_template=DEFAULT_EXEC_TEMPLATE,
1
2023-12-12 04:24:00+00:00
12k