code
stringlengths
17
6.64M
def torch_default_param_init_fn_(module: nn.Module, verbose: int=0, **kwargs): del kwargs if (verbose > 1): warnings.warn(f"Initializing network using module's reset_parameters attribute") if hasattr(module, 'reset_parameters'): module.reset_parameters()
def fused_init_helper_(module: nn.Module, init_fn_): _fused = getattr(module, '_fused', None) if (_fused is None): raise RuntimeError(f'Internal logic error') (dim, splits) = _fused splits = (0, *splits, module.weight.size(dim)) for (s, e) in zip(splits[:(- 1)], splits[1:]): slice_...
def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[(int, float, str, bool)]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[(Tuple[(float, float)], float)]]=None, verbose: int=0, **kwargs): del kwargs i...
def _normal_init_(std, mean=0.0): return partial(torch.nn.init.normal_, mean=mean, std=std)
def _normal_param_init_fn_(module: nn.Module, std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[(int, float, str, bool)]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[(Tuple[(float, float)], float)]]=None, verbose: int=0, **kwargs): del kwargs ...
def baseline_param_init_fn_(module: nn.Module, init_std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[(int, float, str, bool)]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[(Tuple[(float, float)], float)]]=None, verbose: int=0, **kwargs): del kwar...
def small_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, init_div_is_residual: Union[(int, float, str, bool)]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[(Tuple[(float, float)], float)]]=None, verbose: int=0, **kwargs): del kwargs std = math.sqrt((2 / (5 * d_...
def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[(Tuple[(float, float)], float)]]=None, verbose: int=0, **kwargs): 'From section 2.3.1 of GPT-NeoX-20B:\n\n An Open-Source AutoregressiveLanguage Model β€” Black et. al....
def kaiming_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[(int, float, str, bool)]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[(Tuple[(float, float)], float)]]=None, init_gain: float=0, fan_mode: str='fan_in', init_...
def kaiming_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[(int, float, str, bool)]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[(Tuple[(float, float)], float)]]=None, init_gain: float=0, fan_mode: str='fan_in', init_n...
def xavier_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[(int, float, str, bool)]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[(Tuple[(float, float)], float)]]=None, init_gain: float=0, verbose: int=0, **kwargs): ...
def xavier_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[(int, float, str, bool)]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[(Tuple[(float, float)], float)]]=None, init_gain: float=0, verbose: int=0, **kwargs): ...
@torch.inference_mode() def generate_stream(tokenizer, model, params, device, context_len=2048, stream_interval=2): 'Adapted from fastchat/serve/model_worker.py::generate_stream' prompt = params['prompt'] l_prompt = len(prompt) temperature = float(params.get('temperature', 1.0)) max_new_tokens = i...
def main(args): model_name = args.model_name num_gpus = args.num_gpus if (args.device == 'cuda'): kwargs = {'torch_dtype': torch.float16} if (num_gpus == 'auto'): kwargs['device_map'] = 'auto' else: num_gpus = int(num_gpus) if (num_gpus != 1): ...
class DispatchMethod(Enum): LOTTERY = auto() SHORTEST_QUEUE = auto() @classmethod def from_str(cls, name): if (name == 'lottery'): return cls.LOTTERY elif (name == 'shortest_queue'): return cls.SHORTEST_QUEUE else: raise ValueError(f'Invalid...
@dataclasses.dataclass class WorkerInfo(): model_names: List[str] speed: int queue_length: int check_heart_beat: bool last_heart_beat: str
def heart_beat_controller(controller): while True: time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION) controller.remove_stable_workers_by_expiration()
class Controller(): def __init__(self, dispatch_method: str): self.worker_info = {} self.dispatch_method = DispatchMethod.from_str(dispatch_method) self.heart_beat_thread = threading.Thread(target=heart_beat_controller, args=(self,)) self.heart_beat_thread.start() logger.i...
class _Keywords(Enum): NO_VALUE = 'NO_VALUE' FINISHED_ITERATING = 'FINISHED_ITERATING'
@document('style') class Chatbot(Changeable, Selectable, IOComponent, JSONSerializable): '\n Displays a chatbot output showing both user submitted messages and responses. Supports a subset of Markdown including bold, italics, code, and images.\n Preprocessing: this component does *not* accept input.\n Po...
def get_conv_log_filename(): t = datetime.datetime.now() name = os.path.join(LOGDIR, f'{t.year}-{t.month:02d}-{t.day:02d}-conv.json') return name
def get_model_list(): ret = requests.post((args.controller_url + '/refresh_all_workers')) assert (ret.status_code == 200) ret = requests.post((args.controller_url + '/list_models')) models = ret.json()['models'] models.sort(key=(lambda x: priority.get(x, x))) logger.info(f'Models: {models}') ...
def load_demo(url_params, request: gr.Request): logger.info(f'load_demo. ip: {request.client.host}. params: {url_params}') dropdown_update = gr.Dropdown.update(visible=True) if ('model' in url_params): model = url_params['model'] if (model in models): dropdown_update = gr.Dropd...
def load_demo_refresh_model_list(request: gr.Request): logger.info(f'load_demo. ip: {request.client.host}') models = get_model_list() state = default_conversation.copy() return (state, gr.Dropdown.update(choices=models, value=(models[0] if (len(models) > 0) else '')), gr.Chatbot.update(visible=True), ...
def vote_last_response(state, vote_type, model_selector, request: gr.Request): with open(get_conv_log_filename(), 'a') as fout: data = {'tstamp': round(time.time(), 4), 'type': vote_type, 'model': model_selector, 'state': state.dict(), 'ip': request.client.host} fout.write((json.dumps(data) + '\n'...
def upvote_last_response(state, model_selector, request: gr.Request): logger.info(f'upvote. ip: {request.client.host}') vote_last_response(state, 'upvote', model_selector, request) return (('',) + ((disable_btn,) * 3))
def downvote_last_response(state, model_selector, request: gr.Request): logger.info(f'downvote. ip: {request.client.host}') vote_last_response(state, 'downvote', model_selector, request) return (('',) + ((disable_btn,) * 3))
def flag_last_response(state, model_selector, request: gr.Request): logger.info(f'flag. ip: {request.client.host}') vote_last_response(state, 'flag', model_selector, request) return (('',) + ((disable_btn,) * 3))
def regenerate(state, image_process_mode, request: gr.Request): logger.info(f'regenerate. ip: {request.client.host}') state.messages[(- 1)][(- 1)] = None prev_human_msg = state.messages[(- 2)] if (type(prev_human_msg[1]) in (tuple, list)): prev_human_msg[1] = (*prev_human_msg[1][:2], image_pro...
def clear_history(request: gr.Request): logger.info(f'clear_history. ip: {request.client.host}') state = default_conversation.copy() return ((state, state.to_gradio_chatbot(), '', None) + ((disable_btn,) * 5))
def add_text(state, text, image, image_process_mode, request: gr.Request): logger.info(f'add_text. ip: {request.client.host}. len: {len(text)}') if ((len(text) <= 0) and (image is None)): state.skip_next = True return ((state, state.to_gradio_chatbot(), '', None) + ((no_change_btn,) * 5)) ...
def post_process_code(code): sep = '\n```' if (sep in code): blocks = code.split(sep) if ((len(blocks) % 2) == 1): for i in range(1, len(blocks), 2): blocks[i] = blocks[i].replace('\\_', '_') code = sep.join(blocks) return code
def http_bot(state, model_selector, temperature, max_new_tokens, request: gr.Request): logger.info(f'http_bot. ip: {request.client.host}') start_tstamp = time.time() model_name = model_selector if state.skip_next: (yield ((state, state.to_gradio_chatbot()) + ((no_change_btn,) * 5))) re...
def build_demo(embed_mode): textbox = gr.Textbox(show_label=False, placeholder='Enter text and press ENTER', visible=False).style(container=False) with gr.Blocks(title='LLaVA', theme=gr.themes.Base(), css=css) as demo: state = gr.State() if (not embed_mode): gr.Markdown(title_markd...
def heart_beat_worker(controller): while True: time.sleep(WORKER_HEART_BEAT_INTERVAL) controller.send_heart_beat()
def load_model(model_path, model_name, num_gpus): if (num_gpus == 1): kwargs = {} else: kwargs = {'device_map': 'auto', 'max_memory': {i: '13GiB' for i in range(num_gpus)}} tokenizer = AutoTokenizer.from_pretrained(model_path) if ('llava' in model_name.lower()): if ('mpt' in mo...
class ModelWorker(): def __init__(self, controller_addr, worker_addr, worker_id, no_register, model_path, model_name, keep_aspect_ratio, num_gpus): self.controller_addr = controller_addr self.worker_addr = worker_addr self.worker_id = worker_id if model_path.endswith('/'): ...
def release_model_semaphore(fn=None): model_semaphore.release() if (fn is not None): fn()
def main(): if args.worker_address: worker_addr = args.worker_address else: controller_addr = args.controller_address ret = requests.post((controller_addr + '/refresh_all_workers')) ret = requests.post((controller_addr + '/list_models')) models = ret.json()['models'] ...
def forward(self, hidden_states: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor]]=None, attention_mask: Optional[torch.Tensor]=None, output_attentions: bool=False, use_cache: bool=False) -> Tuple[(torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]])]: 'Input shape: Batch x Time x Channe...
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): return attention_mask
def replace_llama_attn_with_flash_attn(): transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = _prepare_decoder_attention_mask transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
def unwrap_model(model: nn.Module) -> nn.Module: '\n Recursively unwraps a model from potential containers (as used in distributed training).\n\n Args:\n model (`torch.nn.Module`): The model to unwrap.\n ' if hasattr(model, 'module'): return unwrap_model(model.module) else: ...
class LLaVATrainer(Trainer): def _save(self, output_dir: Optional[str]=None, state_dict=None): if getattr(self.args, 'tune_mm_mlp_adapter', False): _state_dict = state_dict if (_state_dict is None): model_to_save = unwrap_model(self.model) _state_di...
@dataclass class ModelArguments(): model_name_or_path: Optional[str] = field(default='facebook/opt-125m') version: Optional[str] = field(default='v0') freeze_backbone: bool = field(default=False) tune_mm_mlp_adapter: bool = field(default=False) vision_tower: Optional[str] = field(default=None) ...
@dataclass class DataArguments(): data_path: str = field(default=None, metadata={'help': 'Path to the training data.'}) lazy_preprocess: bool = False is_multimodal: bool = False sep_image_conv_front: bool = False image_token_len: int = 0 image_folder: Optional[str] = field(default=None) im...
@dataclass class TrainingArguments(transformers.TrainingArguments): cache_dir: Optional[str] = field(default=None) optim: str = field(default='adamw_torch') remove_unused_columns: bool = field(default=False) freeze_mm_mlp_adapter: bool = field(default=False) force_fsdp: bool = field(default=False)...
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): 'Collects the state dict and dump to disk.' state_dict = trainer.model.state_dict() if trainer.args.should_save: cpu_state_dict = {key: value.cpu() for (key, value) in state_dict.items()} del state_dict ...
def smart_tokenizer_and_embedding_resize(special_tokens_dict: Dict, tokenizer: transformers.PreTrainedTokenizer, model: transformers.PreTrainedModel): 'Resize tokenizer and embedding.\n\n Note: This is the unoptimized version that may make your embedding size not be divisible by 64.\n ' num_new_tokens =...
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict: 'Tokenize a list of strings.' tokenized_list = [tokenizer(text, return_tensors='pt', padding='longest', max_length=tokenizer.model_max_length, truncation=True) for text in strings] input_ids = labels = [tokenize...
def _mask_targets(target, tokenized_lens, speakers): cur_idx = tokenized_lens[0] tokenized_lens = tokenized_lens[1:] target[:cur_idx] = IGNORE_INDEX for (tokenized_len, speaker) in zip(tokenized_lens, speakers): if (speaker == 'human'): target[(cur_idx + 2):(cur_idx + tokenized_len...
def _add_speaker_and_signal(header, source, get_conversation=True): 'Add speaker and start/end signal on each round.' BEGIN_SIGNAL = '### ' END_SIGNAL = '\n' conversation = header for sentence in source: from_str = sentence['from'] if (from_str.lower() == 'human'): from...
def preprocess_multimodal(sources: Sequence[str], multimodal_cfg: dict, cur_token_len: int) -> Dict: is_multimodal = multimodal_cfg['is_multimodal'] image_token_len = cur_token_len if (not is_multimodal): return sources for source in sources: if multimodal_cfg['sep_image_conv_front']: ...
def preprocess_v1(sources, tokenizer: transformers.PreTrainedTokenizer) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {'human': conv.roles[0], 'gpt': conv.roles[1]} conversations = [] for (i, source) in enumerate(sources): if (roles[source[0]['from']] != conv.roles[0]): ...
def preprocess_mpt(sources, tokenizer: transformers.PreTrainedTokenizer) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {'human': conv.roles[0], 'gpt': conv.roles[1]} conversations = [] for (i, source) in enumerate(sources): if (roles[source[0]['from']] != conv.roles[0]):...
def preprocess(sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict: "\n Given a list of sources, each is a conversation list. This transform:\n 1. Add signal '### ' at the beginning each sentence, with end signal '\n';\n 2. Concatenate conversations together;\n 3. Tokenize the...
class SupervisedDataset(Dataset): 'Dataset for supervised fine-tuning.' def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer): super(SupervisedDataset, self).__init__() logging.warning('Loading data...') list_data_dict = json.load(open(data_path, 'r')) ...
class LazySupervisedDataset(Dataset): 'Dataset for supervised fine-tuning.' def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer, multimodal_cfg: dict): super(LazySupervisedDataset, self).__init__() logging.warning('Loading data...') list_data_dict = json.loa...
@dataclass class DataCollatorForSupervisedDataset(object): 'Collate examples for supervised fine-tuning.' tokenizer: transformers.PreTrainedTokenizer def __call__(self, instances: Sequence[Dict]) -> Dict[(str, torch.Tensor)]: (input_ids, labels) = tuple(([instance[key] for instance in instances] ...
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict: 'Make dataset and collator for supervised fine-tuning.' dataset_cls = (LazySupervisedDataset if data_args.lazy_preprocess else SupervisedDataset) train_dataset = dataset_cls(tokenizer=tokenizer, data_path=data...
def train(): parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments)) (model_args, data_args, training_args) = parser.parse_args_into_dataclasses() if (model_args.vision_tower is not None): if ('mpt' in model_args.model_name_or_path): model = LlavaMPTF...
def build_logger(logger_name, logger_filename): global handler formatter = logging.Formatter(fmt='%(asctime)s | %(levelname)s | %(name)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S') if (not logging.getLogger().handlers): logging.basicConfig(level=logging.INFO) logging.getLogger().handlers[0].s...
class StreamToLogger(object): '\n Fake file-like stream object that redirects writes to a logger instance.\n ' def __init__(self, logger, log_level=logging.INFO): self.terminal = sys.stdout self.logger = logger self.log_level = log_level self.linebuf = '' def __geta...
def disable_torch_init(): '\n Disable the redundant torch default initialization to accelerate model creation.\n ' import torch setattr(torch.nn.Linear, 'reset_parameters', (lambda self: None)) setattr(torch.nn.LayerNorm, 'reset_parameters', (lambda self: None))
def violates_moderation(text): '\n Check whether the text violates OpenAI moderation API.\n ' url = 'https://api.openai.com/v1/moderations' headers = {'Content-Type': 'application/json', 'Authorization': ('Bearer ' + os.environ['OPENAI_API_KEY'])} text = text.replace('\n', '') data = ((('{' ...
def pretty_print_semaphore(semaphore): if (semaphore is None): return 'None' return f'Semaphore(value={semaphore._value}, locked={semaphore.locked()})'
def check_installation(): 'Check whether mmcv-full has been installed successfully.' np_boxes1 = np.asarray([[1.0, 1.0, 3.0, 4.0, 0.5], [2.0, 2.0, 3.0, 4.0, 0.6], [7.0, 7.0, 8.0, 8.0, 0.4]], dtype=np.float32) np_boxes2 = np.asarray([[0.0, 2.0, 2.0, 5.0, 0.3], [2.0, 1.0, 3.0, 3.0, 0.5], [5.0, 5.0, 6.0, 7.0...
class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(((16 * 5) * 5), 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.L...
def quantize(arr, min_val, max_val, levels, dtype=np.int64): 'Quantize an array of (-inf, inf) to [0, levels-1].\n\n Args:\n arr (ndarray): Input array.\n min_val (scalar): Minimum value to be clipped.\n max_val (scalar): Maximum value to be clipped.\n levels (int): Quantization lev...
def dequantize(arr, min_val, max_val, levels, dtype=np.float64): 'Dequantize an array.\n\n Args:\n arr (ndarray): Input array.\n min_val (scalar): Minimum value to be clipped.\n max_val (scalar): Maximum value to be clipped.\n levels (int): Quantization levels.\n dtype (np.ty...
class AlexNet(nn.Module): 'AlexNet backbone.\n\n Args:\n num_classes (int): number of classes for classification.\n ' def __init__(self, num_classes=(- 1)): super(AlexNet, self).__init__() self.num_classes = num_classes self.features = nn.Sequential(nn.Conv2d(3, 64, kerne...
@ACTIVATION_LAYERS.register_module(name='Clip') @ACTIVATION_LAYERS.register_module() class Clamp(nn.Module): 'Clamp activation layer.\n\n This activation function is to clamp the feature map value within\n :math:`[min, max]`. More details can be found in ``torch.clamp()``.\n\n Args:\n min (Number ...
class GELU(nn.Module): 'Applies the Gaussian Error Linear Units function:\n\n .. math::\n \\text{GELU}(x) = x * \\Phi(x)\n where :math:`\\Phi(x)` is the Cumulative Distribution Function for\n Gaussian Distribution.\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of addit...
def build_activation_layer(cfg): 'Build activation layer.\n\n Args:\n cfg (dict): The activation layer config, which should contain:\n\n - type (str): Layer type.\n - layer args: Args needed to instantiate an activation layer.\n\n Returns:\n nn.Module: Created activation ...
def last_zero_init(m): if isinstance(m, nn.Sequential): constant_init(m[(- 1)], val=0) else: constant_init(m, val=0)
@PLUGIN_LAYERS.register_module() class ContextBlock(nn.Module): "ContextBlock module in GCNet.\n\n See 'GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond'\n (https://arxiv.org/abs/1904.11492) for details.\n\n Args:\n in_channels (int): Channels of the input feature map.\n ...
def build_conv_layer(cfg, *args, **kwargs): 'Build convolution layer.\n\n Args:\n cfg (None or dict): The conv layer config, which should contain:\n - type (str): Layer type.\n - layer args: Args needed to instantiate an conv layer.\n args (argument list): Arguments passed t...
@CONV_LAYERS.register_module() class Conv2dAdaptivePadding(nn.Conv2d): 'Implementation of 2D convolution in tensorflow with `padding` as "same",\n which applies padding to input (if needed) so that input image gets fully\n covered by filter and stride you specified. For stride 1, this will ensure\n that ...
@PLUGIN_LAYERS.register_module() class ConvModule(nn.Module): 'A conv block that bundles conv/norm/activation layers.\n\n This block simplifies the usage of convolution layers, which are commonly\n used with a norm layer (e.g., BatchNorm) and activation layer (e.g., ReLU).\n It is based upon three build ...
def conv_ws_2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, eps=1e-05): c_in = weight.size(0) weight_flat = weight.view(c_in, (- 1)) mean = weight_flat.mean(dim=1, keepdim=True).view(c_in, 1, 1, 1) std = weight_flat.std(dim=1, keepdim=True).view(c_in, 1, 1, 1) weight = ((we...
@CONV_LAYERS.register_module('ConvWS') class ConvWS2d(nn.Conv2d): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, eps=1e-05): super(ConvWS2d, self).__init__(in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=di...
@CONV_LAYERS.register_module(name='ConvAWS') class ConvAWS2d(nn.Conv2d): 'AWS (Adaptive Weight Standardization)\n\n This is a variant of Weight Standardization\n (https://arxiv.org/pdf/1903.10520.pdf)\n It is used in DetectoRS to avoid NaN\n (https://arxiv.org/pdf/2006.02334.pdf)\n\n Args:\n ...
class DepthwiseSeparableConvModule(nn.Module): "Depthwise separable convolution module.\n\n See https://arxiv.org/pdf/1704.04861.pdf for details.\n\n This module can replace a ConvModule with the conv block replaced by two\n conv block: depthwise conv block and pointwise conv block. The depthwise\n co...
def drop_path(x, drop_prob=0.0, training=False): 'Drop paths (Stochastic Depth) per sample (when applied in main path of\n residual blocks).\n\n We follow the implementation\n https://github.com/rwightman/pytorch-image-models/blob/a2727c1bf78ba0d7b5727f5f95e37fb7f8866b1f/timm/models/layers/drop.py # noq...
@DROPOUT_LAYERS.register_module() class DropPath(nn.Module): 'Drop paths (Stochastic Depth) per sample (when applied in main path of\n residual blocks).\n\n We follow the implementation\n https://github.com/rwightman/pytorch-image-models/blob/a2727c1bf78ba0d7b5727f5f95e37fb7f8866b1f/timm/models/layers/d...
@DROPOUT_LAYERS.register_module() class Dropout(nn.Dropout): 'A wrapper for ``torch.nn.Dropout``, We rename the ``p`` of\n ``torch.nn.Dropout`` to ``drop_prob`` so as to be consistent with\n ``DropPath``\n\n Args:\n drop_prob (float): Probability of the elements to be\n zeroed. Default:...
def build_dropout(cfg, default_args=None): 'Builder for drop out layers.' return build_from_cfg(cfg, DROPOUT_LAYERS, default_args)
@ACTIVATION_LAYERS.register_module() class HSigmoid(nn.Module): 'Hard Sigmoid Module. Apply the hard sigmoid function:\n Hsigmoid(x) = min(max((x + bias) / divisor, min_value), max_value)\n Default: Hsigmoid(x) = min(max((x + 3) / 6, 0), 1)\n\n Note:\n In MMCV v1.4.4, we modified the default value...
class HSwish(nn.Module): 'Hard Swish Module.\n\n This module applies the hard swish function:\n\n .. math::\n Hswish(x) = x * ReLU6(x + 3) / 6\n\n Args:\n inplace (bool): can optionally do the operation in-place.\n Default: False.\n\n Returns:\n Tensor: The output tenso...
class _NonLocalNd(nn.Module, metaclass=ABCMeta): 'Basic Non-local module.\n\n This module is proposed in\n "Non-local Neural Networks"\n Paper reference: https://arxiv.org/abs/1711.07971\n Code reference: https://github.com/AlexHex7/Non-local_pytorch\n\n Args:\n in_channels (int): Channels o...
class NonLocal1d(_NonLocalNd): "1D Non-local module.\n\n Args:\n in_channels (int): Same as `NonLocalND`.\n sub_sample (bool): Whether to apply max pooling after pairwise\n function (Note that the `sub_sample` is applied on spatial only).\n Default: False.\n conv_cfg ...
@PLUGIN_LAYERS.register_module() class NonLocal2d(_NonLocalNd): "2D Non-local module.\n\n Args:\n in_channels (int): Same as `NonLocalND`.\n sub_sample (bool): Whether to apply max pooling after pairwise\n function (Note that the `sub_sample` is applied on spatial only).\n D...
class NonLocal3d(_NonLocalNd): "3D Non-local module.\n\n Args:\n in_channels (int): Same as `NonLocalND`.\n sub_sample (bool): Whether to apply max pooling after pairwise\n function (Note that the `sub_sample` is applied on spatial only).\n Default: False.\n conv_cfg ...
def infer_abbr(class_type): 'Infer abbreviation from the class name.\n\n When we build a norm layer with `build_norm_layer()`, we want to preserve\n the norm type in variable names, e.g, self.bn1, self.gn. This method will\n infer the abbreviation to map class types to abbreviations.\n\n Rule 1: If th...
def build_norm_layer(cfg, num_features, postfix=''): 'Build normalization layer.\n\n Args:\n cfg (dict): The norm layer config, which should contain:\n\n - type (str): Layer type.\n - layer args: Args needed to instantiate a norm layer.\n - requires_grad (bool, optional)...
def is_norm(layer, exclude=None): 'Check if a layer is a normalization layer.\n\n Args:\n layer (nn.Module): The layer to be checked.\n exclude (type | tuple[type]): Types to be excluded.\n\n Returns:\n bool: Whether the layer is a norm layer.\n ' if (exclude is not None): ...
def build_padding_layer(cfg, *args, **kwargs): 'Build padding layer.\n\n Args:\n cfg (None or dict): The padding layer config, which should contain:\n - type (str): Layer type.\n - layer args: Args needed to instantiate a padding layer.\n\n Returns:\n nn.Module: Created p...
def infer_abbr(class_type): 'Infer abbreviation from the class name.\n\n This method will infer the abbreviation to map class types to\n abbreviations.\n\n Rule 1: If the class has the property "abbr", return the property.\n Rule 2: Otherwise, the abbreviation falls back to snake case of class\n na...
def build_plugin_layer(cfg, postfix='', **kwargs): "Build plugin layer.\n\n Args:\n cfg (None or dict): cfg should contain:\n\n - type (str): identify plugin layer type.\n - layer args: args needed to instantiate a plugin layer.\n postfix (int, str): appended into norm abbre...
class Scale(nn.Module): 'A learnable scale parameter.\n\n This layer scales the input by a learnable factor. It multiplies a\n learnable scale parameter of shape (1,) with input of any shape.\n\n Args:\n scale (float): Initial value of scale factor. Default: 1.0\n ' def __init__(self, scal...