| {"repo_id":"M2PT","entity_id":"py:model_example","uri":"program://M2PT/module/model_example#L1-L29","kind":"module","name":"model_example","path":"model_example.py","language":"python","start_line":1,"end_line":29,"context_start_line":1,"context_end_line":29,"code":"import torch\nfrom torch import nn\nfrom m2pt.main import M2PT\n\n# Create an instance of the MPTransformerBlock class with the specified parameters\nmodel = M2PT(\n dim=512, # Dimension of the input and output tensors\n num_tokens=10000,\n depth=6,\n dim_head=64, # Dimension of each attention head\n heads=8, # Number of attention heads\n dropout=0.1, # Dropout rate\n ff_mult=4, # Multiplier for the dimension of the feed-forward network\n original_linear=nn.Linear(512, 512), # Linear layer for the original input tensor\n auxiliar_linear=nn.Linear(512, 512), # Linear layer for the auxiliary input tensor\n ffn_original_linear=nn.Linear, # Linear layer for the original input tensor in the feed-forward network\n ffn_auxiliar_linear=nn.Linear, # Linear layer for the auxiliary input tensor in the feed-forward network\n ffn_original_last_linear=nn.Linear, # Last linear layer for the original input tensor in the feed-forward network\n ffn_aux_last_linear=nn.Linear, # Last linear layer for the auxiliary input tensor in the feed-forward network\n)\n\n# Create a 3D tensor with shape B x S x D\nx = torch.randint(0, 10000, (1, 512))\n\n# Pass the input tensor through the model\nout = model(x)\n\n# Print the shape of the output tensor\nprint(out.shape)","source_hash":"d24a5209a920e60f35f2a1c3e4a14ff7b796d1b3698ef04d0b072e913a127412","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:example","uri":"program://M2PT/module/example#L1-L27","kind":"module","name":"example","path":"example.py","language":"python","start_line":1,"end_line":27,"context_start_line":1,"context_end_line":27,"code":"import torch\nfrom torch import nn\nfrom m2pt import MPTransformerBlock\n\n# Create an instance of the MPTransformerBlock class with the specified parameters\nmodel = MPTransformerBlock(\n dim=512, # Dimension of the input and output tensors\n dim_head=64, # Dimension of each attention head\n heads=8, # Number of attention heads\n dropout=0.1, # Dropout rate\n ff_mult=4, # Multiplier for the dimension of the feed-forward network\n original_linear=nn.Linear(512, 512), # Linear layer for the original input tensor\n auxiliar_linear=nn.Linear(512, 512), # Linear layer for the auxiliary input tensor\n ffn_original_linear=nn.Linear, # Linear layer for the original input tensor in the feed-forward network\n ffn_auxiliar_linear=nn.Linear, # Linear layer for the auxiliary input tensor in the feed-forward network\n ffn_original_last_linear=nn.Linear, # Last linear layer for the original input tensor in the feed-forward network\n ffn_aux_last_linear=nn.Linear, # Last linear layer for the auxiliary input tensor in the feed-forward network\n)\n\n# Create a 3D tensor with shape B x S x D\nx = torch.randn(1, 512, 512)\n\n# Pass the input tensor through the model\nout = model(x)\n\n# Print the shape of the output tensor\nprint(out.shape)","source_hash":"400c144f38a8cc5a7dd896fdda7b083f58ddd38248e9b9a78a0fa99c65a806a4","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main","uri":"program://M2PT/module/m2pt.main#L1-L450","kind":"module","name":"m2pt.main","path":"m2pt/main.py","language":"python","start_line":1,"end_line":450,"context_start_line":1,"context_end_line":450,"code":"import torch\nfrom torch import nn, Tensor\nfrom zeta.nn.attention.multihead_attention import MultiheadAttention\nfrom typing import List\nimport torch.nn.functional as F\n\n\nclass CrossModalReparamLinear(nn.Linear):\n \"\"\"\n Linear layer with cross-modal reparameterization.\n\n Args:\n in_features (int): Size of each input sample.\n out_features (int): Size of each output sample.\n bias (bool, optional): If set to False, the layer will not learn an additive bias. Default is True.\n origin_layer (nn.Linear, optional): Original linear layer to initialize the weight and bias from. Default is None.\n aux_weight (torch.Tensor, optional): Auxiliary weight tensor. Default is None.\n is_aux_trainable (bool, optional): If set to False, the auxiliary weight will not be trainable. Default is True.\n \"\"\"\n\n def __init__(\n self,\n in_features,\n out_features,\n bias=True,\n origin_layer=None,\n aux_weight=None,\n is_aux_trainable=True,\n ):\n super().__init__(in_features, out_features, bias)\n self.cross_modal_scale = nn.Parameter(torch.zeros(1))\n assert (\n self.weight.size() == aux_weight.size()\n ), \"Target weight and aux weight must have the same shape\"\n self.aux_weight = aux_weight\n self.aux_weight.requires_grad_(is_aux_trainable)\n if origin_layer is not None:\n with torch.no_grad():\n self.weight.copy_(origin_layer.weight)\n self.bias.copy_(origin_layer.bias)\n\n def forward(self, input):\n \"\"\"\n Forward pass of the CrossModalReparamLinear layer.\n\n Args:\n input (torch.Tensor): Input tensor.\n\n Returns:\n torch.Tensor: Output tensor.\n \"\"\"\n weight = (\n self.weight + self.cross_modal_scale * self.aux_weight\n )\n return F.linear(input, weight, self.bias)\n\n\ndef cross_modal_ffn(\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n dim: int,\n ff_mult: int,\n dropout: int,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n *args,\n **kwargs,\n):\n \"\"\"\n Cross-modal feed-forward network.\n\n Args:\n ffn_original_linear (nn.Linear): Linear layer for the original modality.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n dim (int): Dimension of the input.\n ff_mult (int): Multiplier for the hidden dimension.\n dropout (int): Dropout rate.\n ffn_original_last_linear (nn.Linear): Linear layer for the original modality in the last step.\n ffn_aux_last_linear (nn.Linear): Linear layer for the auxiliary modality in the last step.\n *args: Variable length arguments.\n **kwargs: Keyword arguments.\n\n Returns:\n nn.Sequential: Sequential model representing the cross-modal feed-forward network.\n \"\"\"\n\n ffn_1st_rep_linear = CrossModalReParametrization(\n ffn_original_linear(dim, dim * ff_mult),\n ffn_auxiliar_linear(dim, dim * ff_mult),\n )\n\n ffn_2nd_linear = CrossModalReParametrization(\n ffn_original_last_linear(dim * ff_mult, dim),\n ffn_aux_last_linear(dim * ff_mult, dim),\n )\n\n return nn.Sequential(\n ffn_1st_rep_linear,\n nn.GELU(),\n nn.Dropout(dropout),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n\ndef build_cross_modal_reparam_linear(origin_layer, aux_layer):\n assert origin_layer.weight.size() == aux_layer.weight.size()\n return CrossModalReparamLinear(\n in_features=origin_layer.in_features,\n out_features=origin_layer.out_features,\n origin_layer=origin_layer,\n bias=origin_layer.bias is not None,\n aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n\ndef _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name\n):\n origin_linear_layer = _get_attr_by_name(target_module, layer_name)\n aux_linear_layer = _get_attr_by_name(aux_module, layer_name)\n reparam_layer = build_cross_modal_reparam_linear(\n origin_linear_layer, aux_linear_layer\n )\n _set_attr_by_name(target_module, layer_name, reparam_layer)\n\n\ndef reparameterize_aux_into_target_model(\n target_model,\n aux_model,\n layer_names=(\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"),\n main_body_name=\"blocks\",\n):\n \"\"\"\n Reparameterizes the auxiliary model into the target model by replacing specific layers with corresponding layers from the auxiliary model.\n\n Args:\n target_model (object): The target model to reparameterize.\n aux_model (object): The auxiliary model containing the replacement layers.\n layer_names (tuple, optional): The names of the layers to be replaced. Defaults to (\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\").\n main_body_name (str, optional): The name of the main body of the models. Defaults to \"blocks\".\n \"\"\"\n target_transformer_blocks = _get_attr_by_name(\n target_model, main_body_name\n )\n aux_transformer_blocks = _get_attr_by_name(\n aux_model, main_body_name\n )\n for target_block, aux_block in zip(\n target_transformer_blocks, aux_transformer_blocks\n ):\n for layer_name in layer_names:\n change_original_linear_to_reparam(\n target_block, aux_block, layer_name\n )\n\n\nclass CrossModalReParametrization(nn.Module):\n \"\"\"\n A module for cross-modal reparametrization.\n\n Args:\n original_linear (nn.Linear): The original linear layer.\n auxiliary_linear (nn.Linear): The auxiliary linear layer.\n\n Attributes:\n cross_modal_scale (nn.Parameter): The scale parameter for cross-modal reparametrization.\n\n Methods:\n forward(x: Tensor) -> Tensor: Performs forward pass through the module.\n merge(): Merges the weights and biases of the original and auxiliary linear layers.\n \"\"\"\n\n def __init__(\n self,\n original_linear: nn.Linear,\n auxiliary_linear: nn.Linear,\n linears: List[nn.Linear] = None,\n ):\n super().__init__()\n self.original_linear = original_linear\n self.auxiliary_linear = auxiliary_linear\n self.cross_modal_scale = nn.Parameter(torch.zeros(1))\n\n def forward(self, x: Tensor) -> Tensor:\n combined_weight = (\n self.original_linear.weight\n + self.cross_modal_scale * self.auxiliary_linear.weight\n )\n return nn.functional.linear(\n x, combined_weight, self.original_linear.bias\n )\n\n def merge(self):\n self.original_linear.weight.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.weight.data\n )\n if (\n self.original_linear.bias is not None\n and self.auxiliary_linear.bias is not None\n ):\n self.original_linear.bias.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.bias.data\n )\n\n\nclass MPTransformerBlock(nn.Module):\n \"\"\"\n Multi-Modal Transformer Block.\n\n Args:\n dim (int): Dimension of the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n original_linear (nn.Linear): Linear layer for the original modality.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n dim_head: int,\n heads: int,\n dropout: float,\n ff_mult: int,\n original_linear: nn.Linear,\n auxiliar_linear: nn.Linear,\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n ):\n super().__init__()\n self.dim = dim\n self.dim_head = dim_head\n self.heads = heads\n self.dropout = dropout\n self.ff_mult = ff_mult\n self.original_linear = original_linear\n self.auxiliar_linear = auxiliar_linear\n self.ffn_auxiliar_linear = ffn_auxiliar_linear\n self.ffn_original_last_linear = ffn_original_last_linear\n self.ffn_aux_last_linear = ffn_aux_last_linear\n\n self.ffn_1st_rep_linear = CrossModalReParametrization(\n ffn_original_linear(dim, dim * ff_mult),\n self.ffn_auxiliar_linear(dim, dim * ff_mult),\n )\n\n self.ffn_2nd_linear = CrossModalReParametrization(\n ffn_original_last_linear(dim * ff_mult, dim),\n ffn_aux_last_linear(dim * ff_mult, dim),\n )\n\n self.ffn = nn.Sequential(\n self.ffn_1st_rep_linear,\n nn.GELU(),\n nn.Dropout(),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n self.ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n # Cross modal reparametrization\n self.reparametrization = CrossModalReParametrization(\n self.original_linear, self.auxiliar_linear\n )\n\n # Norm\n self.norm = nn.LayerNorm(self.dim)\n\n # Check for gpu\n self.is_cuda = torch.cuda.is_available()\n\n # Flash Attention\n self.mha = MultiheadAttention(\n dim,\n heads,\n dropout,\n subln=True,\n )\n\n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the Multi-Modal Transformer Block.\n\n Args:\n x (Tensor): Input tensor.\n\n Returns:\n Tensor: Output tensor.\n \"\"\"\n skip = x\n x = self.norm(x)\n\n # Cross Modal Reparametrization with the q, k, v\n q, k, v = (\n self.reparametrization(x),\n self.reparametrization(x),\n self.reparametrization(x),\n )\n print(f\"All shapes: {q.shape}, {k.shape}, {v.shape}\")\n\n # Attention\n attn = self.mha(q, k, v)\n\n # After attention projections\n attn_out = self.reparametrization(attn) + skip\n\n # Norm\n attn_out_norm = self.norm(attn_out)\n\n # Reparameterization again\n norm_then_reparam = self.reparametrization(attn_out_norm)\n\n # Reparameterization again\n reparam_them_reparam = self.reparametrization(\n norm_then_reparam\n )\n\n # FFN\n ffn = self.ffn(reparam_them_reparam)\n\n return self.norm(ffn)\n\n # return reparam_them_reparam + attn_out_norm\n\n\n\nclass M2PT(nn.Module):\n \"\"\"\n M2PT (Multi-Perspective Transformer) model.\n\n Args:\n dim (int): Dimension of the model.\n depth (int): Number of transformer blocks.\n num_tokens (int): Number of tokens in the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n ff_mult (int): Multiplier for the feed-forward network dimension.\n original_linear (nn.Linear): Linear layer for the original input.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary input.\n ffn_original_linear (nn.Linear): Linear layer for the original input in the feed-forward network.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary input in the feed-forward network.\n ffn_original_last_linear (nn.Linear): Last linear layer for the original input in the feed-forward network.\n ffn_aux_last_linear (nn.Linear): Last linear layer for the auxiliary input in the feed-forward network.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n depth: int,\n num_tokens: int,\n dim_head: int,\n heads: int,\n dropout: float,\n ff_mult: int,\n original_linear: nn.Linear,\n auxiliar_linear: nn.Linear,\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n ):\n super().__init__()\n self.dim = dim\n self.depth = depth\n self.num_tokens = num_tokens\n self.dim_head = dim_head\n self.heads = heads\n self.dropout = dropout\n self.ff_mult = ff_mult\n self.original_linear = original_linear\n self.auxiliar_linear = auxiliar_linear\n self.ffn_original_linear = ffn_original_linear\n self.ffn_auxiliar_linear = ffn_auxiliar_linear\n self.ffn_original_last_linear = ffn_original_last_linear\n self.ffn_aux_last_linear = ffn_aux_last_linear\n \n self.layers = nn.ModuleList([])\n \n for _ in range(depth):\n self.layers.append(\n MPTransformerBlock(\n dim=dim,\n dim_head=dim_head,\n heads=heads,\n dropout=dropout,\n ff_mult=ff_mult,\n original_linear=original_linear,\n auxiliar_linear=auxiliar_linear,\n ffn_original_linear=ffn_original_linear,\n ffn_auxiliar_linear=ffn_auxiliar_linear,\n ffn_original_last_linear=ffn_original_last_linear,\n ffn_aux_last_linear=ffn_aux_last_linear,\n )\n )\n \n self.norm = nn.LayerNorm(dim)\n \n self.embedding = nn.Embedding(num_tokens, dim)\n \n self.to_out = nn.Sequential(\n nn.Linear(dim, num_tokens),\n nn.Softmax(dim=-1),\n # nn.LayerNorm(dim)\n )\n \n \n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the M2PT model.\n\n Args:\n x (Tensor): Input tensor of shape (batch_size, sequence_length).\n\n Returns:\n Tensor: Output tensor of shape (batch_size, sequence_length, num_tokens).\n \"\"\"\n x = self.embedding(x)\n \n for layer in self.layers:\n x = layer(x) + x\n \n x = self.to_out(x)\n \n return self.norm(x)","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main.CrossModalReparamLinear","uri":"program://M2PT/class/m2pt.main.CrossModalReparamLinear#L8-L55","kind":"class","name":"CrossModalReparamLinear","path":"m2pt/main.py","language":"python","start_line":8,"end_line":55,"context_start_line":1,"context_end_line":75,"code":"import torch\nfrom torch import nn, Tensor\nfrom zeta.nn.attention.multihead_attention import MultiheadAttention\nfrom typing import List\nimport torch.nn.functional as F\n\n\nclass CrossModalReparamLinear(nn.Linear):\n \"\"\"\n Linear layer with cross-modal reparameterization.\n\n Args:\n in_features (int): Size of each input sample.\n out_features (int): Size of each output sample.\n bias (bool, optional): If set to False, the layer will not learn an additive bias. Default is True.\n origin_layer (nn.Linear, optional): Original linear layer to initialize the weight and bias from. Default is None.\n aux_weight (torch.Tensor, optional): Auxiliary weight tensor. Default is None.\n is_aux_trainable (bool, optional): If set to False, the auxiliary weight will not be trainable. Default is True.\n \"\"\"\n\n def __init__(\n self,\n in_features,\n out_features,\n bias=True,\n origin_layer=None,\n aux_weight=None,\n is_aux_trainable=True,\n ):\n super().__init__(in_features, out_features, bias)\n self.cross_modal_scale = nn.Parameter(torch.zeros(1))\n assert (\n self.weight.size() == aux_weight.size()\n ), \"Target weight and aux weight must have the same shape\"\n self.aux_weight = aux_weight\n self.aux_weight.requires_grad_(is_aux_trainable)\n if origin_layer is not None:\n with torch.no_grad():\n self.weight.copy_(origin_layer.weight)\n self.bias.copy_(origin_layer.bias)\n\n def forward(self, input):\n \"\"\"\n Forward pass of the CrossModalReparamLinear layer.\n\n Args:\n input (torch.Tensor): Input tensor.\n\n Returns:\n torch.Tensor: Output tensor.\n \"\"\"\n weight = (\n self.weight + self.cross_modal_scale * self.aux_weight\n )\n return F.linear(input, weight, self.bias)\n\n\ndef cross_modal_ffn(\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n dim: int,\n ff_mult: int,\n dropout: int,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n *args,\n **kwargs,\n):\n \"\"\"\n Cross-modal feed-forward network.\n\n Args:\n ffn_original_linear (nn.Linear): Linear layer for the original modality.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n dim (int): Dimension of the input.","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main.cross_modal_ffn","uri":"program://M2PT/function/m2pt.main.cross_modal_ffn#L58-L105","kind":"function","name":"cross_modal_ffn","path":"m2pt/main.py","language":"python","start_line":58,"end_line":105,"context_start_line":38,"context_end_line":125,"code":" with torch.no_grad():\n self.weight.copy_(origin_layer.weight)\n self.bias.copy_(origin_layer.bias)\n\n def forward(self, input):\n \"\"\"\n Forward pass of the CrossModalReparamLinear layer.\n\n Args:\n input (torch.Tensor): Input tensor.\n\n Returns:\n torch.Tensor: Output tensor.\n \"\"\"\n weight = (\n self.weight + self.cross_modal_scale * self.aux_weight\n )\n return F.linear(input, weight, self.bias)\n\n\ndef cross_modal_ffn(\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n dim: int,\n ff_mult: int,\n dropout: int,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n *args,\n **kwargs,\n):\n \"\"\"\n Cross-modal feed-forward network.\n\n Args:\n ffn_original_linear (nn.Linear): Linear layer for the original modality.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n dim (int): Dimension of the input.\n ff_mult (int): Multiplier for the hidden dimension.\n dropout (int): Dropout rate.\n ffn_original_last_linear (nn.Linear): Linear layer for the original modality in the last step.\n ffn_aux_last_linear (nn.Linear): Linear layer for the auxiliary modality in the last step.\n *args: Variable length arguments.\n **kwargs: Keyword arguments.\n\n Returns:\n nn.Sequential: Sequential model representing the cross-modal feed-forward network.\n \"\"\"\n\n ffn_1st_rep_linear = CrossModalReParametrization(\n ffn_original_linear(dim, dim * ff_mult),\n ffn_auxiliar_linear(dim, dim * ff_mult),\n )\n\n ffn_2nd_linear = CrossModalReParametrization(\n ffn_original_last_linear(dim * ff_mult, dim),\n ffn_aux_last_linear(dim * ff_mult, dim),\n )\n\n return nn.Sequential(\n ffn_1st_rep_linear,\n nn.GELU(),\n nn.Dropout(dropout),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n\ndef build_cross_modal_reparam_linear(origin_layer, aux_layer):\n assert origin_layer.weight.size() == aux_layer.weight.size()\n return CrossModalReparamLinear(\n in_features=origin_layer.in_features,\n out_features=origin_layer.out_features,\n origin_layer=origin_layer,\n bias=origin_layer.bias is not None,\n aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main.build_cross_modal_reparam_linear","uri":"program://M2PT/function/m2pt.main.build_cross_modal_reparam_linear#L108-L116","kind":"function","name":"build_cross_modal_reparam_linear","path":"m2pt/main.py","language":"python","start_line":108,"end_line":116,"context_start_line":88,"context_end_line":136,"code":" ffn_original_linear(dim, dim * ff_mult),\n ffn_auxiliar_linear(dim, dim * ff_mult),\n )\n\n ffn_2nd_linear = CrossModalReParametrization(\n ffn_original_last_linear(dim * ff_mult, dim),\n ffn_aux_last_linear(dim * ff_mult, dim),\n )\n\n return nn.Sequential(\n ffn_1st_rep_linear,\n nn.GELU(),\n nn.Dropout(dropout),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n\ndef build_cross_modal_reparam_linear(origin_layer, aux_layer):\n assert origin_layer.weight.size() == aux_layer.weight.size()\n return CrossModalReparamLinear(\n in_features=origin_layer.in_features,\n out_features=origin_layer.out_features,\n origin_layer=origin_layer,\n bias=origin_layer.bias is not None,\n aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n\ndef _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main._get_attr_by_name","uri":"program://M2PT/function/m2pt.main._get_attr_by_name#L119-L123","kind":"function","name":"_get_attr_by_name","path":"m2pt/main.py","language":"python","start_line":119,"end_line":123,"context_start_line":99,"context_end_line":143,"code":" nn.GELU(),\n nn.Dropout(dropout),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n\ndef build_cross_modal_reparam_linear(origin_layer, aux_layer):\n assert origin_layer.weight.size() == aux_layer.weight.size()\n return CrossModalReparamLinear(\n in_features=origin_layer.in_features,\n out_features=origin_layer.out_features,\n origin_layer=origin_layer,\n bias=origin_layer.bias is not None,\n aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n\ndef _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name\n):\n origin_linear_layer = _get_attr_by_name(target_module, layer_name)\n aux_linear_layer = _get_attr_by_name(aux_module, layer_name)\n reparam_layer = build_cross_modal_reparam_linear(\n origin_linear_layer, aux_linear_layer\n )\n _set_attr_by_name(target_module, layer_name, reparam_layer)","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main._set_attr_by_name","uri":"program://M2PT/function/m2pt.main._set_attr_by_name#L126-L132","kind":"function","name":"_set_attr_by_name","path":"m2pt/main.py","language":"python","start_line":126,"end_line":132,"context_start_line":106,"context_end_line":152,"code":"\n\ndef build_cross_modal_reparam_linear(origin_layer, aux_layer):\n assert origin_layer.weight.size() == aux_layer.weight.size()\n return CrossModalReparamLinear(\n in_features=origin_layer.in_features,\n out_features=origin_layer.out_features,\n origin_layer=origin_layer,\n bias=origin_layer.bias is not None,\n aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n\ndef _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name\n):\n origin_linear_layer = _get_attr_by_name(target_module, layer_name)\n aux_linear_layer = _get_attr_by_name(aux_module, layer_name)\n reparam_layer = build_cross_modal_reparam_linear(\n origin_linear_layer, aux_linear_layer\n )\n _set_attr_by_name(target_module, layer_name, reparam_layer)\n\n\ndef reparameterize_aux_into_target_model(\n target_model,\n aux_model,\n layer_names=(\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"),\n main_body_name=\"blocks\",\n):\n \"\"\"","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main.change_original_linear_to_reparam","uri":"program://M2PT/function/m2pt.main.change_original_linear_to_reparam#L135-L143","kind":"function","name":"change_original_linear_to_reparam","path":"m2pt/main.py","language":"python","start_line":135,"end_line":143,"context_start_line":115,"context_end_line":163,"code":" aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n\ndef _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name\n):\n origin_linear_layer = _get_attr_by_name(target_module, layer_name)\n aux_linear_layer = _get_attr_by_name(aux_module, layer_name)\n reparam_layer = build_cross_modal_reparam_linear(\n origin_linear_layer, aux_linear_layer\n )\n _set_attr_by_name(target_module, layer_name, reparam_layer)\n\n\ndef reparameterize_aux_into_target_model(\n target_model,\n aux_model,\n layer_names=(\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"),\n main_body_name=\"blocks\",\n):\n \"\"\"\n Reparameterizes the auxiliary model into the target model by replacing specific layers with corresponding layers from the auxiliary model.\n\n Args:\n target_model (object): The target model to reparameterize.\n aux_model (object): The auxiliary model containing the replacement layers.\n layer_names (tuple, optional): The names of the layers to be replaced. Defaults to (\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\").\n main_body_name (str, optional): The name of the main body of the models. Defaults to \"blocks\".\n \"\"\"\n target_transformer_blocks = _get_attr_by_name(\n target_model, main_body_name\n )","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main.reparameterize_aux_into_target_model","uri":"program://M2PT/function/m2pt.main.reparameterize_aux_into_target_model#L146-L173","kind":"function","name":"reparameterize_aux_into_target_model","path":"m2pt/main.py","language":"python","start_line":146,"end_line":173,"context_start_line":126,"context_end_line":193,"code":"def _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name\n):\n origin_linear_layer = _get_attr_by_name(target_module, layer_name)\n aux_linear_layer = _get_attr_by_name(aux_module, layer_name)\n reparam_layer = build_cross_modal_reparam_linear(\n origin_linear_layer, aux_linear_layer\n )\n _set_attr_by_name(target_module, layer_name, reparam_layer)\n\n\ndef reparameterize_aux_into_target_model(\n target_model,\n aux_model,\n layer_names=(\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"),\n main_body_name=\"blocks\",\n):\n \"\"\"\n Reparameterizes the auxiliary model into the target model by replacing specific layers with corresponding layers from the auxiliary model.\n\n Args:\n target_model (object): The target model to reparameterize.\n aux_model (object): The auxiliary model containing the replacement layers.\n layer_names (tuple, optional): The names of the layers to be replaced. Defaults to (\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\").\n main_body_name (str, optional): The name of the main body of the models. Defaults to \"blocks\".\n \"\"\"\n target_transformer_blocks = _get_attr_by_name(\n target_model, main_body_name\n )\n aux_transformer_blocks = _get_attr_by_name(\n aux_model, main_body_name\n )\n for target_block, aux_block in zip(\n target_transformer_blocks, aux_transformer_blocks\n ):\n for layer_name in layer_names:\n change_original_linear_to_reparam(\n target_block, aux_block, layer_name\n )\n\n\nclass CrossModalReParametrization(nn.Module):\n \"\"\"\n A module for cross-modal reparametrization.\n\n Args:\n original_linear (nn.Linear): The original linear layer.\n auxiliary_linear (nn.Linear): The auxiliary linear layer.\n\n Attributes:\n cross_modal_scale (nn.Parameter): The scale parameter for cross-modal reparametrization.\n\n Methods:\n forward(x: Tensor) -> Tensor: Performs forward pass through the module.\n merge(): Merges the weights and biases of the original and auxiliary linear layers.\n \"\"\"\n\n def __init__(\n self,","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main.CrossModalReParametrization","uri":"program://M2PT/class/m2pt.main.CrossModalReParametrization#L176-L224","kind":"class","name":"CrossModalReParametrization","path":"m2pt/main.py","language":"python","start_line":176,"end_line":224,"context_start_line":156,"context_end_line":244,"code":" target_model (object): The target model to reparameterize.\n aux_model (object): The auxiliary model containing the replacement layers.\n layer_names (tuple, optional): The names of the layers to be replaced. Defaults to (\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\").\n main_body_name (str, optional): The name of the main body of the models. Defaults to \"blocks\".\n \"\"\"\n target_transformer_blocks = _get_attr_by_name(\n target_model, main_body_name\n )\n aux_transformer_blocks = _get_attr_by_name(\n aux_model, main_body_name\n )\n for target_block, aux_block in zip(\n target_transformer_blocks, aux_transformer_blocks\n ):\n for layer_name in layer_names:\n change_original_linear_to_reparam(\n target_block, aux_block, layer_name\n )\n\n\nclass CrossModalReParametrization(nn.Module):\n \"\"\"\n A module for cross-modal reparametrization.\n\n Args:\n original_linear (nn.Linear): The original linear layer.\n auxiliary_linear (nn.Linear): The auxiliary linear layer.\n\n Attributes:\n cross_modal_scale (nn.Parameter): The scale parameter for cross-modal reparametrization.\n\n Methods:\n forward(x: Tensor) -> Tensor: Performs forward pass through the module.\n merge(): Merges the weights and biases of the original and auxiliary linear layers.\n \"\"\"\n\n def __init__(\n self,\n original_linear: nn.Linear,\n auxiliary_linear: nn.Linear,\n linears: List[nn.Linear] = None,\n ):\n super().__init__()\n self.original_linear = original_linear\n self.auxiliary_linear = auxiliary_linear\n self.cross_modal_scale = nn.Parameter(torch.zeros(1))\n\n def forward(self, x: Tensor) -> Tensor:\n combined_weight = (\n self.original_linear.weight\n + self.cross_modal_scale * self.auxiliary_linear.weight\n )\n return nn.functional.linear(\n x, combined_weight, self.original_linear.bias\n )\n\n def merge(self):\n self.original_linear.weight.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.weight.data\n )\n if (\n self.original_linear.bias is not None\n and self.auxiliary_linear.bias is not None\n ):\n self.original_linear.bias.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.bias.data\n )\n\n\nclass MPTransformerBlock(nn.Module):\n \"\"\"\n Multi-Modal Transformer Block.\n\n Args:\n dim (int): Dimension of the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n original_linear (nn.Linear): Linear layer for the original modality.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n dim_head: int,\n heads: int,","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main.MPTransformerBlock","uri":"program://M2PT/class/m2pt.main.MPTransformerBlock#L227-L346","kind":"class","name":"MPTransformerBlock","path":"m2pt/main.py","language":"python","start_line":227,"end_line":346,"context_start_line":207,"context_end_line":366,"code":" )\n return nn.functional.linear(\n x, combined_weight, self.original_linear.bias\n )\n\n def merge(self):\n self.original_linear.weight.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.weight.data\n )\n if (\n self.original_linear.bias is not None\n and self.auxiliary_linear.bias is not None\n ):\n self.original_linear.bias.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.bias.data\n )\n\n\nclass MPTransformerBlock(nn.Module):\n \"\"\"\n Multi-Modal Transformer Block.\n\n Args:\n dim (int): Dimension of the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n original_linear (nn.Linear): Linear layer for the original modality.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n dim_head: int,\n heads: int,\n dropout: float,\n ff_mult: int,\n original_linear: nn.Linear,\n auxiliar_linear: nn.Linear,\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n ):\n super().__init__()\n self.dim = dim\n self.dim_head = dim_head\n self.heads = heads\n self.dropout = dropout\n self.ff_mult = ff_mult\n self.original_linear = original_linear\n self.auxiliar_linear = auxiliar_linear\n self.ffn_auxiliar_linear = ffn_auxiliar_linear\n self.ffn_original_last_linear = ffn_original_last_linear\n self.ffn_aux_last_linear = ffn_aux_last_linear\n\n self.ffn_1st_rep_linear = CrossModalReParametrization(\n ffn_original_linear(dim, dim * ff_mult),\n self.ffn_auxiliar_linear(dim, dim * ff_mult),\n )\n\n self.ffn_2nd_linear = CrossModalReParametrization(\n ffn_original_last_linear(dim * ff_mult, dim),\n ffn_aux_last_linear(dim * ff_mult, dim),\n )\n\n self.ffn = nn.Sequential(\n self.ffn_1st_rep_linear,\n nn.GELU(),\n nn.Dropout(),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n self.ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n # Cross modal reparametrization\n self.reparametrization = CrossModalReParametrization(\n self.original_linear, self.auxiliar_linear\n )\n\n # Norm\n self.norm = nn.LayerNorm(self.dim)\n\n # Check for gpu\n self.is_cuda = torch.cuda.is_available()\n\n # Flash Attention\n self.mha = MultiheadAttention(\n dim,\n heads,\n dropout,\n subln=True,\n )\n\n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the Multi-Modal Transformer Block.\n\n Args:\n x (Tensor): Input tensor.\n\n Returns:\n Tensor: Output tensor.\n \"\"\"\n skip = x\n x = self.norm(x)\n\n # Cross Modal Reparametrization with the q, k, v\n q, k, v = (\n self.reparametrization(x),\n self.reparametrization(x),\n self.reparametrization(x),\n )\n print(f\"All shapes: {q.shape}, {k.shape}, {v.shape}\")\n\n # Attention\n attn = self.mha(q, k, v)\n\n # After attention projections\n attn_out = self.reparametrization(attn) + skip\n\n # Norm\n attn_out_norm = self.norm(attn_out)\n\n # Reparameterization again\n norm_then_reparam = self.reparametrization(attn_out_norm)\n\n # Reparameterization again\n reparam_them_reparam = self.reparametrization(\n norm_then_reparam\n )\n\n # FFN\n ffn = self.ffn(reparam_them_reparam)\n\n return self.norm(ffn)\n\n # return reparam_them_reparam + attn_out_norm\n\n\n\nclass M2PT(nn.Module):\n \"\"\"\n M2PT (Multi-Perspective Transformer) model.\n\n Args:\n dim (int): Dimension of the model.\n depth (int): Number of transformer blocks.\n num_tokens (int): Number of tokens in the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n ff_mult (int): Multiplier for the feed-forward network dimension.\n original_linear (nn.Linear): Linear layer for the original input.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary input.\n ffn_original_linear (nn.Linear): Linear layer for the original input in the feed-forward network.","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main.M2PT","uri":"program://M2PT/class/m2pt.main.M2PT#L352-L450","kind":"class","name":"M2PT","path":"m2pt/main.py","language":"python","start_line":352,"end_line":450,"context_start_line":332,"context_end_line":450,"code":" # Norm\n attn_out_norm = self.norm(attn_out)\n\n # Reparameterization again\n norm_then_reparam = self.reparametrization(attn_out_norm)\n\n # Reparameterization again\n reparam_them_reparam = self.reparametrization(\n norm_then_reparam\n )\n\n # FFN\n ffn = self.ffn(reparam_them_reparam)\n\n return self.norm(ffn)\n\n # return reparam_them_reparam + attn_out_norm\n\n\n\nclass M2PT(nn.Module):\n \"\"\"\n M2PT (Multi-Perspective Transformer) model.\n\n Args:\n dim (int): Dimension of the model.\n depth (int): Number of transformer blocks.\n num_tokens (int): Number of tokens in the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n ff_mult (int): Multiplier for the feed-forward network dimension.\n original_linear (nn.Linear): Linear layer for the original input.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary input.\n ffn_original_linear (nn.Linear): Linear layer for the original input in the feed-forward network.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary input in the feed-forward network.\n ffn_original_last_linear (nn.Linear): Last linear layer for the original input in the feed-forward network.\n ffn_aux_last_linear (nn.Linear): Last linear layer for the auxiliary input in the feed-forward network.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n depth: int,\n num_tokens: int,\n dim_head: int,\n heads: int,\n dropout: float,\n ff_mult: int,\n original_linear: nn.Linear,\n auxiliar_linear: nn.Linear,\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n ):\n super().__init__()\n self.dim = dim\n self.depth = depth\n self.num_tokens = num_tokens\n self.dim_head = dim_head\n self.heads = heads\n self.dropout = dropout\n self.ff_mult = ff_mult\n self.original_linear = original_linear\n self.auxiliar_linear = auxiliar_linear\n self.ffn_original_linear = ffn_original_linear\n self.ffn_auxiliar_linear = ffn_auxiliar_linear\n self.ffn_original_last_linear = ffn_original_last_linear\n self.ffn_aux_last_linear = ffn_aux_last_linear\n \n self.layers = nn.ModuleList([])\n \n for _ in range(depth):\n self.layers.append(\n MPTransformerBlock(\n dim=dim,\n dim_head=dim_head,\n heads=heads,\n dropout=dropout,\n ff_mult=ff_mult,\n original_linear=original_linear,\n auxiliar_linear=auxiliar_linear,\n ffn_original_linear=ffn_original_linear,\n ffn_auxiliar_linear=ffn_auxiliar_linear,\n ffn_original_last_linear=ffn_original_last_linear,\n ffn_aux_last_linear=ffn_aux_last_linear,\n )\n )\n \n self.norm = nn.LayerNorm(dim)\n \n self.embedding = nn.Embedding(num_tokens, dim)\n \n self.to_out = nn.Sequential(\n nn.Linear(dim, num_tokens),\n nn.Softmax(dim=-1),\n # nn.LayerNorm(dim)\n )\n \n \n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the M2PT model.\n\n Args:\n x (Tensor): Input tensor of shape (batch_size, sequence_length).\n\n Returns:\n Tensor: Output tensor of shape (batch_size, sequence_length, num_tokens).\n \"\"\"\n x = self.embedding(x)\n \n for layer in self.layers:\n x = layer(x) + x\n \n x = self.to_out(x)\n \n return self.norm(x)","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main.__init__","uri":"program://M2PT/function/m2pt.main.__init__#L372-L430","kind":"function","name":"__init__","path":"m2pt/main.py","language":"python","start_line":372,"end_line":430,"context_start_line":352,"context_end_line":450,"code":"class M2PT(nn.Module):\n \"\"\"\n M2PT (Multi-Perspective Transformer) model.\n\n Args:\n dim (int): Dimension of the model.\n depth (int): Number of transformer blocks.\n num_tokens (int): Number of tokens in the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n ff_mult (int): Multiplier for the feed-forward network dimension.\n original_linear (nn.Linear): Linear layer for the original input.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary input.\n ffn_original_linear (nn.Linear): Linear layer for the original input in the feed-forward network.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary input in the feed-forward network.\n ffn_original_last_linear (nn.Linear): Last linear layer for the original input in the feed-forward network.\n ffn_aux_last_linear (nn.Linear): Last linear layer for the auxiliary input in the feed-forward network.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n depth: int,\n num_tokens: int,\n dim_head: int,\n heads: int,\n dropout: float,\n ff_mult: int,\n original_linear: nn.Linear,\n auxiliar_linear: nn.Linear,\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n ):\n super().__init__()\n self.dim = dim\n self.depth = depth\n self.num_tokens = num_tokens\n self.dim_head = dim_head\n self.heads = heads\n self.dropout = dropout\n self.ff_mult = ff_mult\n self.original_linear = original_linear\n self.auxiliar_linear = auxiliar_linear\n self.ffn_original_linear = ffn_original_linear\n self.ffn_auxiliar_linear = ffn_auxiliar_linear\n self.ffn_original_last_linear = ffn_original_last_linear\n self.ffn_aux_last_linear = ffn_aux_last_linear\n \n self.layers = nn.ModuleList([])\n \n for _ in range(depth):\n self.layers.append(\n MPTransformerBlock(\n dim=dim,\n dim_head=dim_head,\n heads=heads,\n dropout=dropout,\n ff_mult=ff_mult,\n original_linear=original_linear,\n auxiliar_linear=auxiliar_linear,\n ffn_original_linear=ffn_original_linear,\n ffn_auxiliar_linear=ffn_auxiliar_linear,\n ffn_original_last_linear=ffn_original_last_linear,\n ffn_aux_last_linear=ffn_aux_last_linear,\n )\n )\n \n self.norm = nn.LayerNorm(dim)\n \n self.embedding = nn.Embedding(num_tokens, dim)\n \n self.to_out = nn.Sequential(\n nn.Linear(dim, num_tokens),\n nn.Softmax(dim=-1),\n # nn.LayerNorm(dim)\n )\n \n \n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the M2PT model.\n\n Args:\n x (Tensor): Input tensor of shape (batch_size, sequence_length).\n\n Returns:\n Tensor: Output tensor of shape (batch_size, sequence_length, num_tokens).\n \"\"\"\n x = self.embedding(x)\n \n for layer in self.layers:\n x = layer(x) + x\n \n x = self.to_out(x)\n \n return self.norm(x)","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main.forward","uri":"program://M2PT/function/m2pt.main.forward#L433-L450","kind":"function","name":"forward","path":"m2pt/main.py","language":"python","start_line":433,"end_line":450,"context_start_line":413,"context_end_line":450,"code":" original_linear=original_linear,\n auxiliar_linear=auxiliar_linear,\n ffn_original_linear=ffn_original_linear,\n ffn_auxiliar_linear=ffn_auxiliar_linear,\n ffn_original_last_linear=ffn_original_last_linear,\n ffn_aux_last_linear=ffn_aux_last_linear,\n )\n )\n \n self.norm = nn.LayerNorm(dim)\n \n self.embedding = nn.Embedding(num_tokens, dim)\n \n self.to_out = nn.Sequential(\n nn.Linear(dim, num_tokens),\n nn.Softmax(dim=-1),\n # nn.LayerNorm(dim)\n )\n \n \n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the M2PT model.\n\n Args:\n x (Tensor): Input tensor of shape (batch_size, sequence_length).\n\n Returns:\n Tensor: Output tensor of shape (batch_size, sequence_length, num_tokens).\n \"\"\"\n x = self.embedding(x)\n \n for layer in self.layers:\n x = layer(x) + x\n \n x = self.to_out(x)\n \n return self.norm(x)","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"py:m2pt.main.merge","uri":"program://M2PT/function/m2pt.main.merge#L212-L224","kind":"function","name":"merge","path":"m2pt/main.py","language":"python","start_line":212,"end_line":224,"context_start_line":192,"context_end_line":244,"code":" def __init__(\n self,\n original_linear: nn.Linear,\n auxiliary_linear: nn.Linear,\n linears: List[nn.Linear] = None,\n ):\n super().__init__()\n self.original_linear = original_linear\n self.auxiliary_linear = auxiliary_linear\n self.cross_modal_scale = nn.Parameter(torch.zeros(1))\n\n def forward(self, x: Tensor) -> Tensor:\n combined_weight = (\n self.original_linear.weight\n + self.cross_modal_scale * self.auxiliary_linear.weight\n )\n return nn.functional.linear(\n x, combined_weight, self.original_linear.bias\n )\n\n def merge(self):\n self.original_linear.weight.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.weight.data\n )\n if (\n self.original_linear.bias is not None\n and self.auxiliary_linear.bias is not None\n ):\n self.original_linear.bias.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.bias.data\n )\n\n\nclass MPTransformerBlock(nn.Module):\n \"\"\"\n Multi-Modal Transformer Block.\n\n Args:\n dim (int): Dimension of the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n original_linear (nn.Linear): Linear layer for the original modality.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n dim_head: int,\n heads: int,","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"file:model_example.py","uri":"program://M2PT/file/model_example.py","kind":"file","name":"model_example.py","path":"model_example.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nfrom torch import nn\nfrom m2pt.main import M2PT\n\n# Create an instance of the MPTransformerBlock class with the specified parameters\nmodel = M2PT(\n dim=512, # Dimension of the input and output tensors\n num_tokens=10000,\n depth=6,\n dim_head=64, # Dimension of each attention head\n heads=8, # Number of attention heads\n dropout=0.1, # Dropout rate\n ff_mult=4, # Multiplier for the dimension of the feed-forward network\n original_linear=nn.Linear(512, 512), # Linear layer for the original input tensor\n auxiliar_linear=nn.Linear(512, 512), # Linear layer for the auxiliary input tensor\n ffn_original_linear=nn.Linear, # Linear layer for the original input tensor in the feed-forward network\n ffn_auxiliar_linear=nn.Linear, # Linear layer for the auxiliary input tensor in the feed-forward network\n ffn_original_last_linear=nn.Linear, # Last linear layer for the original input tensor in the feed-forward network\n ffn_aux_last_linear=nn.Linear, # Last linear layer for the auxiliary input tensor in the feed-forward network\n)\n","source_hash":"d24a5209a920e60f35f2a1c3e4a14ff7b796d1b3698ef04d0b072e913a127412","truncated":false} |
| {"repo_id":"M2PT","entity_id":"file:example.py","uri":"program://M2PT/file/example.py","kind":"file","name":"example.py","path":"example.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nfrom torch import nn\nfrom m2pt import MPTransformerBlock\n\n# Create an instance of the MPTransformerBlock class with the specified parameters\nmodel = MPTransformerBlock(\n dim=512, # Dimension of the input and output tensors\n dim_head=64, # Dimension of each attention head\n heads=8, # Number of attention heads\n dropout=0.1, # Dropout rate\n ff_mult=4, # Multiplier for the dimension of the feed-forward network\n original_linear=nn.Linear(512, 512), # Linear layer for the original input tensor\n auxiliar_linear=nn.Linear(512, 512), # Linear layer for the auxiliary input tensor\n ffn_original_linear=nn.Linear, # Linear layer for the original input tensor in the feed-forward network\n ffn_auxiliar_linear=nn.Linear, # Linear layer for the auxiliary input tensor in the feed-forward network\n ffn_original_last_linear=nn.Linear, # Last linear layer for the original input tensor in the feed-forward network\n ffn_aux_last_linear=nn.Linear, # Last linear layer for the auxiliary input tensor in the feed-forward network\n)\n\n# Create a 3D tensor with shape B x S x D\nx = torch.randn(1, 512, 512)","source_hash":"400c144f38a8cc5a7dd896fdda7b083f58ddd38248e9b9a78a0fa99c65a806a4","truncated":false} |
| {"repo_id":"M2PT","entity_id":"file:m2pt/main.py","uri":"program://M2PT/file/m2pt/main.py","kind":"file","name":"m2pt/main.py","path":"m2pt/main.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nfrom torch import nn, Tensor\nfrom zeta.nn.attention.multihead_attention import MultiheadAttention\nfrom typing import List\nimport torch.nn.functional as F\n\n\nclass CrossModalReparamLinear(nn.Linear):\n \"\"\"\n Linear layer with cross-modal reparameterization.\n\n Args:\n in_features (int): Size of each input sample.\n out_features (int): Size of each output sample.\n bias (bool, optional): If set to False, the layer will not learn an additive bias. Default is True.\n origin_layer (nn.Linear, optional): Original linear layer to initialize the weight and bias from. Default is None.\n aux_weight (torch.Tensor, optional): Auxiliary weight tensor. Default is None.\n is_aux_trainable (bool, optional): If set to False, the auxiliary weight will not be trainable. Default is True.\n \"\"\"\n\n def __init__(","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false} |
| {"repo_id":"M2PT","entity_id":"file:m2pt/__init__.py","uri":"program://M2PT/file/m2pt/__init__.py","kind":"file","name":"m2pt/__init__.py","path":"m2pt/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":16,"code":"from m2pt.main import (\n CrossModalReparamLinear,\n cross_modal_ffn,\n reparameterize_aux_into_target_model,\n CrossModalReParametrization,\n MPTransformerBlock,\n)\n\n\n__all__ = [\n \"CrossModalReparamLinear\",\n \"cross_modal_ffn\",\n \"reparameterize_aux_into_target_model\",\n \"CrossModalReParametrization\",\n \"MPTransformerBlock\",\n]","source_hash":"649706ded706fbf75470f96549eb6bd23ff887ab6e879e9e1fc2473833252159","truncated":false} |
|
|