报错:Traceback (most recent call last):
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 114, in
main()
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 105, in main
run_training(args.script, args.config, cudnn_benchmark=args.cudnn_benchmark,
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 75, in run_training
expr_func(settings)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/train_script.py", line 56, in run
net = build_mamba_fetrack(cfg)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 117, in build_mamba_fetrack
backbone = create_model( model_name= cfg.MODEL.BACKBONE.TYPE, pretrained= pretrained, num_classes=1000,
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/timm/models/factory.py", line 81, in create_model
model = create_fn(pretrained=pretrained, **kwargs)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 644, in vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2
model = VisionMamba(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 383, in init
[
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 384, in
create_block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 222, in create_block
block = Block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 89, in init
self.mixer = mixer_cls()
TypeError: FocusedLinearAttention.init() got an unexpected keyword argument 'device'
[2024-10-14 11:45:02,646] torch.distributed.elastic.multiprocessing.api: [ERROR] failed (exitcode: 1) local_rank: 0 (pid: 3693284) of binary: /home/heyuting/anaconda3/envs/mamba_fetrack/bin/python
Traceback (most recent call last):
File "/home/heyuting/anaconda3/envs/mamba_fetrack/bin/torchrun", line 8, in
sys.exit(main())
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/distributed/elastic/multiprocessing/errors/init.py", line 346, in wrapper
return f(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/distributed/run.py", line 806, in main
run(args)
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/distributed/run.py", line 797, in run
elastic_launch(
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/distributed/launcher/api.py", line 134, in call
return launch_agent(self._config, self._entrypoint, list(args))
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/distributed/launcher/api.py", line 264, in launch_agent
raise ChildFailedError(
torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
The error you're encountering is due to a TypeError that indicates the FocusedLinearAttention.__init__() method is being called with an unexpected keyword argument 'device'. It seems that the FocusedLinearAttention class's constructor does not accept a 'device' parameter, or the parameter is being passed incorrectly.
Here's a step-by-step approach to troubleshoot and resolve this issue:
Check FocusedLinearAttention Definition:
Go to the implementation of the FocusedLinearAttention class. Ensure that its __init__ method is defined to accept all parameters being passed to it. Look for a 'device' parameter under its constructor definition. If it's not there, you might need to add it or remove the argument from the call if it's unnecessary.
Correct the Argument:
If the 'device' parameter is needed and should be part of the class, modify the __init__ method in the FocusedLinearAttention class to include it. If the device is not supposed to be an argument for this class, find where this class is being instantiated (models_mamba.py, line 89), and correct the call to omit the 'device' argument.
Find where FocusedLinearAttention is being Instantiated:
The traceback shows that the error occurs in models_mamba.py at line 89, within the instantiation of FocusedLinearAttention. Check the specific call to this class and inspect how parameters are being passed. Adjust according to the constructor of FocusedLinearAttention.
Review Changes in External Libraries:
If FocusedLinearAttention is part of an external library (not your code), it could be that its interface has changed in a recent update. In such cases, check the release notes or documentation for the library to understand how you should now interact with this class.
Review Dependencies:
Ensure that all your dependencies are properly installed and compatible, especially if you've updated any packages in your environment. You can run pip list or check your environment manager to verify this.
Version Control:
If this error started occurring after a recent change, and you use version control (e.g., Git), reviewing the change history could offer some insights. Look for recent modifications related to FocusedLinearAttention or related model setups.
Error Handling in Distributed Setup:
Since you're using a distributed setup (), ensure that all nodes are running the same code with the necessary environment configuration. Distributed setups require that each process is run with the same version of code and dependencies to function correctly.
那么在import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal, lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.mamba_fetrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
from .HinBlock import HinResBlock
from .ResGLU import ResGLUAdapter, ModelArgs
from .vit import Attention, FocusedLinearAttention
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0., integrate_glu=False
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
当前在import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal, lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.mamba_fetrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
from .HinBlock import HinResBlock
from .ResGLU import ResGLUAdapter, ModelArgs
from .vit import Attention, FocusedLinearAttention
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0., integrate_glu=False
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
报错:/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/conv.py:456: UserWarning: Applied workaround for CuDNN issue, install nvrtc.so (Triggered internally at ../aten/src/ATen/native/cudnn/Conv_v8.cpp:80.)
return F.conv2d(input, weight, bias, self.stride,
Training crashed at epoch 1
Traceback for the error!
Traceback (most recent call last):
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/trainers/base_trainer.py", line 85, in train
self.train_epoch()
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/trainers/ltr_trainer.py", line 133, in train_epoch
self.cycle_dataset(loader)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/trainers/ltr_trainer.py", line 86, in cycle_dataset
loss, stats = self.actor(data)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/actors/mamba_fetrack.py", line 31, in call
out_dict = self.forward_pass(data)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/actors/mamba_fetrack.py", line 74, in forward_pass
out_dict = self.net(template=template_list,
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 52, in forward
rgb_feature = self.backbone.forward_features( z=template, x=search,
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 513, in forward_features
hidden_states, residual = layer(
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 149, in forward
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
TypeError: Attention.forward() got an unexpected keyword argument 'inference_params'
Restarting training from last epoch ...
Finished training!
在import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal, lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.mamba_fetrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
from .HinBlock import HinResBlock
from .ResGLU import ResGLUAdapter, ModelArgs
from .vit import Attention, FocusedLinearAttention
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0., integrate_glu=False
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal, lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.mamba_fetrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
from .HinBlock import HinResBlock
from .ResGLU import ResGLUAdapter, ModelArgs
from .vit import Attention, FocusedLinearAttention
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0., integrate_glu=False
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
报错:Traceback (most recent call last):
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 110, in
main()
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 101, in main
run_training(args.script, args.config, cudnn_benchmark=args.cudnn_benchmark,
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 75, in run_training
expr_func(settings)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/train_script.py", line 56, in run
net = build_mamba_fetrack(cfg)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 117, in build_mamba_fetrack
backbone = create_model( model_name= cfg.MODEL.BACKBONE.TYPE, pretrained= pretrained, num_classes=1000,
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/timm/models/factory.py", line 81, in create_model
model = create_fn(pretrained=pretrained, **kwargs)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 617, in vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2
model = VisionMamba(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 356, in init
[
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 357, in
create_block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 195, in create_block
block = Block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 89, in init
self.mixer = mixer_cls(dim)
TypeError: FocusedLinearAttention.init() got an unexpected keyword argument 'dtype'
Traceback for the error!
Traceback (most recent call last):
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/trainers/base_trainer.py", line 85, in train
self.train_epoch()
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/trainers/ltr_trainer.py", line 133, in train_epoch
self.cycle_dataset(loader)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/trainers/ltr_trainer.py", line 86, in cycle_dataset
loss, stats = self.actor(data)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/actors/mamba_fetrack.py", line 31, in call
out_dict = self.forward_pass(data)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/actors/mamba_fetrack.py", line 74, in forward_pass
out_dict = self.net(template=template_list,
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 52, in forward
rgb_feature = self.backbone.forward_features( z=template, x=search,
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 516, in forward_features
hidden_states, residual = layer(
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 149, in forward
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
TypeError: FocusedLinearAttention.forward() missing 2 required positional arguments: 'H' and 'W'
Restarting training from last epoch ...
Finished training!
只要确保 FocusedLinearAttention.forward() 在调用时能预期地接收到 H 和 W,就能解决这个错误。同时回顾代码逻辑的传递路径,确认每一个步骤都正确盛传了所需的形态维度参数。
User
直接改成 def forward(self, x, inference_params=None):
H = 16
W = 20可以吗
Assistant
您可以直接在 FocusedLinearAttention 的 forward 方法中设置 H 和 W 的默认值,例如 H=16 和 W=20。这样可以避免在每次调用该方法时都需要明确传递这两个参数。然而,这需要确保这两个硬编码的值在所有场景下都是适用的。
这种方法适用于以下情况:
您的模型在所有数据输入中这些维度始终不变。
你在训练和推理中都保持这些固定的维度不变。
修改示例
在 FocusedLinearAttention 类中,将 forward 方法修改为:
python
class FocusedLinearAttention(nn.Module):
...
def forward(self, x, inference_params=None):
# 如果输入图像的空间维度始终是 16x20,你可以写死这两个值
H = 16
W = 20
B, N, C = x.shape
q = self.q(x)
if self.sr_ratio > 1:
x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
x_ = self.norm(x_)
kv = self.kv(x_).reshape(B, -1, 2, C).permute(2, 0, 1, 3)
else:
kv = self.kv(x).reshape(B, -1, 2, C).permute(2, 0, 1, 3)
k, v = kv[0], kv[1]
n = k.shape[1]
k = k + self.positional_encoding
focusing_factor = self.focusing_factor
kernel_function = nn.ReLU()
scale = nn.Softplus()(self.scale)
q = kernel_function(q) + 1e-6
k = kernel_function(k) + 1e-6
q = q / scale
k = k / scale
q_norm = q.norm(dim=-1, keepdim=True)
k_norm = k.norm(dim=-1, keepdim=True)
q = q ** focusing_factor
k = k ** focusing_factor
q = (q / q.norm(dim=-1, keepdim=True)) * q_norm
k = (k / k.norm(dim=-1, keepdim=True)) * k_norm
q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
k = k.reshape(B, n, self.num_heads, -1).permute(0, 2, 1, 3)
v = v.reshape(B, n, self.num_heads, -1).permute(0, 2, 1, 3)
z = 1 / (q @ k.mean(dim=-2, keepdim=True).transpose(-2, -1) + 1e-6)
kv = (k.transpose(-2, -1) * (n ** -0.5)) @ (v * (n ** -0.5))
x = q @ kv * z
if self.sr_ratio > 1:
v = nn.functional.interpolate(v.transpose(-2, -1).reshape(B * self.num_heads, -1, n), size=N, mode='linear').reshape(B, self.num_heads, -1, N).transpose(-2, -1)
x = x.transpose(1, 2).reshape(B, N, C)
v = v.reshape(B * self.num_heads, H, W, -1).permute(0, 3, 1, 2)
x = x + self.dwc(v).reshape(B, C, N).permute(0, 2, 1)
x = self.proj(x)
x = self.proj_drop(x)
return x
请注意的是,这样的硬编码需要谨慎使用。如果有任何情况下数据不满足这些固定的 H 和 W,您需要根据实际情况对 H 和 W 进行动态计算或传递。
User
在import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal, lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.mamba_fetrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
from .HinBlock import HinResBlock
from .ResGLU import ResGLUAdapter, ModelArgs
from .vit import Attention, FocusedLinearAttention
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0., integrate_glu=False
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
After addressing these points, re-run the training script to verify if the issue has been resolved. If you've made changes to an external library, you may need to adapt your code to handle FocusedLinearAttention differently based on updates or changes in that library's API.
code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls()
# self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
# 引入门控机制
model_args = ModelArgs()
# self.glu_adapter = GLUAdapter(model_args)
# 如果需要集成 ResGLUAdapter,则初始化
if integrate_glu:
model_args = ModelArgs()
self.glu_adapter = ResGLUAdapter(model_args)
else:
self.glu_adapter = None
# self.glu_adapter = ResGLUAdapter(model_args)
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
# 增加门控机制, 消除冗余和不相关的特征,保留最具表现力的输出
if self.glu_adapter is not None:
hidden_states = self.glu_adapter(hidden_states)
# hidden_states = self.glu_adapter(hidden_states)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal(module.weight, std=initializer_range)
code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
和 class FocusedLinearAttention(nn.Module):
def init(self, dim, num_patches, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1,
focusing_factor=3, kernel_size=5):
super().init()
assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
code
self.dim = dim
self.num_heads = num_heads
head_dim = dim // num_heads
self.q = nn.Linear(dim, dim, bias=qkv_bias)
self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
self.sr_ratio = sr_ratio
if sr_ratio > 1:
self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
self.norm = nn.LayerNorm(dim)
self.focusing_factor = focusing_factor
self.dwc = nn.Conv2d(in_channels=head_dim, out_channels=head_dim, kernel_size=kernel_size,
groups=head_dim, padding=kernel_size // 2)
self.scale = nn.Parameter(torch.zeros(size=(1, 1, dim)))
self.positional_encoding = nn.Parameter(torch.zeros(size=(1, num_patches // (sr_ratio * sr_ratio), dim)))
print('Linear Attention sr_ratio{} f{} kernel{}'.
format(sr_ratio, focusing_factor, kernel_size))
def forward(self, x, H, W):
H = 16
W = 20
B, N, C = x.shape
q = self.q(x)
if self.sr_ratio > 1:
x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
x_ = self.norm(x_)
kv = self.kv(x_).reshape(B, -1, 2, C).permute(2, 0, 1, 3)
else:
kv = self.kv(x).reshape(B, -1, 2, C).permute(2, 0, 1, 3)
k, v = kv[0], kv[1]
n = k.shape[1]
k = k + self.positional_encoding
focusing_factor = self.focusing_factor
kernel_function = nn.ReLU()
scale = nn.Softplus()(self.scale)
q = kernel_function(q) + 1e-6
k = kernel_function(k) + 1e-6
q = q / scale
k = k / scale
q_norm = q.norm(dim=-1, keepdim=True)
k_norm = k.norm(dim=-1, keepdim=True)
q = q ** focusing_factor
k = k ** focusing_factor
q = (q / q.norm(dim=-1, keepdim=True)) * q_norm
k = (k / k.norm(dim=-1, keepdim=True)) * k_norm
q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
k = k.reshape(B, n, self.num_heads, -1).permute(0, 2, 1, 3)
v = v.reshape(B, n, self.num_heads, -1).permute(0, 2, 1, 3)
z = 1 / (q @ k.mean(dim=-2, keepdim=True).transpose(-2, -1) + 1e-6)
kv = (k.transpose(-2, -1) * (n ** -0.5)) @ (v * (n ** -0.5))
x = q @ kv * z
if self.sr_ratio > 1:
v = nn.functional.interpolate(v.transpose(-2, -1).reshape(B * self.num_heads, -1, n), size=N, mode='linear').reshape(B, self.num_heads, -1, N).transpose(-2, -1)
x = x.transpose(1, 2).reshape(B, N, C)
v = v.reshape(B * self.num_heads, H, W, -1).permute(0, 3, 1, 2)
x = x + self.dwc(v).reshape(B, C, N).permute(0, 2, 1)
x = self.proj(x)
x = self.proj_drop(x)
return x
中引发报错:Traceback (most recent call last):
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 110, in
main()
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 101, in main
run_training(args.script, args.config, cudnn_benchmark=args.cudnn_benchmark,
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 75, in run_training
expr_func(settings)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/train_script.py", line 56, in run
net = build_mamba_fetrack(cfg)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 117, in build_mamba_fetrack
backbone = create_model( model_name= cfg.MODEL.BACKBONE.TYPE, pretrained= pretrained, num_classes=1000,
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/timm/models/factory.py", line 81, in create_model
model = create_fn(pretrained=pretrained, **kwargs)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 644, in vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2
model = VisionMamba(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 383, in init
[
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 384, in
create_block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 222, in create_block
block = Block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 89, in init
self.mixer = mixer_cls()
TypeError: FocusedLinearAttention.init() got an unexpected keyword argument 'device'
code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
# self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
# 引入门控机制
model_args = ModelArgs()
# self.glu_adapter = GLUAdapter(model_args)
# 如果需要集成 ResGLUAdapter,则初始化
if integrate_glu:
model_args = ModelArgs()
self.glu_adapter = ResGLUAdapter(model_args)
else:
self.glu_adapter = None
# self.glu_adapter = ResGLUAdapter(model_args)
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
# 增加门控机制, 消除冗余和不相关的特征,保留最具表现力的输出
if self.glu_adapter is not None:
hidden_states = self.glu_adapter(hidden_states)
# hidden_states = self.glu_adapter(hidden_states)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal(module.weight, std=initializer_range)
code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
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
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.scale = self.head_dim ** -0.5
self.fused_attn = True
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,
)
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中,报错:Traceback (most recent call last):
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 110, in
main()
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 101, in main
run_training(args.script, args.config, cudnn_benchmark=args.cudnn_benchmark,
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 75, in run_training
expr_func(settings)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/train_script.py", line 56, in run
net = build_mamba_fetrack(cfg)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 117, in build_mamba_fetrack
backbone = create_model( model_name= cfg.MODEL.BACKBONE.TYPE, pretrained= pretrained, num_classes=1000,
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/timm/models/factory.py", line 81, in create_model
model = create_fn(pretrained=pretrained, **kwargs)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 644, in vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2
model = VisionMamba(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 383, in init
[
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 384, in
create_block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 222, in create_block
block = Block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 89, in init
self.mixer = mixer_cls(dim)
TypeError: Attention.init() got an unexpected keyword argument 'device'
code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
# self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
# 引入门控机制
model_args = ModelArgs()
# self.glu_adapter = GLUAdapter(model_args)
# 如果需要集成 ResGLUAdapter,则初始化
if integrate_glu:
model_args = ModelArgs()
self.glu_adapter = ResGLUAdapter(model_args)
else:
self.glu_adapter = None
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
# 增加门控机制, 消除冗余和不相关的特征,保留最具表现力的输出
if self.glu_adapter is not None:
hidden_states = self.glu_adapter(hidden_states)
# hidden_states = self.glu_adapter(hidden_states)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal(module.weight, std=initializer_range)
code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
if pretrained:
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model 和 class FocusedLinearAttention(nn.Module):
def init(self, dim, num_patches, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1,
focusing_factor=3, kernel_size=5,device=None, inference_params=None):
super().init()
assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
device=None, # 添加参数
dtype=None, # 添加参数
self.dim = dim
self.num_heads = num_heads
head_dim = dim // num_heads
code
self.q = nn.Linear(dim, dim, bias=qkv_bias)
self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
self.sr_ratio = sr_ratio
if sr_ratio > 1:
self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
self.norm = nn.LayerNorm(dim)
self.focusing_factor = focusing_factor
self.dwc = nn.Conv2d(in_channels=head_dim, out_channels=head_dim, kernel_size=kernel_size,
groups=head_dim, padding=kernel_size // 2)
self.scale = nn.Parameter(torch.zeros(size=(1, 1, dim)))
self.positional_encoding = nn.Parameter(torch.zeros(size=(1, num_patches // (sr_ratio * sr_ratio), dim)))
print('Linear Attention sr_ratio{} f{} kernel{}'.
format(sr_ratio, focusing_factor, kernel_size))
def forward(self, x, H, W):
H = 16
W = 20
B, N, C = x.shape
q = self.q(x)
if self.sr_ratio > 1:
x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
x_ = self.norm(x_)
kv = self.kv(x_).reshape(B, -1, 2, C).permute(2, 0, 1, 3)
else:
kv = self.kv(x).reshape(B, -1, 2, C).permute(2, 0, 1, 3)
k, v = kv[0], kv[1]
n = k.shape[1]
k = k + self.positional_encoding
focusing_factor = self.focusing_factor
kernel_function = nn.ReLU()
scale = nn.Softplus()(self.scale)
q = kernel_function(q) + 1e-6
k = kernel_function(k) + 1e-6
q = q / scale
k = k / scale
q_norm = q.norm(dim=-1, keepdim=True)
k_norm = k.norm(dim=-1, keepdim=True)
q = q ** focusing_factor
k = k ** focusing_factor
q = (q / q.norm(dim=-1, keepdim=True)) * q_norm
k = (k / k.norm(dim=-1, keepdim=True)) * k_norm
q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
k = k.reshape(B, n, self.num_heads, -1).permute(0, 2, 1, 3)
v = v.reshape(B, n, self.num_heads, -1).permute(0, 2, 1, 3)
z = 1 / (q @ k.mean(dim=-2, keepdim=True).transpose(-2, -1) + 1e-6)
kv = (k.transpose(-2, -1) * (n ** -0.5)) @ (v * (n ** -0.5))
x = q @ kv * z
if self.sr_ratio > 1:
v = nn.functional.interpolate(v.transpose(-2, -1).reshape(B * self.num_heads, -1, n), size=N, mode='linear').reshape(B, self.num_heads, -1, N).transpose(-2, -1)
x = x.transpose(1, 2).reshape(B, N, C)
v = v.reshape(B * self.num_heads, H, W, -1).permute(0, 3, 1, 2)
x = x + self.dwc(v).reshape(B, C, N).permute(0, 2, 1)
x = self.proj(x)
x = self.proj_drop(x)
return x
中报错:Traceback (most recent call last):
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 110, in
main()
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 101, in main
run_training(args.script, args.config, cudnn_benchmark=args.cudnn_benchmark,
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 75, in run_training
expr_func(settings)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/train_script.py", line 56, in run
net = build_mamba_fetrack(cfg)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 117, in build_mamba_fetrack
backbone = create_model( model_name= cfg.MODEL.BACKBONE.TYPE, pretrained= pretrained, num_classes=1000,
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/timm/models/factory.py", line 81, in create_model
model = create_fn(pretrained=pretrained, **kwargs)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 617, in vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2
model = VisionMamba(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 356, in init
[
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 357, in
create_block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 195, in create_block
block = Block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 89, in init
self.mixer = mixer_cls(dim)
TypeError: FocusedLinearAttention.init() got multiple values for argument 'dim'
self.q = nn.Linear(dim, dim, bias=qkv_bias)
self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
self.sr_ratio = sr_ratio
if sr_ratio > 1:
self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
self.norm = nn.LayerNorm(dim)
self.focusing_factor = focusing_factor
self.dwc = nn.Conv2d(in_channels=head_dim, out_channels=head_dim, kernel_size=kernel_size,
groups=head_dim, padding=kernel_size // 2)
self.scale = nn.Parameter(torch.zeros(size=(1, 1, dim)))
self.positional_encoding = nn.Parameter(torch.zeros(size=(1, num_patches // (sr_ratio * sr_ratio), dim)))
print('Linear Attention sr_ratio{} f{} kernel{}'.
format(sr_ratio, focusing_factor, kernel_size))
def forward(self, x, H, W):
H = 16
W = 20
B, N, C = x.shape
q = self.q(x)
if self.sr_ratio > 1:
x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
x_ = self.norm(x_)
kv = self.kv(x_).reshape(B, -1, 2, C).permute(2, 0, 1, 3)
else:
kv = self.kv(x).reshape(B, -1, 2, C).permute(2, 0, 1, 3)
k, v = kv[0], kv[1]
n = k.shape[1]
k = k + self.positional_encoding
focusing_factor = self.focusing_factor
kernel_function = nn.ReLU()
scale = nn.Softplus()(self.scale)
q = kernel_function(q) + 1e-6
k = kernel_function(k) + 1e-6
q = q / scale
k = k / scale
q_norm = q.norm(dim=-1, keepdim=True)
k_norm = k.norm(dim=-1, keepdim=True)
q = q ** focusing_factor
k = k ** focusing_factor
q = (q / q.norm(dim=-1, keepdim=True)) * q_norm
k = (k / k.norm(dim=-1, keepdim=True)) * k_norm
q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
k = k.reshape(B, n, self.num_heads, -1).permute(0, 2, 1, 3)
v = v.reshape(B, n, self.num_heads, -1).permute(0, 2, 1, 3)
z = 1 / (q @ k.mean(dim=-2, keepdim=True).transpose(-2, -1) + 1e-6)
kv = (k.transpose(-2, -1) * (n ** -0.5)) @ (v * (n ** -0.5))
x = q @ kv * z
if self.sr_ratio > 1:
v = nn.functional.interpolate(v.transpose(-2, -1).reshape(B * self.num_heads, -1, n), size=N, mode='linear').reshape(B, self.num_heads, -1, N).transpose(-2, -1)
x = x.transpose(1, 2).reshape(B, N, C)
v = v.reshape(B * self.num_heads, H, W, -1).permute(0, 3, 1, 2)
x = x + self.dwc(v).reshape(B, C, N).permute(0, 2, 1)
x = self.proj(x)
x = self.proj_drop(x)
return x了之后,还是报错:Traceback (most recent call last):
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 110, in
main()
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 101, in main
run_training(args.script, args.config, cudnn_benchmark=args.cudnn_benchmark,
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 75, in run_training
expr_func(settings)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/train_script.py", line 56, in run
net = build_mamba_fetrack(cfg)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 117, in build_mamba_fetrack
backbone = create_model( model_name= cfg.MODEL.BACKBONE.TYPE, pretrained= pretrained, num_classes=1000,
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/timm/models/factory.py", line 81, in create_model
model = create_fn(pretrained=pretrained, **kwargs)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 617, in vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2
model = VisionMamba(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 356, in init
[
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 357, in
create_block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 195, in create_block
block = Block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 89, in init
self.mixer = mixer_cls(dim)
TypeError: FocusedLinearAttention.init() got multiple values for argument 'dim'
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
# self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
# 引入门控机制
model_args = ModelArgs()
# self.glu_adapter = GLUAdapter(model_args)
# 如果需要集成 ResGLUAdapter,则初始化
if integrate_glu:
model_args = ModelArgs()
self.glu_adapter = ResGLUAdapter(model_args)
else:
self.glu_adapter = None
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
# 增加门控机制, 消除冗余和不相关的特征,保留最具表现力的输出
if self.glu_adapter is not None:
hidden_states = self.glu_adapter(hidden_states)
# hidden_states = self.glu_adapter(hidden_states)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal(module.weight, std=initializer_range)
code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
和 class FocusedLinearAttention(nn.Module):
def init(self, dim=None, num_patches=None, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1,
focusing_factor=3, kernel_size=5,device=None, inference_params=None):
super().init()
if dim is None:
raise ValueError("The parameter 'dim' must be provided.")
assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
device=None, # 添加参数
dtype=None, # 添加参数
self.dim = dim
self.num_heads = num_heads
head_dim = dim // num_heads
code
self.q = nn.Linear(dim, dim, bias=qkv_bias)
self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
self.sr_ratio = sr_ratio
if sr_ratio > 1:
self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
self.norm = nn.LayerNorm(dim)
self.focusing_factor = focusing_factor
self.dwc = nn.Conv2d(in_channels=head_dim, out_channels=head_dim, kernel_size=kernel_size,
groups=head_dim, padding=kernel_size // 2)
self.scale = nn.Parameter(torch.zeros(size=(1, 1, dim)))
self.positional_encoding = nn.Parameter(torch.zeros(size=(1, num_patches // (sr_ratio * sr_ratio), dim)))
print('Linear Attention sr_ratio{} f{} kernel{}'.
format(sr_ratio, focusing_factor, kernel_size))
def forward(self, x, H, W):
H = 16
W = 20
B, N, C = x.shape
q = self.q(x)
if self.sr_ratio > 1:
x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
x_ = self.norm(x_)
kv = self.kv(x_).reshape(B, -1, 2, C).permute(2, 0, 1, 3)
else:
kv = self.kv(x).reshape(B, -1, 2, C).permute(2, 0, 1, 3)
k, v = kv[0], kv[1]
n = k.shape[1]
k = k + self.positional_encoding
focusing_factor = self.focusing_factor
kernel_function = nn.ReLU()
scale = nn.Softplus()(self.scale)
q = kernel_function(q) + 1e-6
k = kernel_function(k) + 1e-6
q = q / scale
k = k / scale
q_norm = q.norm(dim=-1, keepdim=True)
k_norm = k.norm(dim=-1, keepdim=True)
q = q ** focusing_factor
k = k ** focusing_factor
q = (q / q.norm(dim=-1, keepdim=True)) * q_norm
k = (k / k.norm(dim=-1, keepdim=True)) * k_norm
q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
k = k.reshape(B, n, self.num_heads, -1).permute(0, 2, 1, 3)
v = v.reshape(B, n, self.num_heads, -1).permute(0, 2, 1, 3)
z = 1 / (q @ k.mean(dim=-2, keepdim=True).transpose(-2, -1) + 1e-6)
kv = (k.transpose(-2, -1) * (n ** -0.5)) @ (v * (n ** -0.5))
x = q @ kv * z
if self.sr_ratio > 1:
v = nn.functional.interpolate(v.transpose(-2, -1).reshape(B * self.num_heads, -1, n), size=N, mode='linear').reshape(B, self.num_heads, -1, N).transpose(-2, -1)
x = x.transpose(1, 2).reshape(B, N, C)
v = v.reshape(B * self.num_heads, H, W, -1).permute(0, 3, 1, 2)
x = x + self.dwc(v).reshape(B, C, N).permute(0, 2, 1)
x = self.proj(x)
x = self.proj_drop(x)
return x中还报错:Traceback (most recent call last):
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 110, in
main()
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 101, in main
run_training(args.script, args.config, cudnn_benchmark=args.cudnn_benchmark,
File "/data/local_userdata/heyuting/MyFETrack/lib/train/run_training.py", line 75, in run_training
expr_func(settings)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/train/train_script.py", line 56, in run
net = build_mamba_fetrack(cfg)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 117, in build_mamba_fetrack
backbone = create_model( model_name= cfg.MODEL.BACKBONE.TYPE, pretrained= pretrained, num_classes=1000,
File "/home/heyuting/anaconda3/envs/mamba_fetrack/lib/python3.10/site-packages/timm/models/factory.py", line 81, in create_model
model = create_fn(pretrained=pretrained, **kwargs)
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 617, in vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2
model = VisionMamba(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 356, in init
[
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 357, in
create_block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 195, in create_block
block = Block(
File "/data/local_userdata/heyuting/MyFETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 89, in init
self.mixer = mixer_cls(dim)
TypeError: FocusedLinearAttention.init() got multiple values for argument 'dim'
class Block(nn.Module):
def __init__(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0., integrate_glu=False
):
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
# 调用时不需要再传递dim,因为它已经在mixer_cls中设置了
self.mixer = mixer_cls()
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
model_args = ModelArgs()
if integrate_glu:
model_args = ModelArgs()
self.glu_adapter = ResGLUAdapter(model_args)
else:
self.glu_adapter = None
通过在partial函数中避免重复设置以及小心管理参数的使用,这应该可以帮你解决 "multiple values for argument" 的问题。确保参数仅在必要的地方进行初始化,并避免在链中重复传递。这个调整适用于防止相同参数重复传递的问题。
code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
# self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
# 引入门控机制
model_args = ModelArgs()
# self.glu_adapter = GLUAdapter(model_args)
# 如果需要集成 ResGLUAdapter,则初始化
if integrate_glu:
model_args = ModelArgs()
self.glu_adapter = ResGLUAdapter(model_args)
else:
self.glu_adapter = None
# self.glu_adapter = ResGLUAdapter(model_args)
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
# 增加门控机制, 消除冗余和不相关的特征,保留最具表现力的输出
if self.glu_adapter is not None:
hidden_states = self.glu_adapter(hidden_states)
# hidden_states = self.glu_adapter(hidden_states)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal(module.weight, std=initializer_range)
code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)