Paddle2.0:浅析并实现 LV-ViT 模型

本文探索提升ViT性能的训练技巧,提出LV-ViT模型。其改进包括增加网络深度、显式引入归纳偏置、改进残差连接、采用Re-labeling和Token Labeling策略及MixToken数据增广等。模型在ImageNet上性能优异,如LV-ViT-L在512分辨率下Top1精度达86.4,超越多种方案。

☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

paddle2.0:浅析并实现 lv-vit 模型 - 创想鸟

引入

本文探索了用于提升 ViT 性能的各种训练技巧通过一系列实验对比、改进与组合,本文所提方案取得了 SOTA 方案超越了 EfficientNet、T2TViT、DeiT、Swin Transformer、CaiT 等方案

相关资料

论文:All Tokens Matter: Token Labeling for Training Better Vision Transformers官方实现:zihangJiang/TokenLabeling

主要改进

本文主要探索了提升 ViT 性能的各种训练技巧对比原版 ViT 模型和 LV-ViT 模型的训练 Pipeline 的总体示意图如下:

Paddle2.0:浅析并实现 LV-ViT 模型 - 创想鸟

Network Depth

众所周知,提升模型的深度有助于改善模型的泛化性能与容量。作者通过逐渐提升基线 ViT 的深度对其如何影响 ViT 的性能进行了研究。由于添加更多的模块不可避免会引入更多的模型参数,作者减少前馈层的隐含层维度(作者发现对模型性能几乎没有负面影响)。

Explicit inductive bias

ViT 旨在通过自注意力进行全局信息集成,并不会像 CNN 一样显式引入归纳偏置。尽管 DeepVit 一文提到:当无显式归纳偏置时,底层模块仍可以隐式学习之。然而,MHSA 计算代价要远高于简单的卷积。正如 T2T-ViT 一文所提到:Patch 嵌入中的 Tokenization 难以捕获低级与局部结构信息,导致了训练过程中的较低的采样效率。考虑到这些问题,作者提出直接添加更多的卷积层增强块嵌入模块的容量以显式引入归纳偏置。此外,为从更大感受野提取信息,作者采用了更小 Stride 的卷积以提供近邻 Token 的重叠信息。

Rethinking residual connection

假设LayerNorm表示为LN,作者重写Transformer模块的计算如下:

对此,作者解释为:通过逐渐添加源自其他 Token 的信息调整输入。

原始的 ViT 采用固定比例 1 添加信息调整,作者提出采用更小比例 αα 重缩放残差特征值:

由于更少的信息经过残差分支,这种方式可以增强残差链接;调整残差分支的缩放因子可以改善模型的泛化性能。

Re-labeling

RandomCrop 是训练阶段最常用的一种数据增光方法。ImageNet 是一种单标签的基准数据集,然而其标签并不总是精确,甚至裁剪后的图像可能并不包含标签对应的目标。为解决该问题,作者在训练数据及中添加了 Re-labeling 策略,为每个图像重设一个 K=1000 维得分图以得到更精确的标签。不同于知识蒸馏需要老师模型在线生成监督标签,Re-labeling 是一种廉价操作且可视作预处理操作。在训练过程中,仅需对每个裁剪图像计算 K 维稠密得分。因此能够以近乎可忽略的额外计算改善标签质量。

Token Labeling

由于可以从所有 Token 中收集全局信息,为 ViT 添加特定的 Token(比如 cls)是一种常见操作。已有研究表明:在所有 Token 中定义训练目标有助于改善训练时的采样效率。更进一步,基于 Re-labeling 提供的稠密得分图,可以采用它为每个图像块与其对应 Token 提供一个独特标签,作者称之为 Token Labeling。具体来说,作者添加了一个 Token Labeling 损失函数,它利用了每个训练图像的稠密得分图并计算每个 Token 与对应标签之间的交叉熵损失作为辅助损失。假设 ViT 的输出为 ,K 维得分图为 ,整个图像的标签为 。辅助损失定义如下:

注:H 表示交叉熵损失。因此,总体损失定义如下:

MixToken

已有研究表明:MixUp、CutMix 等数据增广方法有助于提升 ViT 的性能与鲁棒性。然而,ViT 依赖于块标记化将每个输入图像转换成 Token 序列,本文所提 Token Labeling 策略同样是在块层面进行处理。如果我们直接将 CutMix 用于原始图像,某些图像块可能包含来自两个图像的内容,进而导致混合区域问题,见下图。

Paddle2.0:浅析并实现 LV-ViT 模型 - 创想鸟

当实施 Token Labeling 时,我们很难为每个输出 Token 赋予干净而正确的标签。考虑到这个问题,我们重新思考了 CutMix 并提出了 MixToken,它可以视作改进版 CutMix,见上图右。具体来说,假设两个图像表示为 I1,I2I1,I2,他们对应的标签为 我们首先将两个图像送入块嵌入模块将每个图像序列化得到 然后,我们通过 MixToken 按照如下方式生成新的序列 Token:

注:M 的生成方式与 CutMix 相同。
对于每个标签,我们采用类似方式混合:
CLS 的标签重写如下:

模型搭建

介绍完 LV-ViT 模型的一些改进接下来就完整的搭建一下模型

模型组网

In [3]

import numpy as npimport paddleimport paddle.nn as nnfrom common import DropPath, Identityfrom common import trunc_normal_, ones_, zeros_from common import to_2tuple, add_parameterclass GroupLinear(nn.Layer):    """    Group Linear operator    """    def __init__(self, in_planes, out_channels, groups=1, bias=True):        super(GroupLinear, self).__init__()        assert in_planes % groups == 0        assert out_channels % groups == 0        self.in_dim = in_planes        self.out_dim = out_channels        self.groups = groups        self.group_in_dim = int(self.in_dim / self.groups)        self.group_out_dim = int(self.out_dim / self.groups)        self.group_weight = add_parameter(            self, paddle.zeros((self.groups, self.group_in_dim, self.group_out_dim))        )        if bias is True:            self.group_bias = add_parameter(self, paddle.zeros((self.out_dim,)))        else:            self.group_bias = None    def forward(self, x):        t, b, d = x.shape        x = x.reshape((t * b, self.groups, int(d / self.groups)))        x = x.transpose((1, 0, 2))        x = paddle.bmm(x, self.group_weight)        x = x.transpose((1, 0, 2))        x = x.reshape((t, b, self.out_dim))        if self.group_bias is not None:            x = x + self.group_bias        return xclass Mlp(nn.Layer):    """    MLP with support to use group linear operator    """    def __init__(        self,        in_features,        hidden_features=None,        out_features=None,        act_layer=nn.GELU,        drop=0.0,        group=1,    ):        super().__init__()        out_features = out_features or in_features        hidden_features = hidden_features or in_features        if group == 1:            self.fc1 = nn.Linear(in_features, hidden_features)            self.fc2 = nn.Linear(hidden_features, out_features)        else:            self.fc1 = GroupLinear(in_features, hidden_features, group)            self.fc2 = GroupLinear(hidden_features, out_features, group)        self.act = act_layer()        self.drop = nn.Dropout(drop)    def forward(self, x):        x = self.fc1(x)        x = self.act(x)        x = self.drop(x)        x = self.fc2(x)        x = self.drop(x)        return xclass Attention(nn.Layer):    """    Multi-head self-attention    with some modification to support different num_heads and head_dim.    """    def __init__(        self,        dim,        num_heads=8,        head_dim=None,        qkv_bias=False,        qk_scale=None,        attn_drop=0.0,        proj_drop=0.0,    ):        super().__init__()        self.num_heads = num_heads        if head_dim is not None:            self.head_dim = head_dim        else:            head_dim = dim // num_heads            self.head_dim = head_dim        self.scale = qk_scale or head_dim ** -0.5        self.qkv = nn.Linear(            dim, self.head_dim * self.num_heads * 3, bias_attr=qkv_bias        )        self.attn_drop = nn.Dropout(attn_drop)        self.proj = nn.Linear(self.head_dim * self.num_heads, 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))            .transpose((2, 0, 3, 1, 4))        )        # B,heads,N,C/heads        q, k, v = qkv[0], qkv[1], qkv[2]        # trick here to make q@k.t more stable        attn = (q * self.scale) @ k.transpose((0, 1, 3, 2))        attn = nn.functional.softmax(attn, axis=-1)        attn = self.attn_drop(attn)        x = (            (attn @ v)            .transpose((0, 2, 1, 3))            .reshape((B, N, self.head_dim * self.num_heads))        )        x = self.proj(x)        x = self.proj_drop(x)        return xclass Block(nn.Layer):    """    Pre-layernorm transformer block    """    def __init__(        self,        dim,        num_heads,        head_dim=None,        mlp_ratio=4.0,        qkv_bias=False,        qk_scale=None,        drop=0.0,        attn_drop=0.0,        drop_path=0.0,        act_layer=nn.GELU,        norm_layer=nn.LayerNorm,        group=1,        skip_lam=1.0,    ):        super().__init__()        self.dim = dim        self.mlp_hidden_dim = int(dim * mlp_ratio)        self.skip_lam = skip_lam        self.norm1 = norm_layer(dim)        self.attn = Attention(            dim,            num_heads=num_heads,            head_dim=head_dim,            qkv_bias=qkv_bias,            qk_scale=qk_scale,            attn_drop=attn_drop,            proj_drop=drop,        )        self.drop_path = DropPath(drop_path) if drop_path > 0.0 else Identity()        self.norm2 = norm_layer(dim)        self.mlp = Mlp(            in_features=dim,            hidden_features=self.mlp_hidden_dim,            act_layer=act_layer,            drop=drop,            group=group,        )    def forward(self, x):        x = x + self.drop_path(self.attn(self.norm1(x))) / self.skip_lam        x = x + self.drop_path(self.mlp(self.norm2(x))) / self.skip_lam        return xclass MHABlock(nn.Layer):    """    Multihead Attention block with residual branch    """    def __init__(        self,        dim,        num_heads,        head_dim=None,        mlp_ratio=4.0,        qkv_bias=False,        qk_scale=None,        drop=0.0,        attn_drop=0.0,        drop_path=0.0,        act_layer=nn.GELU,        norm_layer=nn.LayerNorm,        group=1,        skip_lam=1.0,    ):        super().__init__()        self.dim = dim        self.norm1 = norm_layer(dim)        self.skip_lam = skip_lam        self.attn = Attention(            dim,            num_heads=num_heads,            head_dim=head_dim,            qkv_bias=qkv_bias,            qk_scale=qk_scale,            attn_drop=attn_drop,            proj_drop=drop,        )        self.drop_path = DropPath(drop_path) if drop_path > 0.0 else Identity()    def forward(self, x):        x = x + self.drop_path(self.attn(self.norm1(x * self.skip_lam))) / self.skip_lam        return xclass FFNBlock(nn.Layer):    """    Feed forward network with residual branch    """    def __init__(        self,        dim,        num_heads,        head_dim=None,        mlp_ratio=4.0,        qkv_bias=False,        qk_scale=None,        drop=0.0,        attn_drop=0.0,        drop_path=0.0,        act_layer=nn.GELU,        norm_layer=nn.LayerNorm,        group=1,        skip_lam=1.0,    ):        super().__init__()        self.skip_lam = skip_lam        self.dim = dim        self.mlp_hidden_dim = int(dim * mlp_ratio)        self.drop_path = DropPath(drop_path) if drop_path > 0.0 else Identity()        self.norm2 = norm_layer(dim)        self.mlp = Mlp(            in_features=dim,            hidden_features=self.mlp_hidden_dim,            act_layer=act_layer,            drop=drop,            group=group,        )    def forward(self, x):        x = x + self.drop_path(self.mlp(self.norm2(x * self.skip_lam))) / self.skip_lam        return xclass HybridEmbed(nn.Layer):    """CNN Feature Map Embedding    Extract feature map from CNN, flatten, project to embedding dim.    """    def __init__(        self, backbone, img_size=224, feature_size=None, in_chans=3, embed_dim=768    ):        super().__init__()        assert isinstance(backbone, nn.Layer)        img_size = to_2tuple(img_size)        self.img_size = img_size        self.backbone = backbone        if feature_size is None:            with paddle.no_grad():                training = backbone.training                if training:                    backbone.eval()                o = self.backbone(                    paddle.zeros((1, in_chans, img_size[0], img_size[1]))                )[-1]                feature_size = o.shape[-2:]                feature_dim = o.shape[1]                backbone.train(training)        else:            feature_size = to_2tuple(feature_size)            feature_dim = self.backbone.feature_info.channels()[-1]        self.num_patches = feature_size[0] * feature_size[1]        self.proj = nn.Conv2D(feature_dim, embed_dim, kernel_size=1)    def forward(self, x):        x = self.backbone(x)[-1]        x = self.proj(x)        return xclass PatchEmbedNaive(nn.Layer):    """    Image to Patch Embedding    """    def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):        super().__init__()        img_size = to_2tuple(img_size)        patch_size = to_2tuple(patch_size)        num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])        self.img_size = img_size        self.patch_size = patch_size        self.num_patches = num_patches        self.embed_dim = embed_dim        self.proj = nn.Conv2D(            in_chans, embed_dim, kernel_size=patch_size, stride=patch_size        )    def forward(self, x):        B, C, H, W = x.shape        assert (            H == self.img_size[0] and W == self.img_size[1]        ), f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."        x = self.proj(x)        return xclass PatchEmbed4_2(nn.Layer):    """    Image to Patch Embedding with 4 layer convolution    """    def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):        super().__init__()        new_patch_size = to_2tuple(patch_size // 2)        img_size = to_2tuple(img_size)        patch_size = to_2tuple(patch_size)        num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])        self.img_size = img_size        self.patch_size = patch_size        self.num_patches = num_patches        self.embed_dim = embed_dim        self.conv1 = nn.Conv2D(            in_chans, 64, kernel_size=7, stride=2, padding=3, bias_attr=False        )  # 112x112        self.bn1 = nn.BatchNorm2D(64)        self.relu = nn.ReLU()        self.conv2 = nn.Conv2D(            64, 64, kernel_size=3, stride=1, padding=1, bias_attr=False        )  # 112x112        self.bn2 = nn.BatchNorm2D(64)        self.conv3 = nn.Conv2D(            64, 64, kernel_size=3, stride=1, padding=1, bias_attr=False        )        self.bn3 = nn.BatchNorm2D(64)        self.proj = nn.Conv2D(            64, embed_dim, kernel_size=new_patch_size, stride=new_patch_size        )    def forward(self, x):        x = self.conv1(x)        x = self.bn1(x)        x = self.relu(x)        x = self.conv2(x)        x = self.bn2(x)        x = self.relu(x)        x = self.conv3(x)        x = self.bn3(x)        x = self.relu(x)        x = self.proj(x)  # [B, C, W, H]        return xclass PatchEmbed4_2_128(nn.Layer):    """    Image to Patch Embedding with 4 layer convolution and 128 filters    """    def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):        super().__init__()        new_patch_size = to_2tuple(patch_size // 2)        img_size = to_2tuple(img_size)        patch_size = to_2tuple(patch_size)        num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])        self.img_size = img_size        self.patch_size = patch_size        self.num_patches = num_patches        self.embed_dim = embed_dim        self.conv1 = nn.Conv2D(            in_chans, 128, kernel_size=7, stride=2, padding=3, bias_attr=False        )  # 112x112        self.bn1 = nn.BatchNorm2D(128)        self.relu = nn.ReLU()        self.conv2 = nn.Conv2D(            128, 128, kernel_size=3, stride=1, padding=1, bias_attr=False        )  # 112x112        self.bn2 = nn.BatchNorm2D(128)        self.conv3 = nn.Conv2D(            128, 128, kernel_size=3, stride=1, padding=1, bias_attr=False        )        self.bn3 = nn.BatchNorm2D(128)        self.proj = nn.Conv2D(            128, embed_dim, kernel_size=new_patch_size, stride=new_patch_size        )    def forward(self, x):        x = self.conv1(x)        x = self.bn1(x)        x = self.relu(x)        x = self.conv2(x)        x = self.bn2(x)        x = self.relu(x)        x = self.conv3(x)        x = self.bn3(x)        x = self.relu(x)        x = self.proj(x)  # [B, C, W, H]        return xdef get_block(block_type, **kargs):    if block_type == "mha":        # multi-head attention block        return MHABlock(**kargs)    elif block_type == "ffn":        # feed forward block        return FFNBlock(**kargs)    elif block_type == "tr":        # transformer block        return Block(**kargs)def rand_bbox(size, lam):    W = size[2]    H = size[3]    cut_rat = np.sqrt(1.0 - lam)    cut_w = np.int(W * cut_rat)    cut_h = np.int(H * cut_rat)    # uniform    cx = np.random.randint(W)    cy = np.random.randint(H)    bbx1 = np.clip(cx - cut_w // 2, 0, W)    bby1 = np.clip(cy - cut_h // 2, 0, H)    bbx2 = np.clip(cx + cut_w // 2, 0, W)    bby2 = np.clip(cy + cut_h // 2, 0, H)    return bbx1, bby1, bbx2, bby2def get_dpr(drop_path_rate, depth, drop_path_decay="linear"):    if drop_path_decay == "linear":        # linear dpr decay        # stochastic depth decay rule        dpr = np.linspace(0, drop_path_rate, depth)    elif drop_path_decay == "fix":        # use fixed dpr        dpr = [drop_path_rate] * depth    else:        # use predefined drop_path_rate list        assert len(drop_path_rate) == depth        dpr = drop_path_rate    return dprclass LV_ViT(nn.Layer):    """Vision Transformer with tricks    Arguements:        p_emb: different conv based position embedding (default: 4 layer conv)        skip_lam: residual scalar for skip connection (default: 1.0)        order: which order of layers will be used (default: None, will override depth if given)        mix_token: use mix token augmentation for batch of tokens (default: False)        return_dense: whether to return feature of all tokens with an additional aux_head (default: False)    """    def __init__(        self,        img_size=224,        patch_size=16,        in_chans=3,        embed_dim=768,        depth=12,        num_heads=12,        mlp_ratio=3.0,        qkv_bias=False,        qk_scale=None,        drop_rate=0.0,        attn_drop_rate=0.0,        drop_path_rate=0.0,        drop_path_decay="linear",        hybrid_backbone=None,        norm_layer=nn.LayerNorm,        p_emb="4_2",        head_dim=None,        skip_lam=1.0,        order=None,        mix_token=True,        return_dense=True,        class_dim=1000,    ):        super().__init__()        self.class_dim = class_dim        # num_features for consistency with other models        self.num_features = self.embed_dim = embed_dim        self.output_dim = embed_dim if class_dim == 0 else class_dim        if hybrid_backbone is not None:            self.patch_embed = HybridEmbed(                hybrid_backbone,                img_size=img_size,                in_chans=in_chans,                embed_dim=embed_dim,            )        else:            if p_emb == "4_2":                patch_embed_fn = PatchEmbed4_2            elif p_emb == "4_2_128":                patch_embed_fn = PatchEmbed4_2_128            else:                patch_embed_fn = PatchEmbedNaive            self.patch_embed = patch_embed_fn(                img_size=img_size,                patch_size=patch_size,                in_chans=in_chans,                embed_dim=embed_dim,            )        num_patches = self.patch_embed.num_patches        self.cls_token = add_parameter(self, paddle.zeros((1, 1, embed_dim)))        self.pos_embed = add_parameter(            self, paddle.zeros((1, num_patches + 1, embed_dim))        )        self.pos_drop = nn.Dropout(p=drop_rate)        if order is None:            dpr = get_dpr(drop_path_rate, depth, drop_path_decay)            self.blocks = nn.LayerList(                [                    Block(                        dim=embed_dim,                        num_heads=num_heads,                        head_dim=head_dim,                        mlp_ratio=mlp_ratio,                        qkv_bias=qkv_bias,                        qk_scale=qk_scale,                        drop=drop_rate,                        attn_drop=attn_drop_rate,                        drop_path=dpr[i],                        norm_layer=norm_layer,                        skip_lam=skip_lam,                    )                    for i in range(depth)                ]            )        else:            # use given order to sequentially generate modules            dpr = get_dpr(drop_path_rate, len(order), drop_path_decay)            self.blocks = nn.LayerList(                [                    get_block(                        order[i],                        dim=embed_dim,                        num_heads=num_heads,                        head_dim=head_dim,                        mlp_ratio=mlp_ratio,                        qkv_bias=qkv_bias,                        qk_scale=qk_scale,                        drop=drop_rate,                        attn_drop=attn_drop_rate,                        drop_path=dpr[i],                        norm_layer=norm_layer,                        skip_lam=skip_lam,                    )                    for i in range(len(order))                ]            )        self.norm = norm_layer(embed_dim)        if class_dim > 0:            self.head = nn.Linear(embed_dim, class_dim)        self.return_dense = return_dense        self.mix_token = mix_token        if (return_dense) and (class_dim > 0):            self.aux_head = nn.Linear(embed_dim, class_dim)        if mix_token:            self.beta = 1.0            assert return_dense, "always return all features when mixtoken is enabled"        trunc_normal_(self.pos_embed)        trunc_normal_(self.cls_token)        self.apply(self._init_weights)    def _init_weights(self, m):        if isinstance(m, nn.Linear):            trunc_normal_(m.weight)            if isinstance(m, nn.Linear) and m.bias is not None:                zeros_(m.bias)        elif isinstance(m, GroupLinear):            trunc_normal_(m.group_weight)            if isinstance(m, GroupLinear) and m.group_bias is not None:                zeros_(m.group_bias)        elif isinstance(m, nn.LayerNorm):            zeros_(m.bias)            ones_(m.weight)    def forward_embeddings(self, x):        x = self.patch_embed(x)        return x    def forward_tokens(self, x):        B = x.shape[0]        cls_tokens = self.cls_token.expand((B, -1, -1))        x = paddle.concat((cls_tokens, x), axis=1)        x = x + self.pos_embed        x = self.pos_drop(x)        for blk in self.blocks:            x = blk(x)        x = self.norm(x)        return x    def forward_features(self, x):        # simple forward to obtain feature map (without mixtoken)        x = self.forward_embeddings(x)        x = x.flatten(2).transpose(1, 2)        x = self.forward_tokens(x)        return x    def forward(self, x):        x = self.forward_embeddings(x)        """        # Todo...        # token level mixtoken augmentation        if self.mix_token and self.training:            lam = np.random.beta(self.beta, self.beta)            patch_h, patch_w = x.shape[2], x.shape[3]            bbx1, bby1, bbx2, bby2 = rand_bbox(x.shape, lam)            temp_x = x.clone()            temp_x[:, :, bbx1:bbx2, bby1:bby2] = x.flip(                0)[:, :, bbx1:bbx2, bby1:bby2]            x = temp_x        else:            bbx1, bby1, bbx2, bby2 = 0, 0, 0, 0        """        bbx1, bby1, bbx2, bby2 = 0, 0, 0, 0        x = x.flatten(2).transpose((0, 2, 1))        x = self.forward_tokens(x)        if self.class_dim > 0:            x_cls = self.head(x[:, 0])        if (self.return_dense) and (self.class_dim > 0):            x_aux = self.aux_head(x[:, 1:])            return x_cls + 0.5 * x_aux.max(1)[0]            """            # Todo...            if not self.training:                return x_cls+0.5*x_aux.max(1)[0]            recover the mixed part            if self.mix_token and self.training:                x_aux = x_aux.reshape(                    x_aux.shape[0], patch_h, patch_w, x_aux.shape[-1])                temp_x = x_aux.clone()                temp_x[:, bbx1:bbx2, bby1:bby2, :] = x_aux.flip(                    0)[:, bbx1:bbx2, bby1:bby2, :]                x_aux = temp_x                x_aux = x_aux.reshape(                    x_aux.shape[0], patch_h*patch_w, x_aux.shape[-1])            return x_cls, x_aux, (bbx1, bby1, bbx2, bby2)            """        return x_cls

预设模型

In [4]

def lvvit_s(pretrained=False, **kwargs):    model = LV_ViT(        img_size=224,        embed_dim=384,        depth=16,        num_heads=6,        p_emb="4_2",        skip_lam=2.0,        **kwargs,    )    if pretrained:        params = paddle.load('data/data86826/lvvit_s_224.pdparams')        model.set_dict(params)    return modeldef lvvit_s_384(pretrained=False, **kwargs):    model = LV_ViT(        img_size=384,        embed_dim=384,        depth=16,        num_heads=6,        p_emb="4_2",        skip_lam=2.0,        **kwargs,    )    if pretrained:        params = paddle.load('data/data86826/lvvit_s_384.pdparams')        model.set_dict(params)    return modeldef lvvit_m(pretrained=False, **kwargs):    model = LV_ViT(        img_size=224,        embed_dim=512,        depth=20,        num_heads=8,        p_emb="4_2",        skip_lam=2.0,        **kwargs,    )    if pretrained:        params = paddle.load('data/data86826/lvvit_m_224.pdparams')        model.set_dict(params)    return modeldef lvvit_m_384(pretrained=False, **kwargs):    model = LV_ViT(        img_size=384,        embed_dim=512,        depth=20,        num_heads=8,        p_emb="4_2",        skip_lam=2.0,        **kwargs,    )    if pretrained:        params = paddle.load('data/data86826/lvvit_m_384.pdparams')        model.set_dict(params)    return modeldef lvvit_m_448(pretrained=False, **kwargs):    model = LV_ViT(        img_size=448,        embed_dim=512,        depth=20,        num_heads=8,        p_emb="4_2",        skip_lam=2.0,        **kwargs,    )    if pretrained:        params = paddle.load('data/data86826/lvvit_m_448.pdparams')        model.set_dict(params)    return modeldef lvvit_l_448(pretrained=False, **kwargs):    model = LV_ViT(        img_size=448,        embed_dim=768,        depth=24,        num_heads=12,        p_emb="4_2_128",        skip_lam=3.0,        order=["tr"] * 24,        **kwargs,    )    if pretrained:        params = paddle.load('data/data86826/lvvit_l_448.pdparams')        model.set_dict(params)    return model

模型测试

In [7]

model = lvvit_s(True)random_input = paddle.randn((1, 3, 224, 224))out = model(random_input)print(out.shape)model.eval()out = model(random_input)print(out.shape)
[1, 1000][1, 1000]

精度验证

官方标称精度如下表:

Model layer dim Image resolution Param Top 1

LV-ViT-S1638422426.15M83.3LV-ViT-S1638438426.30M84.4LV-ViT-M2051222455.83M84.0LV-ViT-M2051238456.03M85.4LV-ViT-M2051244856.13M85.5LV-ViT-L24768448150.47M86.2LV-ViT-L24768512150.66M86.4

解压数据集

In [2]

!mkdir ~/data/ILSVRC2012!tar -xf ~/data/data68594/ILSVRC2012_img_val.tar -C ~/data/ILSVRC2012

模型验证

In [5]

import osimport cv2import numpy as npimport paddleimport paddle.vision.transforms as Tfrom PIL import Image# 构建数据集class ILSVRC2012(paddle.io.Dataset):    def __init__(self, root, label_list, transform, backend='pil'):        self.transform = transform        self.root = root        self.label_list = label_list        self.backend = backend        self.load_datas()    def load_datas(self):        self.imgs = []        self.labels = []        with open(self.label_list, 'r') as f:            for line in f:                img, label = line[:-1].split(' ')                self.imgs.append(os.path.join(self.root, img))                self.labels.append(int(label))    def __getitem__(self, idx):        label = self.labels[idx]        image = self.imgs[idx]        if self.backend=='cv2':            image = cv2.imread(image)        else:            image = Image.open(image).convert('RGB')        image = self.transform(image)        return image.astype('float32'), np.array(label).astype('int64')    def __len__(self):        return len(self.imgs)def get_transforms(resize, crop):    transforms = T.Compose(        [            T.Resize(resize, interpolation="bicubic"),            T.CenterCrop(crop),            T.ToTensor(),            T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),        ]    )    return transformstransforms_224 = get_transforms(248, 224)transforms_384 = get_transforms(384, 384)transforms_448 = get_transforms(448, 448)# 配置模型model = lvvit_s(pretrained=True)model = paddle.Model(model)model.prepare(metrics=paddle.metric.Accuracy(topk=(1, 5)))# 配置数据集val_dataset = ILSVRC2012('data/ILSVRC2012', transform=transforms_224, label_list='data/data68594/val_list.txt', backend='pil')# 模型验证acc = model.evaluate(val_dataset, batch_size=768, num_workers=0, verbose=1)print(acc)
Eval begin...The loss value printed in the log is the current batch, and the metric is the average value of previous step.
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/tensor/creation.py:143: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations  if data.dtype == np.object:/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/fluid/dataloader/dataloader_iter.py:89: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here.Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations  if isinstance(slot[0], (np.ndarray, np.bool, numbers.Number)):/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/fluid/layers/utils.py:77: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  return (isinstance(seq, collections.Sequence) and
step 66/66 [==============================] - acc_top1: 0.8314 - acc_top5: 0.9588 - 8s/step         Eval samples: 50000{'acc_top1': 0.83144, 'acc_top5': 0.95882}

总结

通过探索更加有效的 ViT 的训练策略,构建出了 LV-ViT 在 ImageNet 数据集上实现了 SOTA。证明了 ViT 通过更加合理更加有效的训练策略能够实现更高的精度表现。

以上就是Paddle2.0:浅析并实现 LV-ViT 模型的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/67277.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
忽视缓冲时间会带来哪些连锁反应
上一篇 2025年11月12日 11:23:13
为什么资源分配总是有人过载
下一篇 2025年11月12日 11:24:12

相关推荐

  • Matplotlib 地图中多类型图例的创建与优化

    Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化

    本教程旨在解决matplotlib地图可视化中,如何在一个图例中同时展示颜色块(如区域分类)和自定义标记(如特定兴趣点)的问题。文章详细介绍了当传统`patch`对象无法正确显示标记时,如何利用`matplotlib.lines.line2d`创建标记图例句柄,并将其与颜色块图例句柄合并,从而生成一…

    2026年5月10日 用户投稿
    100
  • Golang JSON序列化:控制敏感字段暴露的最佳实践

    本教程探讨golang中如何高效控制结构体字段在json序列化时的可见性。当需要将包含敏感信息的结构体数组转换为json响应时,通过利用`encoding/json`包提供的结构体标签,特别是`json:”-“`,可以轻松实现对特定字段的忽略,从而避免敏感数据泄露,确保api…

    2026年5月10日
    000
  • 利用海象运算符简化条件赋值:Python教程与最佳实践

    本文旨在探讨Python中海象运算符(:=)在条件赋值场景下的应用。通过对比传统if/else语句与海象运算符,以及条件表达式,分析海象运算符在简化代码、提高可读性方面的优势与局限性。并通过具体示例,展示如何在列表推导式等场景下合理使用海象运算符,同时强调其潜在的复杂性及替代方案,帮助开发者更好地掌…

    2026年5月10日
    000
  • 比特币新手教程 比特币交易平台有哪些

    比特币是一种去中心化的数字货币,基于区块链技术实现点对点交易,具有匿名性、有限发行和不可篡改等特点;新手可通过交易所购买,P2P交易获得比特币,常用平台包括Binance、OKX和Huobi;交易流程包括注册账户、实名认证、绑定支付方式、充值法币并下单购买,可选择市价单或限价单;比特币存储方式有交易…

    2026年5月10日
    000
  • c++中的SFINAE技术是什么_c++模板编程中的SFINAE原理与应用

    SFINAE 是“替换失败不是错误”的原则,指模板实例化时若参数替换导致错误,只要存在其他合法候选,编译器不报错而是继续重载决议。它用于条件启用模板、类型检测等场景,如通过 decltype 或 enable_if 控制函数重载,实现类型特征判断。尽管 C++20 引入 Concepts 简化了部分…

    2026年5月10日
    000
  • Go语言mgo查询构建:深入理解bson.M与日期范围查询的正确实践

    本文旨在解决go语言mgo库中构建复杂查询时,特别是涉及嵌套`bson.m`和日期范围筛选的常见错误。我们将深入剖析`bson.m`的类型特性,解释为何直接索引`interface{}`会导致“invalid operation”错误,并提供一种推荐的、结构清晰的代码重构方案,以确保查询条件能够正确…

    2026年5月10日
    100
  • RichHandler与Rich Progress集成:解决显示冲突的教程

    在使用rich库的`richhandler`进行日志输出并同时使用`progress`组件时,可能会遇到显示错乱或溢出问题。这通常是由于为`richhandler`和`progress`分别创建了独立的`console`实例导致的。解决方案是确保日志处理器和进度条组件共享同一个`console`实例…

    2026年5月10日
    000
  • Golang goroutine与channel调试技巧

    使用go run -race检测数据竞争,结合runtime.NumGoroutine监控协程数量,通过pprof分析阻塞调用栈,利用select超时避免永久阻塞,有效排查goroutine泄漏、死锁和数据竞争问题。 Go语言的goroutine和channel是并发编程的核心,但它们也带来了调试上…

    2026年5月10日
    000
  • 《魔兽世界》将于6月11日开启国服回归技术测试

    《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试

    《%ign%ignore_a_1%re_a_1%》官方宣布,将于6月11日开启国服回归技术测试,时间为7天,并称可以在6月内正式开服,玩家们可以访问官网下载战网客户端并预下载“巫妖王之怒”客户端,技术测试详情见下图。 WordAi WordAI是一个AI驱动的内容重写平台 53 查看详情 以上就是《…

    2026年5月10日 用户投稿
    200
  • 使用 Jupyter Notebook 进行探索性数据分析

    Jupyter Notebook通过单元格实现代码与Markdown结合,支持数据导入(pandas)、清洗(fillna)、探索(matplotlib/seaborn可视化)、统计分析(describe/corr)和特征工程,便于记录与分享分析过程。 Jupyter Notebook 是进行探索性…

    2026年5月10日
    000
  • 如何在HTML中插入表单元素_HTML表单控件与输入类型使用指南

    HTML表单通过标签构建,包含action和method属性定义数据提交目标与方式,常用input类型如text、password、email等适配不同输入需求,配合label、required、placeholder提升可用性,结合textarea、select、button等控件实现完整交互,是…

    2026年5月10日
    000
  • 创建指定大小并填充特定数据的Golang文件教程

    本文将介绍如何使用Golang创建一个指定大小的文件,并用特定数据填充它。我们将使用 `os` 包提供的函数来创建和截断文件,从而实现快速生成大文件的目的。示例代码展示了如何创建一个10MB的文件,并将其填充为全零数据。掌握这些方法,可以方便地在例如日志系统或磁盘队列等场景中,预先创建测试文件或初始…

    2026年5月10日
    000
  • Python命令怎样使用profile分析脚本性能 Python命令性能分析的基础教程

    使用Python的cProfile模块分析脚本性能最直接的方式是通过命令行执行python -m cProfile your_script.py,它会输出每个函数的调用次数、总耗时、累积耗时等关键指标,帮助定位性能瓶颈;为进一步分析,可将结果保存为文件python -m cProfile -o ou…

    2026年5月10日
    000
  • 如何插入查询结果数据_SQL插入Select查询结果方法

    如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法

    使用INSERT INTO…SELECT语句可高效插入数据,通过NOT EXISTS、LEFT JOIN、MERGE语句或唯一约束避免重复;表结构不一致时可通过别名、类型转换、默认值或计算字段处理;结合存储过程可提升可维护性,支持参数化与动态SQL。 将查询结果数据插入到另一个表中,可以…

    2026年5月10日 用户投稿
    000
  • 使用 WebCodecs VideoDecoder 实现精确逐帧回退

    本文档旨在解决在使用 WebCodecs VideoDecoder 进行视频解码时,实现精确逐帧回退的问题。通过比较帧的时间戳与目标帧的时间戳,可以避免渲染中间帧,从而提高用户体验。本文将提供详细的解决方案和示例代码,帮助开发者实现精确的视频帧控制。 在使用 WebCodecs VideoDecod…

    2026年5月10日
    000
  • Debian Copilot的社区活跃度如何

    debian copilot是codeberg社区维护的ai助手,旨在为debian用户提供服务。尽管搜索结果中没有直接提供关于debian copilot社区支持活跃度的具体数据,但我们可以通过debian社区的整体活跃度和特点来推断其活跃性。 Debian社区的一般情况: Debian拥有详尽的…

    2026年5月10日
    000
  • Discord.py 交互按钮超时与持久化解决方案

    本教程旨在解决Discord.py中交互按钮在一段时间后出现“This Interaction Failed”错误的问题。我们将深入探讨视图(View)的超时机制,并提供通过正确设置timeout参数以及利用bot.add_view()方法实现按钮持久化的具体方案,确保您的机器人交互功能稳定可靠,即…

    2026年5月10日
    000
  • Python递归函数追踪与性能考量:以序列打印为例

    本文深入探讨了Python中一种递归打印序列元素的方法,并着重演示了如何通过引入缩进参数来有效追踪递归函数的执行流程和参数变化。通过实际代码示例,文章揭示了递归调用可能带来的潜在性能开销,特别是对调用栈空间的需求,以及Python默认递归深度限制可能导致的错误,为读者提供了理解和优化递归算法的实用见…

    2026年5月10日
    000
  • python中zip函数详解 python多序列压缩zip函数应用场景

    zip函数的应用场景包括:1) 同时遍历多个序列,2) 合并多个列表的数据,3) 数据分析和科学计算中的元素运算,4) 处理csv文件,5) 性能优化。zip函数是一个强大的工具,能够简化代码并提高处理多个序列时的效率。 在Python中,zip函数是一个非常有用的工具,它能够将多个可迭代对象打包成…

    2026年5月10日
    000
  • JavaScript 动态菜单点击高亮效果实现教程

    本教程详细介绍了如何使用 JavaScript 实现动态菜单的点击高亮功能。通过事件委托和状态管理,当用户点击菜单项时,被点击项会高亮显示(绿色),同时其他菜单项恢复默认样式(白色)。这种方法避免了不必要的DOM操作,提高了性能和代码可维护性,确保了无论点击方向如何,功能都能稳定运行。 动态菜单高亮…

    2026年5月10日
    200

发表回复

登录后才能评论
关注微信