text
stringlengths
5
631k
id
stringlengths
14
178
metadata
dict
__index_level_0__
int64
0
647
""" EfficientNet, MobileNetV3, etc Blocks Hacked together by / Copyright 2019, Ross Wightman """ from typing import Callable, Dict, Optional, Type import torch import torch.nn as nn from torch.nn import functional as F from timm.layers import create_conv2d, DropPath, make_divisible, create_act_layer, create_aa, to_2tuple, LayerType,\ ConvNormAct, get_norm_act_layer, MultiQueryAttention2d, Attention2d __all__ = [ 'SqueezeExcite', 'ConvBnAct', 'DepthwiseSeparableConv', 'InvertedResidual', 'CondConvResidual', 'EdgeResidual', 'UniversalInvertedResidual', 'MobileAttention' ] ModuleType = Type[nn.Module] def num_groups(group_size: Optional[int], channels: int): if not group_size: # 0 or None return 1 # normal conv with 1 group else: # NOTE group_size == 1 -> depthwise conv assert channels % group_size == 0 return channels // group_size class SqueezeExcite(nn.Module): """ Squeeze-and-Excitation w/ specific features for EfficientNet/MobileNet family Args: in_chs (int): input channels to layer rd_ratio (float): ratio of squeeze reduction act_layer (nn.Module): activation layer of containing block gate_layer (Callable): attention gate function force_act_layer (nn.Module): override block's activation fn if this is set/bound rd_round_fn (Callable): specify a fn to calculate rounding of reduced chs """ def __init__( self, in_chs: int, rd_ratio: float = 0.25, rd_channels: Optional[int] = None, act_layer: LayerType = nn.ReLU, gate_layer: LayerType = nn.Sigmoid, force_act_layer: Optional[LayerType] = None, rd_round_fn: Optional[Callable] = None, ): super(SqueezeExcite, self).__init__() if rd_channels is None: rd_round_fn = rd_round_fn or round rd_channels = rd_round_fn(in_chs * rd_ratio) act_layer = force_act_layer or act_layer self.conv_reduce = nn.Conv2d(in_chs, rd_channels, 1, bias=True) self.act1 = create_act_layer(act_layer, inplace=True) self.conv_expand = nn.Conv2d(rd_channels, in_chs, 1, bias=True) self.gate = create_act_layer(gate_layer) def forward(self, x): x_se = x.mean((2, 3), keepdim=True) x_se = self.conv_reduce(x_se) x_se = self.act1(x_se) x_se = self.conv_expand(x_se) return x * self.gate(x_se) class ConvBnAct(nn.Module): """ Conv + Norm Layer + Activation w/ optional skip connection """ def __init__( self, in_chs: int, out_chs: int, kernel_size: int, stride: int = 1, dilation: int = 1, group_size: int = 0, pad_type: str = '', skip: bool = False, act_layer: LayerType = nn.ReLU, norm_layer: LayerType = nn.BatchNorm2d, aa_layer: Optional[LayerType] = None, drop_path_rate: float = 0., ): super(ConvBnAct, self).__init__() norm_act_layer = get_norm_act_layer(norm_layer, act_layer) groups = num_groups(group_size, in_chs) self.has_skip = skip and stride == 1 and in_chs == out_chs use_aa = aa_layer is not None and stride > 1 # FIXME handle dilation self.conv = create_conv2d( in_chs, out_chs, kernel_size, stride=1 if use_aa else stride, dilation=dilation, groups=groups, padding=pad_type) self.bn1 = norm_act_layer(out_chs, inplace=True) self.aa = create_aa(aa_layer, channels=out_chs, stride=stride, enable=use_aa) self.drop_path = DropPath(drop_path_rate) if drop_path_rate else nn.Identity() def feature_info(self, location): if location == 'expansion': # output of conv after act, same as block coutput return dict(module='bn1', hook_type='forward', num_chs=self.conv.out_channels) else: # location == 'bottleneck', block output return dict(module='', num_chs=self.conv.out_channels) def forward(self, x): shortcut = x x = self.conv(x) x = self.bn1(x) x = self.aa(x) if self.has_skip: x = self.drop_path(x) + shortcut return x class DepthwiseSeparableConv(nn.Module): """ Depthwise-separable block Used for DS convs in MobileNet-V1 and in the place of IR blocks that have no expansion (factor of 1.0). This is an alternative to having a IR with an optional first pw conv. """ def __init__( self, in_chs: int, out_chs: int, dw_kernel_size: int = 3, stride: int = 1, dilation: int = 1, group_size: int = 1, pad_type: str = '', noskip: bool = False, pw_kernel_size: int = 1, pw_act: bool = False, s2d: int = 0, act_layer: LayerType = nn.ReLU, norm_layer: LayerType = nn.BatchNorm2d, aa_layer: Optional[LayerType] = None, se_layer: Optional[ModuleType] = None, drop_path_rate: float = 0., ): super(DepthwiseSeparableConv, self).__init__() norm_act_layer = get_norm_act_layer(norm_layer, act_layer) self.has_skip = (stride == 1 and in_chs == out_chs) and not noskip self.has_pw_act = pw_act # activation after point-wise conv use_aa = aa_layer is not None and stride > 1 # FIXME handle dilation # Space to depth if s2d == 1: sd_chs = int(in_chs * 4) self.conv_s2d = create_conv2d(in_chs, sd_chs, kernel_size=2, stride=2, padding='same') self.bn_s2d = norm_act_layer(sd_chs, sd_chs) dw_kernel_size = (dw_kernel_size + 1) // 2 dw_pad_type = 'same' if dw_kernel_size == 2 else pad_type in_chs = sd_chs use_aa = False # disable AA else: self.conv_s2d = None self.bn_s2d = None dw_pad_type = pad_type groups = num_groups(group_size, in_chs) self.conv_dw = create_conv2d( in_chs, in_chs, dw_kernel_size, stride=1 if use_aa else stride, dilation=dilation, padding=dw_pad_type, groups=groups) self.bn1 = norm_act_layer(in_chs, inplace=True) self.aa = create_aa(aa_layer, channels=out_chs, stride=stride, enable=use_aa) # Squeeze-and-excitation self.se = se_layer(in_chs, act_layer=act_layer) if se_layer else nn.Identity() self.conv_pw = create_conv2d(in_chs, out_chs, pw_kernel_size, padding=pad_type) self.bn2 = norm_act_layer(out_chs, inplace=True, apply_act=self.has_pw_act) self.drop_path = DropPath(drop_path_rate) if drop_path_rate else nn.Identity() def feature_info(self, location): if location == 'expansion': # after SE, input to PW return dict(module='conv_pw', hook_type='forward_pre', num_chs=self.conv_pw.in_channels) else: # location == 'bottleneck', block output return dict(module='', num_chs=self.conv_pw.out_channels) def forward(self, x): shortcut = x if self.conv_s2d is not None: x = self.conv_s2d(x) x = self.bn_s2d(x) x = self.conv_dw(x) x = self.bn1(x) x = self.aa(x) x = self.se(x) x = self.conv_pw(x) x = self.bn2(x) if self.has_skip: x = self.drop_path(x) + shortcut return x class InvertedResidual(nn.Module): """ Inverted residual block w/ optional SE Originally used in MobileNet-V2 - https://arxiv.org/abs/1801.04381v4, this layer is often referred to as 'MBConv' for (Mobile inverted bottleneck conv) and is also used in * MNasNet - https://arxiv.org/abs/1807.11626 * EfficientNet - https://arxiv.org/abs/1905.11946 * MobileNet-V3 - https://arxiv.org/abs/1905.02244 """ def __init__( self, in_chs: int, out_chs: int, dw_kernel_size: int = 3, stride: int = 1, dilation: int = 1, group_size: int = 1, pad_type: str = '', noskip: bool = False, exp_ratio: float = 1.0, exp_kernel_size: int = 1, pw_kernel_size: int = 1, s2d: int = 0, act_layer: LayerType = nn.ReLU, norm_layer: LayerType = nn.BatchNorm2d, aa_layer: Optional[LayerType] = None, se_layer: Optional[ModuleType] = None, conv_kwargs: Optional[Dict] = None, drop_path_rate: float = 0., ): super(InvertedResidual, self).__init__() norm_act_layer = get_norm_act_layer(norm_layer, act_layer) conv_kwargs = conv_kwargs or {} self.has_skip = (in_chs == out_chs and stride == 1) and not noskip use_aa = aa_layer is not None and stride > 1 # FIXME handle dilation # Space to depth if s2d == 1: sd_chs = int(in_chs * 4) self.conv_s2d = create_conv2d(in_chs, sd_chs, kernel_size=2, stride=2, padding='same') self.bn_s2d = norm_act_layer(sd_chs, sd_chs) dw_kernel_size = (dw_kernel_size + 1) // 2 dw_pad_type = 'same' if dw_kernel_size == 2 else pad_type in_chs = sd_chs use_aa = False # disable AA else: self.conv_s2d = None self.bn_s2d = None dw_pad_type = pad_type mid_chs = make_divisible(in_chs * exp_ratio) groups = num_groups(group_size, mid_chs) # Point-wise expansion self.conv_pw = create_conv2d(in_chs, mid_chs, exp_kernel_size, padding=pad_type, **conv_kwargs) self.bn1 = norm_act_layer(mid_chs, inplace=True) # Depth-wise convolution self.conv_dw = create_conv2d( mid_chs, mid_chs, dw_kernel_size, stride=1 if use_aa else stride, dilation=dilation, groups=groups, padding=dw_pad_type, **conv_kwargs) self.bn2 = norm_act_layer(mid_chs, inplace=True) self.aa = create_aa(aa_layer, channels=mid_chs, stride=stride, enable=use_aa) # Squeeze-and-excitation self.se = se_layer(mid_chs, act_layer=act_layer) if se_layer else nn.Identity() # Point-wise linear projection self.conv_pwl = create_conv2d(mid_chs, out_chs, pw_kernel_size, padding=pad_type, **conv_kwargs) self.bn3 = norm_act_layer(out_chs, apply_act=False) self.drop_path = DropPath(drop_path_rate) if drop_path_rate else nn.Identity() def feature_info(self, location): if location == 'expansion': # after SE, input to PWL return dict(module='conv_pwl', hook_type='forward_pre', num_chs=self.conv_pwl.in_channels) else: # location == 'bottleneck', block output return dict(module='', num_chs=self.conv_pwl.out_channels) def forward(self, x): shortcut = x if self.conv_s2d is not None: x = self.conv_s2d(x) x = self.bn_s2d(x) x = self.conv_pw(x) x = self.bn1(x) x = self.conv_dw(x) x = self.bn2(x) x = self.aa(x) x = self.se(x) x = self.conv_pwl(x) x = self.bn3(x) if self.has_skip: x = self.drop_path(x) + shortcut return x class LayerScale2d(nn.Module): def __init__(self, dim: int, init_values: float = 1e-5, inplace: bool = False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): gamma = self.gamma.view(1, -1, 1, 1) return x.mul_(gamma) if self.inplace else x * gamma class UniversalInvertedResidual(nn.Module): """ Universal Inverted Residual Block (aka Universal Inverted Bottleneck, UIB) For MobileNetV4 - https://arxiv.org/abs/, referenced from https://github.com/tensorflow/models/blob/d93c7e932de27522b2fa3b115f58d06d6f640537/official/vision/modeling/layers/nn_blocks.py#L778 """ def __init__( self, in_chs: int, out_chs: int, dw_kernel_size_start: int = 0, dw_kernel_size_mid: int = 3, dw_kernel_size_end: int = 0, stride: int = 1, dilation: int = 1, group_size: int = 1, pad_type: str = '', noskip: bool = False, exp_ratio: float = 1.0, act_layer: LayerType = nn.ReLU, norm_layer: LayerType = nn.BatchNorm2d, aa_layer: Optional[LayerType] = None, se_layer: Optional[ModuleType] = None, conv_kwargs: Optional[Dict] = None, drop_path_rate: float = 0., layer_scale_init_value: Optional[float] = 1e-5, ): super(UniversalInvertedResidual, self).__init__() conv_kwargs = conv_kwargs or {} self.has_skip = (in_chs == out_chs and stride == 1) and not noskip if stride > 1: assert dw_kernel_size_start or dw_kernel_size_mid or dw_kernel_size_end # FIXME dilation isn't right w/ extra ks > 1 convs if dw_kernel_size_start: dw_start_stride = stride if not dw_kernel_size_mid else 1 dw_start_groups = num_groups(group_size, in_chs) self.dw_start = ConvNormAct( in_chs, in_chs, dw_kernel_size_start, stride=dw_start_stride, dilation=dilation, # FIXME groups=dw_start_groups, padding=pad_type, apply_act=False, act_layer=act_layer, norm_layer=norm_layer, aa_layer=aa_layer, **conv_kwargs, ) else: self.dw_start = nn.Identity() # Point-wise expansion mid_chs = make_divisible(in_chs * exp_ratio) self.pw_exp = ConvNormAct( in_chs, mid_chs, 1, padding=pad_type, act_layer=act_layer, norm_layer=norm_layer, **conv_kwargs, ) # Middle depth-wise convolution if dw_kernel_size_mid: groups = num_groups(group_size, mid_chs) self.dw_mid = ConvNormAct( mid_chs, mid_chs, dw_kernel_size_mid, stride=stride, dilation=dilation, # FIXME groups=groups, padding=pad_type, act_layer=act_layer, norm_layer=norm_layer, aa_layer=aa_layer, **conv_kwargs, ) else: # keeping mid as identity so it can be hooked more easily for features self.dw_mid = nn.Identity() # Squeeze-and-excitation self.se = se_layer(mid_chs, act_layer=act_layer) if se_layer else nn.Identity() # Point-wise linear projection self.pw_proj = ConvNormAct( mid_chs, out_chs, 1, padding=pad_type, apply_act=False, act_layer=act_layer, norm_layer=norm_layer, **conv_kwargs, ) if dw_kernel_size_end: dw_end_stride = stride if not dw_kernel_size_start and not dw_kernel_size_mid else 1 dw_end_groups = num_groups(group_size, out_chs) if dw_end_stride > 1: assert not aa_layer self.dw_end = ConvNormAct( out_chs, out_chs, dw_kernel_size_end, stride=dw_end_stride, dilation=dilation, groups=dw_end_groups, padding=pad_type, apply_act=False, act_layer=act_layer, norm_layer=norm_layer, **conv_kwargs, ) else: self.dw_end = nn.Identity() if layer_scale_init_value is not None: self.layer_scale = LayerScale2d(out_chs, layer_scale_init_value) else: self.layer_scale = nn.Identity() self.drop_path = DropPath(drop_path_rate) if drop_path_rate else nn.Identity() def feature_info(self, location): if location == 'expansion': # after SE, input to PWL return dict(module='pw_proj.conv', hook_type='forward_pre', num_chs=self.pw_proj.conv.in_channels) else: # location == 'bottleneck', block output return dict(module='', num_chs=self.pw_proj.conv.out_channels) def forward(self, x): shortcut = x x = self.dw_start(x) x = self.pw_exp(x) x = self.dw_mid(x) x = self.se(x) x = self.pw_proj(x) x = self.dw_end(x) x = self.layer_scale(x) if self.has_skip: x = self.drop_path(x) + shortcut return x class MobileAttention(nn.Module): """ Mobile Attention Block For MobileNetV4 - https://arxiv.org/abs/, referenced from https://github.com/tensorflow/models/blob/d93c7e932de27522b2fa3b115f58d06d6f640537/official/vision/modeling/layers/nn_blocks.py#L1504 """ def __init__( self, in_chs: int, out_chs: int, stride: int = 1, dw_kernel_size: int = 3, dilation: int = 1, group_size: int = 1, pad_type: str = '', num_heads: int = 8, key_dim: int = 64, value_dim: int = 64, use_multi_query: bool = False, query_strides: int = (1, 1), kv_stride: int = 1, cpe_dw_kernel_size: int = 3, noskip: bool = False, act_layer: LayerType = nn.ReLU, norm_layer: LayerType = nn.BatchNorm2d, aa_layer: Optional[LayerType] = None, drop_path_rate: float = 0., attn_drop: float = 0.0, proj_drop: float = 0.0, layer_scale_init_value: Optional[float] = 1e-5, use_bias: bool = False, use_cpe: bool = False, ): super(MobileAttention, self).__init__() norm_act_layer = get_norm_act_layer(norm_layer, act_layer) self.has_skip = (stride == 1 and in_chs == out_chs) and not noskip self.query_strides = to_2tuple(query_strides) self.kv_stride = kv_stride self.has_query_stride = any([s > 1 for s in self.query_strides]) # This CPE is different than the one suggested in the original paper. # https://arxiv.org/abs/2102.10882 # 1. Rather than adding one CPE before the attention blocks, we add a CPE # into every attention block. # 2. We replace the expensive Conv2D by a Separable DW Conv. if use_cpe: self.conv_cpe_dw = create_conv2d( in_chs, in_chs, kernel_size=cpe_dw_kernel_size, dilation=dilation, depthwise=True, bias=True, ) else: self.conv_cpe_dw = None self.norm = norm_act_layer(in_chs, apply_act=False) if num_heads is None: assert in_chs % key_dim == 0 num_heads = in_chs // key_dim if use_multi_query: self.attn = MultiQueryAttention2d( in_chs, dim_out=out_chs, num_heads=num_heads, key_dim=key_dim, value_dim=value_dim, query_strides=query_strides, kv_stride=kv_stride, dw_kernel_size=dw_kernel_size, dilation=dilation, padding=pad_type, attn_drop=attn_drop, proj_drop=proj_drop, norm_layer=norm_layer, # use_bias=use_bias, # why not here if used w/ mhsa? ) else: self.attn = Attention2d( in_chs, dim_out=out_chs, num_heads=num_heads, attn_drop=attn_drop, proj_drop=proj_drop, bias=use_bias, ) if layer_scale_init_value is not None: self.layer_scale = LayerScale2d(out_chs, layer_scale_init_value) else: self.layer_scale = nn.Identity() self.drop_path = DropPath(drop_path_rate) if drop_path_rate else nn.Identity() def feature_info(self, location): if location == 'expansion': # after SE, input to PW return dict(module='conv_pw', hook_type='forward_pre', num_chs=self.conv_pw.in_channels) else: # location == 'bottleneck', block output return dict(module='', num_chs=self.conv_pw.out_channels) def forward(self, x): if self.conv_cpe_dw is not None: x_cpe = self.conv_cpe_dw(x) x = x + x_cpe shortcut = x x = self.norm(x) x = self.attn(x) x = self.layer_scale(x) if self.has_skip: x = self.drop_path(x) + shortcut return x class CondConvResidual(InvertedResidual): """ Inverted residual block w/ CondConv routing""" def __init__( self, in_chs: int, out_chs: int, dw_kernel_size: int = 3, stride: int = 1, dilation: int = 1, group_size: int = 1, pad_type: str = '', noskip: bool = False, exp_ratio: float = 1.0, exp_kernel_size: int = 1, pw_kernel_size: int = 1, act_layer: LayerType = nn.ReLU, norm_layer: LayerType = nn.BatchNorm2d, aa_layer: Optional[LayerType] = None, se_layer: Optional[ModuleType] = None, num_experts: int = 0, drop_path_rate: float = 0., ): self.num_experts = num_experts conv_kwargs = dict(num_experts=self.num_experts) super(CondConvResidual, self).__init__( in_chs, out_chs, dw_kernel_size=dw_kernel_size, stride=stride, dilation=dilation, group_size=group_size, pad_type=pad_type, noskip=noskip, exp_ratio=exp_ratio, exp_kernel_size=exp_kernel_size, pw_kernel_size=pw_kernel_size, act_layer=act_layer, norm_layer=norm_layer, aa_layer=aa_layer, se_layer=se_layer, conv_kwargs=conv_kwargs, drop_path_rate=drop_path_rate, ) self.routing_fn = nn.Linear(in_chs, self.num_experts) def forward(self, x): shortcut = x pooled_inputs = F.adaptive_avg_pool2d(x, 1).flatten(1) # CondConv routing routing_weights = torch.sigmoid(self.routing_fn(pooled_inputs)) x = self.conv_pw(x, routing_weights) x = self.bn1(x) x = self.conv_dw(x, routing_weights) x = self.bn2(x) x = self.se(x) x = self.conv_pwl(x, routing_weights) x = self.bn3(x) if self.has_skip: x = self.drop_path(x) + shortcut return x class EdgeResidual(nn.Module): """ Residual block with expansion convolution followed by pointwise-linear w/ stride Originally introduced in `EfficientNet-EdgeTPU: Creating Accelerator-Optimized Neural Networks with AutoML` - https://ai.googleblog.com/2019/08/efficientnet-edgetpu-creating.html This layer is also called FusedMBConv in the MobileDet, EfficientNet-X, and EfficientNet-V2 papers * MobileDet - https://arxiv.org/abs/2004.14525 * EfficientNet-X - https://arxiv.org/abs/2102.05610 * EfficientNet-V2 - https://arxiv.org/abs/2104.00298 """ def __init__( self, in_chs: int, out_chs: int, exp_kernel_size: int = 3, stride: int = 1, dilation: int = 1, group_size: int = 0, pad_type: str = '', force_in_chs: int = 0, noskip: bool = False, exp_ratio: float = 1.0, pw_kernel_size: int = 1, act_layer: LayerType = nn.ReLU, norm_layer: LayerType = nn.BatchNorm2d, aa_layer: Optional[LayerType] = None, se_layer: Optional[ModuleType] = None, drop_path_rate: float = 0., ): super(EdgeResidual, self).__init__() norm_act_layer = get_norm_act_layer(norm_layer, act_layer) if force_in_chs > 0: mid_chs = make_divisible(force_in_chs * exp_ratio) else: mid_chs = make_divisible(in_chs * exp_ratio) groups = num_groups(group_size, mid_chs) # NOTE: Using out_chs of conv_exp for groups calc self.has_skip = (in_chs == out_chs and stride == 1) and not noskip use_aa = aa_layer is not None and stride > 1 # FIXME handle dilation # Expansion convolution self.conv_exp = create_conv2d( in_chs, mid_chs, exp_kernel_size, stride=1 if use_aa else stride, dilation=dilation, groups=groups, padding=pad_type) self.bn1 = norm_act_layer(mid_chs, inplace=True) self.aa = create_aa(aa_layer, channels=mid_chs, stride=stride, enable=use_aa) # Squeeze-and-excitation self.se = se_layer(mid_chs, act_layer=act_layer) if se_layer else nn.Identity() # Point-wise linear projection self.conv_pwl = create_conv2d(mid_chs, out_chs, pw_kernel_size, padding=pad_type) self.bn2 = norm_act_layer(out_chs, apply_act=False) self.drop_path = DropPath(drop_path_rate) if drop_path_rate else nn.Identity() def feature_info(self, location): if location == 'expansion': # after SE, before PWL return dict(module='conv_pwl', hook_type='forward_pre', num_chs=self.conv_pwl.in_channels) else: # location == 'bottleneck', block output return dict(module='', num_chs=self.conv_pwl.out_channels) def forward(self, x): shortcut = x x = self.conv_exp(x) x = self.bn1(x) x = self.aa(x) x = self.se(x) x = self.conv_pwl(x) x = self.bn2(x) if self.has_skip: x = self.drop_path(x) + shortcut return x
pytorch-image-models/timm/models/_efficientnet_blocks.py/0
{ "file_path": "pytorch-image-models/timm/models/_efficientnet_blocks.py", "repo_id": "pytorch-image-models", "token_count": 13564 }
263
""" BEiT: BERT Pre-Training of Image Transformers (https://arxiv.org/abs/2106.08254) Model from official source: https://github.com/microsoft/unilm/tree/master/beit @inproceedings{beit, title={{BEiT}: {BERT} Pre-Training of Image Transformers}, author={Hangbo Bao and Li Dong and Songhao Piao and Furu Wei}, booktitle={International Conference on Learning Representations}, year={2022}, url={https://openreview.net/forum?id=p-BhZSz59o4} } BEiT-v2 from https://github.com/microsoft/unilm/tree/master/beit2 @article{beitv2, title={{BEiT v2}: Masked Image Modeling with Vector-Quantized Visual Tokenizers}, author={Zhiliang Peng and Li Dong and Hangbo Bao and Qixiang Ye and Furu Wei}, year={2022}, eprint={2208.06366}, archivePrefix={arXiv}, primaryClass={cs.CV} } At this point only the 1k fine-tuned classification weights and model configs have been added, see original source above for pre-training models and procedure. Modifications by / Copyright 2021 Ross Wightman, original copyrights below """ # -------------------------------------------------------- # BEIT: BERT Pre-Training of Image Transformers (https://arxiv.org/abs/2106.08254) # Github source: https://github.com/microsoft/unilm/tree/master/beit # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # By Hangbo Bao # Based on timm and DeiT code bases # https://github.com/rwightman/pytorch-image-models/tree/master/timm # https://github.com/facebookresearch/deit/ # https://github.com/facebookresearch/dino # --------------------------------------------------------' import math from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import PatchEmbed, Mlp, SwiGLU, LayerNorm, DropPath, trunc_normal_, use_fused_attn from timm.layers import resample_patch_embed, resample_abs_pos_embed, resize_rel_pos_bias_table, ndgrid from ._builder import build_model_with_cfg from ._features import feature_take_indices from ._manipulate import checkpoint from ._registry import generate_default_cfgs, register_model __all__ = ['Beit'] def gen_relative_position_index(window_size: Tuple[int, int]) -> torch.Tensor: """Generate relative position index for window-based attention. Creates a lookup table for relative position indices between all pairs of positions within a window, including special handling for cls token interactions. Args: window_size: Height and width of the attention window. Returns: Relative position index tensor of shape (window_area+1, window_area+1) where +1 accounts for the cls token. """ num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3 # cls to token & token 2 cls & cls to cls # get pair-wise relative position index for each token inside the window window_area = window_size[0] * window_size[1] coords = torch.stack(ndgrid(torch.arange(window_size[0]), torch.arange(window_size[1]))) # 2, Wh, Ww coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0 relative_coords[:, :, 1] += window_size[1] - 1 relative_coords[:, :, 0] *= 2 * window_size[1] - 1 relative_position_index = torch.zeros(size=(window_area + 1,) * 2, dtype=relative_coords.dtype) relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww relative_position_index[0, 0:] = num_relative_distance - 3 relative_position_index[0:, 0] = num_relative_distance - 2 relative_position_index[0, 0] = num_relative_distance - 1 return relative_position_index class Attention(nn.Module): """Multi-head attention module with optional relative position bias. Implements multi-head self-attention with support for relative position bias and fused attention operations. Can use either standard or custom head dimensions. """ fused_attn: torch.jit.Final[bool] def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = False, qkv_bias_separate: bool = False, attn_drop: float = 0., proj_drop: float = 0., window_size: Optional[Tuple[int, int]] = None, attn_head_dim: Optional[int] = None, ): """Initialize attention module. Args: dim: Input feature dimension. num_heads: Number of attention heads. qkv_bias: If True, add learnable bias to query, key, value projections. qkv_bias_separate: If True, use separate bias for q, k, v projections. attn_drop: Dropout rate for attention weights. proj_drop: Dropout rate for output projection. window_size: Window size for relative position bias. If None, no relative position bias. attn_head_dim: Dimension per attention head. If None, uses dim // num_heads. """ super().__init__() self.num_heads = num_heads head_dim = dim // num_heads if attn_head_dim is not None: head_dim = attn_head_dim all_head_dim = head_dim * self.num_heads self.scale = head_dim ** -0.5 self.fused_attn = use_fused_attn() self.qkv_bias_separate = qkv_bias_separate self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False) if qkv_bias: self.q_bias = nn.Parameter(torch.zeros(all_head_dim)) self.register_buffer('k_bias', torch.zeros(all_head_dim), persistent=False) self.v_bias = nn.Parameter(torch.zeros(all_head_dim)) else: self.q_bias = None self.k_bias = None self.v_bias = None if window_size: self.window_size = window_size self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3 self.relative_position_bias_table = nn.Parameter( torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH self.register_buffer("relative_position_index", gen_relative_position_index(window_size), persistent=False) else: self.window_size = None self.relative_position_bias_table = None self.relative_position_index = None self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(all_head_dim, dim) self.proj_drop = nn.Dropout(proj_drop) def _get_rel_pos_bias(self) -> torch.Tensor: """Get relative position bias for the attention window. Returns: Relative position bias tensor of shape (1, num_heads, window_area+1, window_area+1). """ relative_position_bias = self.relative_position_bias_table[ self.relative_position_index.view(-1)].view( self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww return relative_position_bias.unsqueeze(0) def forward(self, x: torch.Tensor, shared_rel_pos_bias: Optional[torch.Tensor] = None) -> torch.Tensor: """Forward pass of attention module. Args: x: Input tensor of shape (batch_size, num_tokens, dim). shared_rel_pos_bias: Optional shared relative position bias from parent module. Returns: Output tensor of shape (batch_size, num_tokens, dim). """ B, N, C = x.shape if self.q_bias is None: qkv = self.qkv(x) else: qkv_bias = torch.cat((self.q_bias, self.k_bias, self.v_bias)) if self.qkv_bias_separate: qkv = self.qkv(x) qkv += qkv_bias else: qkv = F.linear(x, weight=self.qkv.weight, bias=qkv_bias) qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) # B, num_heads, N, head_dim if self.fused_attn: rel_pos_bias = None if self.relative_position_bias_table is not None: rel_pos_bias = self._get_rel_pos_bias() if shared_rel_pos_bias is not None: rel_pos_bias = rel_pos_bias + shared_rel_pos_bias elif shared_rel_pos_bias is not None: rel_pos_bias = shared_rel_pos_bias x = F.scaled_dot_product_attention( q, k, v, attn_mask=rel_pos_bias, dropout_p=self.attn_drop.p if self.training else 0., ) else: q = q * self.scale attn = (q @ k.transpose(-2, -1)) if self.relative_position_bias_table is not None: attn = attn + self._get_rel_pos_bias() if shared_rel_pos_bias is not None: attn = attn + shared_rel_pos_bias attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = attn @ v x = x.transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class Block(nn.Module): """Transformer block with attention and MLP. Standard transformer block consisting of multi-head self-attention and MLP with residual connections and layer normalization. Supports layer scale and stochastic depth regularization. """ def __init__( self, dim: int, num_heads: int, qkv_bias: bool = False, mlp_ratio: float = 4., scale_mlp: bool = False, swiglu_mlp: bool = False, proj_drop: float = 0., attn_drop: float = 0., drop_path: float = 0., init_values: Optional[float] = None, act_layer: Callable = nn.GELU, norm_layer: Callable = LayerNorm, window_size: Optional[Tuple[int, int]] = None, attn_head_dim: Optional[int] = None, ): """Initialize transformer block. Args: dim: Input feature dimension. num_heads: Number of attention heads. qkv_bias: If True, add learnable bias to query, key, value projections. mlp_ratio: Ratio of MLP hidden dimension to input dimension. scale_mlp: If True, apply layer normalization in MLP. swiglu_mlp: If True, use SwiGLU activation in MLP. proj_drop: Dropout rate for projections. attn_drop: Dropout rate for attention. drop_path: Drop path rate for stochastic depth. init_values: Initial values for layer scale. If None, no layer scale. act_layer: Activation function class. norm_layer: Normalization layer class. window_size: Window size for relative position bias in attention. attn_head_dim: Dimension per attention head. """ super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=proj_drop, window_size=window_size, attn_head_dim=attn_head_dim, ) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) if swiglu_mlp: self.mlp = SwiGLU( in_features=dim, hidden_features=int(dim * mlp_ratio), norm_layer=norm_layer if scale_mlp else None, drop=proj_drop, ) else: self.mlp = Mlp( in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, norm_layer=norm_layer if scale_mlp else None, drop=proj_drop, ) self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity() if init_values: self.gamma_1 = nn.Parameter(init_values * torch.ones(dim)) self.gamma_2 = nn.Parameter(init_values * torch.ones(dim)) else: self.gamma_1, self.gamma_2 = None, None def forward(self, x: torch.Tensor, shared_rel_pos_bias: Optional[torch.Tensor] = None) -> torch.Tensor: """Forward pass of transformer block. Args: x: Input tensor of shape (batch_size, num_tokens, dim). shared_rel_pos_bias: Optional shared relative position bias. Returns: Output tensor of shape (batch_size, num_tokens, dim). """ if self.gamma_1 is None: x = x + self.drop_path1(self.attn(self.norm1(x), shared_rel_pos_bias=shared_rel_pos_bias)) x = x + self.drop_path2(self.mlp(self.norm2(x))) else: x = x + self.drop_path1(self.gamma_1 * self.attn(self.norm1(x), shared_rel_pos_bias=shared_rel_pos_bias)) x = x + self.drop_path2(self.gamma_2 * self.mlp(self.norm2(x))) return x class RelativePositionBias(nn.Module): """Relative position bias module for window-based attention. Generates learnable relative position biases for all pairs of positions within a window, including special handling for cls token. """ def __init__(self, window_size: Tuple[int, int], num_heads: int): """Initialize relative position bias module. Args: window_size: Height and width of the attention window. num_heads: Number of attention heads. """ super().__init__() self.window_size = window_size self.window_area = window_size[0] * window_size[1] num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3 self.relative_position_bias_table = nn.Parameter(torch.zeros(num_relative_distance, num_heads)) # trunc_normal_(self.relative_position_bias_table, std=.02) self.register_buffer("relative_position_index", gen_relative_position_index(window_size)) def forward(self) -> torch.Tensor: """Generate relative position bias. Returns: Relative position bias tensor of shape (num_heads, window_area+1, window_area+1). """ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( self.window_area + 1, self.window_area + 1, -1) # Wh*Ww,Wh*Ww,nH return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww class Beit(nn.Module): """BEiT: BERT Pre-Training of Image Transformers. Vision Transformer model with support for relative position bias and shared relative position bias across layers. Implements both BEiT v1 and v2 architectures with flexible configuration options. """ def __init__( self, img_size: Union[int, Tuple[int, int]] = 224, patch_size: Union[int, Tuple[int, int]] = 16, in_chans: int = 3, num_classes: int = 1000, global_pool: str = 'avg', embed_dim: int = 768, depth: int = 12, num_heads: int = 12, qkv_bias: bool = True, mlp_ratio: float = 4., swiglu_mlp: bool = False, scale_mlp: bool = False, drop_rate: float = 0., pos_drop_rate: float = 0., proj_drop_rate: float = 0., attn_drop_rate: float = 0., drop_path_rate: float = 0., norm_layer: Callable = LayerNorm, init_values: Optional[float] = None, use_abs_pos_emb: bool = True, use_rel_pos_bias: bool = False, use_shared_rel_pos_bias: bool = False, head_init_scale: float = 0.001, ): """Initialize BEiT model. Args: img_size: Input image size. patch_size: Patch size for patch embedding. in_chans: Number of input image channels. num_classes: Number of classes for classification head. global_pool: Type of global pooling ('avg' or ''). embed_dim: Embedding dimension. depth: Number of transformer blocks. num_heads: Number of attention heads. qkv_bias: If True, add learnable bias to query, key, value projections. mlp_ratio: Ratio of MLP hidden dimension to embedding dimension. swiglu_mlp: If True, use SwiGLU activation in MLP. scale_mlp: If True, apply layer normalization in MLP. drop_rate: Dropout rate. pos_drop_rate: Dropout rate for position embeddings. proj_drop_rate: Dropout rate for projections. attn_drop_rate: Dropout rate for attention. drop_path_rate: Stochastic depth rate. norm_layer: Normalization layer class. init_values: Initial values for layer scale. use_abs_pos_emb: If True, use absolute position embeddings. use_rel_pos_bias: If True, use relative position bias in attention. use_shared_rel_pos_bias: If True, share relative position bias across layers. head_init_scale: Scale factor for head initialization. """ super().__init__() self.num_classes = num_classes self.global_pool = global_pool self.num_features = self.head_hidden_size = self.embed_dim = embed_dim # for consistency with other models self.num_prefix_tokens = 1 self.grad_checkpointing = False self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, ) num_patches = self.patch_embed.num_patches r = self.patch_embed.feat_ratio() if hasattr(self.patch_embed, 'feat_ratio') else patch_size self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) # self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) if use_abs_pos_emb else None self.pos_drop = nn.Dropout(p=pos_drop_rate) if use_shared_rel_pos_bias: self.rel_pos_bias = RelativePositionBias( window_size=self.patch_embed.grid_size, num_heads=num_heads, ) else: self.rel_pos_bias = None dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule self.blocks = nn.ModuleList([ Block( dim=embed_dim, num_heads=num_heads, qkv_bias=qkv_bias, mlp_ratio=mlp_ratio, scale_mlp=scale_mlp, swiglu_mlp=swiglu_mlp, proj_drop=proj_drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, init_values=init_values, window_size=self.patch_embed.grid_size if use_rel_pos_bias else None, ) for i in range(depth)]) self.feature_info = [ dict(module=f'blocks.{i}', num_chs=embed_dim, reduction=r) for i in range(depth)] use_fc_norm = self.global_pool == 'avg' self.norm = nn.Identity() if use_fc_norm else norm_layer(embed_dim) self.fc_norm = norm_layer(embed_dim) if use_fc_norm else nn.Identity() self.head_drop = nn.Dropout(drop_rate) self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() self.apply(self._init_weights) if self.pos_embed is not None: trunc_normal_(self.pos_embed, std=.02) trunc_normal_(self.cls_token, std=.02) self.fix_init_weight() if isinstance(self.head, nn.Linear): trunc_normal_(self.head.weight, std=.02) self.head.weight.data.mul_(head_init_scale) self.head.bias.data.mul_(head_init_scale) def fix_init_weight(self): """Fix initialization weights according to BEiT paper. Rescales attention and MLP weights based on layer depth to improve training stability. """ def rescale(param, layer_id): param.div_(math.sqrt(2.0 * layer_id)) for layer_id, layer in enumerate(self.blocks): rescale(layer.attn.proj.weight.data, layer_id + 1) rescale(layer.mlp.fc2.weight.data, layer_id + 1) def _init_weights(self, m: nn.Module): """Initialize model weights. Args: m: Module to initialize. """ if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self) -> Set[str]: """Get parameter names that should not use weight decay. Returns: Set of parameter names to exclude from weight decay. """ nwd = {'pos_embed', 'cls_token'} for n, _ in self.named_parameters(): if 'relative_position_bias_table' in n: nwd.add(n) return nwd @torch.jit.ignore def set_grad_checkpointing(self, enable: bool = True): """Enable or disable gradient checkpointing. Args: enable: If True, enable gradient checkpointing. """ self.grad_checkpointing = enable @torch.jit.ignore def group_matcher(self, coarse: bool = False) -> Dict[str, Any]: """Create parameter group matcher for optimizer parameter groups. Args: coarse: If True, use coarse grouping. Returns: Dictionary mapping group names to regex patterns. """ matcher = dict( stem=r'^cls_token|pos_embed|patch_embed|rel_pos_bias', # stem and embed blocks=[(r'^blocks\.(\d+)', None), (r'^norm', (99999,))], ) return matcher @torch.jit.ignore def get_classifier(self) -> nn.Module: """Get the classifier head. Returns: The classification head module. """ return self.head def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None): """Reset the classification head. Args: num_classes: Number of classes for new head. global_pool: Global pooling type. """ self.num_classes = num_classes if global_pool is not None: self.global_pool = global_pool self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() def forward_intermediates( self, x: torch.Tensor, indices: Optional[Union[int, List[int]]] = None, return_prefix_tokens: bool = False, norm: bool = False, stop_early: bool = False, output_fmt: str = 'NCHW', intermediates_only: bool = False, ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]: """Forward pass that returns intermediate feature maps. Args: x: Input image tensor of shape (batch_size, channels, height, width). indices: Block indices to return features from. If int, returns last n blocks. return_prefix_tokens: If True, return both prefix and spatial tokens. norm: If True, apply normalization to intermediate features. stop_early: If True, stop at last selected intermediate. output_fmt: Output format ('NCHW' or 'NLC'). intermediates_only: If True, only return intermediate features. Returns: If intermediates_only is True, returns list of intermediate tensors. Otherwise, returns tuple of (final_features, intermediates). """ assert output_fmt in ('NCHW', 'NLC'), 'Output format must be one of NCHW or NLC.' reshape = output_fmt == 'NCHW' intermediates = [] take_indices, max_index = feature_take_indices(len(self.blocks), indices) # forward pass B, _, height, width = x.shape x = self.patch_embed(x) x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) if self.pos_embed is not None: x = x + self.pos_embed x = self.pos_drop(x) rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None if torch.jit.is_scripting() or not stop_early: # can't slice blocks in torchscript blocks = self.blocks else: blocks = self.blocks[:max_index + 1] for i, blk in enumerate(blocks): if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint(blk, x, shared_rel_pos_bias=rel_pos_bias) else: x = blk(x, shared_rel_pos_bias=rel_pos_bias) if i in take_indices: # normalize intermediates with final norm layer if enabled intermediates.append(self.norm(x) if norm else x) # process intermediates if self.num_prefix_tokens: # split prefix (e.g. class, distill) and spatial feature tokens prefix_tokens = [y[:, 0:self.num_prefix_tokens] for y in intermediates] intermediates = [y[:, self.num_prefix_tokens:] for y in intermediates] if reshape: # reshape to BCHW output format H, W = self.patch_embed.dynamic_feat_size((height, width)) intermediates = [y.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() for y in intermediates] if not torch.jit.is_scripting() and return_prefix_tokens: # return_prefix not support in torchscript due to poor type handling intermediates = list(zip(intermediates, prefix_tokens)) if intermediates_only: return intermediates x = self.norm(x) return x, intermediates def prune_intermediate_layers( self, indices: Union[int, List[int]] = 1, prune_norm: bool = False, prune_head: bool = True, ) -> List[int]: """Prune layers not required for specified intermediate outputs. Args: indices: Indices of blocks to keep. prune_norm: If True, remove final normalization. prune_head: If True, remove classification head. Returns: List of indices that were kept. """ take_indices, max_index = feature_take_indices(len(self.blocks), indices) self.blocks = self.blocks[:max_index + 1] # truncate blocks if prune_norm: self.norm = nn.Identity() if prune_head: self.fc_norm = nn.Identity() self.reset_classifier(0, '') return take_indices def forward_features(self, x: torch.Tensor) -> torch.Tensor: """Forward pass through feature extraction layers. Args: x: Input tensor of shape (batch_size, channels, height, width). Returns: Feature tensor of shape (batch_size, num_tokens, embed_dim). """ x = self.patch_embed(x) x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) if self.pos_embed is not None: x = x + self.pos_embed x = self.pos_drop(x) rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None for blk in self.blocks: if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint(blk, x, shared_rel_pos_bias=rel_pos_bias) else: x = blk(x, shared_rel_pos_bias=rel_pos_bias) x = self.norm(x) return x def forward_head(self, x: torch.Tensor, pre_logits: bool = False) -> torch.Tensor: """Forward pass through classification head. Args: x: Feature tensor of shape (batch_size, num_tokens, embed_dim). pre_logits: If True, return features before final linear layer. Returns: Logits tensor of shape (batch_size, num_classes) or pre-logits. """ if self.global_pool: x = x[:, self.num_prefix_tokens:].mean(dim=1) if self.global_pool == 'avg' else x[:, 0] x = self.fc_norm(x) x = self.head_drop(x) return x if pre_logits else self.head(x) def forward(self, x: torch.Tensor) -> torch.Tensor: """Forward pass through the model. Args: x: Input tensor of shape (batch_size, channels, height, width). Returns: Logits tensor of shape (batch_size, num_classes). """ x = self.forward_features(x) x = self.forward_head(x) return x def _cfg(url: str = '', **kwargs) -> Dict[str, Any]: """Create a default configuration dictionary for BEiT models. Args: url: Model weights URL. **kwargs: Additional configuration parameters. Returns: Configuration dictionary. """ return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'crop_pct': .9, 'interpolation': 'bicubic', 'fixed_input_size': True, 'mean': (0.5, 0.5, 0.5), 'std': (0.5, 0.5, 0.5), 'first_conv': 'patch_embed.proj', 'classifier': 'head', **kwargs } default_cfgs = generate_default_cfgs({ 'beit_base_patch16_224.in22k_ft_in22k_in1k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beit/beit_base_patch16_224_pt22k_ft22kto1k.pth', hf_hub_id='timm/'), 'beit_base_patch16_384.in22k_ft_in22k_in1k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beit/beit_base_patch16_384_pt22k_ft22kto1k.pth', hf_hub_id='timm/', input_size=(3, 384, 384), crop_pct=1.0, ), 'beit_base_patch16_224.in22k_ft_in22k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beit/beit_base_patch16_224_pt22k_ft22k.pth', hf_hub_id='timm/', num_classes=21841, ), 'beit_large_patch16_224.in22k_ft_in22k_in1k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beit/beit_large_patch16_224_pt22k_ft22kto1k.pth', hf_hub_id='timm/'), 'beit_large_patch16_384.in22k_ft_in22k_in1k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beit/beit_large_patch16_384_pt22k_ft22kto1k.pth', hf_hub_id='timm/', input_size=(3, 384, 384), crop_pct=1.0, ), 'beit_large_patch16_512.in22k_ft_in22k_in1k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beit/beit_large_patch16_512_pt22k_ft22kto1k.pth', hf_hub_id='timm/', input_size=(3, 512, 512), crop_pct=1.0, ), 'beit_large_patch16_224.in22k_ft_in22k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beit/beit_large_patch16_224_pt22k_ft22k.pth', hf_hub_id='timm/', num_classes=21841, ), 'beitv2_base_patch16_224.in1k_ft_in22k_in1k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beitv2/beitv2_base_patch16_224_pt1k_ft21kto1k.pth', hf_hub_id='timm/', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD ), 'beitv2_base_patch16_224.in1k_ft_in1k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beitv2/beitv2_base_patch16_224_pt1k_ft1k.pth', hf_hub_id='timm/', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD ), 'beitv2_base_patch16_224.in1k_ft_in22k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beitv2/beitv2_base_patch16_224_pt1k_ft21k.pth', hf_hub_id='timm/', num_classes=21841, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD ), 'beitv2_large_patch16_224.in1k_ft_in22k_in1k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beitv2/beitv2_large_patch16_224_pt1k_ft21kto1k.pth', hf_hub_id='timm/', crop_pct=0.95, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD ), 'beitv2_large_patch16_224.in1k_ft_in1k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beitv2/beitv2_large_patch16_224_pt1k_ft1k.pth', hf_hub_id='timm/', crop_pct=0.95, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD ), 'beitv2_large_patch16_224.in1k_ft_in22k': _cfg( #url='https://conversationhub.blob.core.windows.net/beit-share-public/beitv2/beitv2_large_patch16_224_pt1k_ft21k.pth', hf_hub_id='timm/', num_classes=21841, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD ), }) def checkpoint_filter_fn(state_dict: Dict[str, torch.Tensor], model: nn.Module, interpolation: str = 'bicubic', antialias: bool = True) -> Dict[str, torch.Tensor]: """Filter and process checkpoint state dict for loading. Handles resizing of patch embeddings, position embeddings, and relative position bias tables when model size differs from checkpoint. Args: state_dict: Checkpoint state dictionary. model: Target model to load weights into. interpolation: Interpolation method for resizing. antialias: If True, use antialiasing when resizing. Returns: Filtered state dictionary. """ state_dict = state_dict.get('model', state_dict) state_dict = state_dict.get('module', state_dict) # beit v2 didn't strip module out_dict = {} for k, v in state_dict.items(): if 'relative_position_index' in k: continue if 'patch_embed.proj.weight' in k: O, I, H, W = model.patch_embed.proj.weight.shape if v.shape[-1] != W or v.shape[-2] != H: v = resample_patch_embed( v, (H, W), interpolation=interpolation, antialias=antialias, verbose=True, ) elif k == 'pos_embed' and v.shape[1] != model.pos_embed.shape[1]: # To resize pos embedding when using model at different size from pretrained weights num_prefix_tokens = 1 v = resample_abs_pos_embed( v, new_size=model.patch_embed.grid_size, num_prefix_tokens=num_prefix_tokens, interpolation=interpolation, antialias=antialias, verbose=True, ) elif k.endswith('relative_position_bias_table'): m = model.get_submodule(k[:-29]) if v.shape != m.relative_position_bias_table.shape or m.window_size[0] != m.window_size[1]: v = resize_rel_pos_bias_table( v, new_window_size=m.window_size, new_bias_shape=m.relative_position_bias_table.shape, ) out_dict[k] = v return out_dict def _create_beit(variant: str, pretrained: bool = False, **kwargs) -> Beit: """Create a BEiT model. Args: variant: Model variant name. pretrained: If True, load pretrained weights. **kwargs: Additional model arguments. Returns: BEiT model instance. """ out_indices = kwargs.pop('out_indices', 3) model = build_model_with_cfg( Beit, variant, pretrained, pretrained_filter_fn=checkpoint_filter_fn, feature_cfg=dict(out_indices=out_indices, feature_cls='getter'), **kwargs, ) return model @register_model def beit_base_patch16_224(pretrained: bool = False, **kwargs) -> Beit: """BEiT base model @ 224x224 with patch size 16x16.""" model_args = dict( patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, use_abs_pos_emb=False, use_rel_pos_bias=True, init_values=0.1) model = _create_beit('beit_base_patch16_224', pretrained=pretrained, **dict(model_args, **kwargs)) return model @register_model def beit_base_patch16_384(pretrained: bool = False, **kwargs) -> Beit: """BEiT base model @ 384x384 with patch size 16x16.""" model_args = dict( img_size=384, patch_size=16, embed_dim=768, depth=12, num_heads=12, use_abs_pos_emb=False, use_rel_pos_bias=True, init_values=0.1) model = _create_beit('beit_base_patch16_384', pretrained=pretrained, **dict(model_args, **kwargs)) return model @register_model def beit_large_patch16_224(pretrained: bool = False, **kwargs) -> Beit: """BEiT large model @ 224x224 with patch size 16x16.""" model_args = dict( patch_size=16, embed_dim=1024, depth=24, num_heads=16, use_abs_pos_emb=False, use_rel_pos_bias=True, init_values=1e-5) model = _create_beit('beit_large_patch16_224', pretrained=pretrained, **dict(model_args, **kwargs)) return model @register_model def beit_large_patch16_384(pretrained: bool = False, **kwargs) -> Beit: """BEiT large model @ 384x384 with patch size 16x16.""" model_args = dict( img_size=384, patch_size=16, embed_dim=1024, depth=24, num_heads=16, use_abs_pos_emb=False, use_rel_pos_bias=True, init_values=1e-5) model = _create_beit('beit_large_patch16_384', pretrained=pretrained, **dict(model_args, **kwargs)) return model @register_model def beit_large_patch16_512(pretrained: bool = False, **kwargs) -> Beit: """BEiT large model @ 512x512 with patch size 16x16.""" model_args = dict( img_size=512, patch_size=16, embed_dim=1024, depth=24, num_heads=16, use_abs_pos_emb=False, use_rel_pos_bias=True, init_values=1e-5) model = _create_beit('beit_large_patch16_512', pretrained=pretrained, **dict(model_args, **kwargs)) return model @register_model def beitv2_base_patch16_224(pretrained: bool = False, **kwargs) -> Beit: """BEiT v2 base model @ 224x224 with patch size 16x16.""" model_args = dict( patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, use_abs_pos_emb=False, use_rel_pos_bias=True, init_values=1e-5) model = _create_beit('beitv2_base_patch16_224', pretrained=pretrained, **dict(model_args, **kwargs)) return model @register_model def beitv2_large_patch16_224(pretrained: bool = False, **kwargs) -> Beit: """BEiT v2 large model @ 224x224 with patch size 16x16.""" model_args = dict( patch_size=16, embed_dim=1024, depth=24, num_heads=16, use_abs_pos_emb=False, use_rel_pos_bias=True, init_values=1e-5) model = _create_beit('beitv2_large_patch16_224', pretrained=pretrained, **dict(model_args, **kwargs)) return model
pytorch-image-models/timm/models/beit.py/0
{ "file_path": "pytorch-image-models/timm/models/beit.py", "repo_id": "pytorch-image-models", "token_count": 18240 }
264
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={2022} } Based on Apache 2.0 licensed code at https://github.com/snap-research/EfficientFormer, Copyright (c) 2022 Snap Inc. Modifications and timm support by / Copyright 2022, Ross Wightman """ from typing import Dict, List, Optional, Tuple, Union import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import DropPath, trunc_normal_, to_2tuple, Mlp, ndgrid from ._builder import build_model_with_cfg from ._features import feature_take_indices from ._manipulate import checkpoint_seq from ._registry import generate_default_cfgs, register_model __all__ = ['EfficientFormer'] # model_registry will add each entrypoint fn to this EfficientFormer_width = { 'l1': (48, 96, 224, 448), 'l3': (64, 128, 320, 512), 'l7': (96, 192, 384, 768), } EfficientFormer_depth = { 'l1': (3, 2, 6, 4), 'l3': (4, 4, 12, 6), 'l7': (6, 6, 18, 8), } class Attention(torch.nn.Module): attention_bias_cache: Dict[str, torch.Tensor] def __init__( self, dim=384, key_dim=32, num_heads=8, attn_ratio=4, resolution=7 ): super().__init__() self.num_heads = num_heads self.scale = key_dim ** -0.5 self.key_dim = key_dim self.key_attn_dim = key_dim * num_heads self.val_dim = int(attn_ratio * key_dim) self.val_attn_dim = self.val_dim * num_heads self.attn_ratio = attn_ratio self.qkv = nn.Linear(dim, self.key_attn_dim * 2 + self.val_attn_dim) self.proj = nn.Linear(self.val_attn_dim, dim) resolution = to_2tuple(resolution) pos = torch.stack(ndgrid(torch.arange(resolution[0]), torch.arange(resolution[1]))).flatten(1) rel_pos = (pos[..., :, None] - pos[..., None, :]).abs() rel_pos = (rel_pos[0] * resolution[1]) + rel_pos[1] self.attention_biases = torch.nn.Parameter(torch.zeros(num_heads, resolution[0] * resolution[1])) self.register_buffer('attention_bias_idxs', rel_pos) self.attention_bias_cache = {} # per-device attention_biases cache (data-parallel compat) @torch.no_grad() def train(self, mode=True): super().train(mode) if mode and self.attention_bias_cache: self.attention_bias_cache = {} # clear ab cache def get_attention_biases(self, device: torch.device) -> torch.Tensor: if torch.jit.is_tracing() or self.training: return self.attention_biases[:, self.attention_bias_idxs] else: device_key = str(device) if device_key not in self.attention_bias_cache: self.attention_bias_cache[device_key] = self.attention_biases[:, self.attention_bias_idxs] return self.attention_bias_cache[device_key] def forward(self, x): # x (B,N,C) B, N, C = x.shape qkv = self.qkv(x) qkv = qkv.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) q, k, v = qkv.split([self.key_dim, self.key_dim, self.val_dim], dim=3) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn + self.get_attention_biases(x.device) attn = attn.softmax(dim=-1) x = (attn @ v).transpose(1, 2).reshape(B, N, self.val_attn_dim) x = self.proj(x) return x class Stem4(nn.Sequential): def __init__(self, in_chs, out_chs, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d): super().__init__() self.stride = 4 self.add_module('conv1', nn.Conv2d(in_chs, out_chs // 2, kernel_size=3, stride=2, padding=1)) self.add_module('norm1', norm_layer(out_chs // 2)) self.add_module('act1', act_layer()) self.add_module('conv2', nn.Conv2d(out_chs // 2, out_chs, kernel_size=3, stride=2, padding=1)) self.add_module('norm2', norm_layer(out_chs)) self.add_module('act2', act_layer()) class Downsample(nn.Module): """ Downsampling via strided conv w/ norm Input: tensor in shape [B, C, H, W] Output: tensor in shape [B, C, H/stride, W/stride] """ def __init__(self, in_chs, out_chs, kernel_size=3, stride=2, padding=None, norm_layer=nn.BatchNorm2d): super().__init__() if padding is None: padding = kernel_size // 2 self.conv = nn.Conv2d(in_chs, out_chs, kernel_size=kernel_size, stride=stride, padding=padding) self.norm = norm_layer(out_chs) def forward(self, x): x = self.conv(x) x = self.norm(x) return x class Flat(nn.Module): def __init__(self, ): super().__init__() def forward(self, x): x = x.flatten(2).transpose(1, 2) return x class Pooling(nn.Module): """ Implementation of pooling for PoolFormer --pool_size: pooling size """ def __init__(self, pool_size=3): super().__init__() self.pool = nn.AvgPool2d(pool_size, stride=1, padding=pool_size // 2, count_include_pad=False) def forward(self, x): return self.pool(x) - x class ConvMlpWithNorm(nn.Module): """ Implementation of MLP with 1*1 convolutions. Input: tensor with shape [B, C, H, W] """ def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, drop=0. ): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Conv2d(in_features, hidden_features, 1) self.norm1 = norm_layer(hidden_features) if norm_layer is not None else nn.Identity() self.act = act_layer() self.fc2 = nn.Conv2d(hidden_features, out_features, 1) self.norm2 = norm_layer(out_features) if norm_layer is not None else nn.Identity() self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.norm1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.norm2(x) x = self.drop(x) return x class LayerScale(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): return x.mul_(self.gamma) if self.inplace else x * self.gamma class MetaBlock1d(nn.Module): def __init__( self, dim, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.LayerNorm, proj_drop=0., drop_path=0., layer_scale_init_value=1e-5 ): super().__init__() self.norm1 = norm_layer(dim) self.token_mixer = Attention(dim) self.norm2 = norm_layer(dim) self.mlp = Mlp( in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, drop=proj_drop, ) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.ls1 = LayerScale(dim, layer_scale_init_value) self.ls2 = LayerScale(dim, layer_scale_init_value) def forward(self, x): x = x + self.drop_path(self.ls1(self.token_mixer(self.norm1(x)))) x = x + self.drop_path(self.ls2(self.mlp(self.norm2(x)))) return x class LayerScale2d(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): gamma = self.gamma.view(1, -1, 1, 1) return x.mul_(gamma) if self.inplace else x * gamma class MetaBlock2d(nn.Module): def __init__( self, dim, pool_size=3, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, proj_drop=0., drop_path=0., layer_scale_init_value=1e-5 ): super().__init__() self.token_mixer = Pooling(pool_size=pool_size) self.ls1 = LayerScale2d(dim, layer_scale_init_value) self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.mlp = ConvMlpWithNorm( dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, norm_layer=norm_layer, drop=proj_drop, ) self.ls2 = LayerScale2d(dim, layer_scale_init_value) self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity() def forward(self, x): x = x + self.drop_path1(self.ls1(self.token_mixer(x))) x = x + self.drop_path2(self.ls2(self.mlp(x))) return x class EfficientFormerStage(nn.Module): def __init__( self, dim, dim_out, depth, downsample=True, num_vit=1, pool_size=3, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, norm_layer_cl=nn.LayerNorm, proj_drop=.0, drop_path=0., layer_scale_init_value=1e-5, ): super().__init__() self.grad_checkpointing = False if downsample: self.downsample = Downsample(in_chs=dim, out_chs=dim_out, norm_layer=norm_layer) dim = dim_out else: assert dim == dim_out self.downsample = nn.Identity() blocks = [] if num_vit and num_vit >= depth: blocks.append(Flat()) for block_idx in range(depth): remain_idx = depth - block_idx - 1 if num_vit and num_vit > remain_idx: blocks.append( MetaBlock1d( dim, mlp_ratio=mlp_ratio, act_layer=act_layer, norm_layer=norm_layer_cl, proj_drop=proj_drop, drop_path=drop_path[block_idx], layer_scale_init_value=layer_scale_init_value, )) else: blocks.append( MetaBlock2d( dim, pool_size=pool_size, mlp_ratio=mlp_ratio, act_layer=act_layer, norm_layer=norm_layer, proj_drop=proj_drop, drop_path=drop_path[block_idx], layer_scale_init_value=layer_scale_init_value, )) if num_vit and num_vit == remain_idx: blocks.append(Flat()) self.blocks = nn.Sequential(*blocks) def forward(self, x): x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x class EfficientFormer(nn.Module): def __init__( self, depths, embed_dims=None, in_chans=3, num_classes=1000, global_pool='avg', downsamples=None, num_vit=0, mlp_ratios=4, pool_size=3, layer_scale_init_value=1e-5, act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, norm_layer_cl=nn.LayerNorm, drop_rate=0., proj_drop_rate=0., drop_path_rate=0., **kwargs ): super().__init__() self.num_classes = num_classes self.global_pool = global_pool self.stem = Stem4(in_chans, embed_dims[0], norm_layer=norm_layer) prev_dim = embed_dims[0] # stochastic depth decay rule self.num_stages = len(depths) last_stage = self.num_stages - 1 dpr = [x.tolist() for x in torch.linspace(0, drop_path_rate, sum(depths)).split(depths)] downsamples = downsamples or (False,) + (True,) * (self.num_stages - 1) stages = [] self.feature_info = [] for i in range(self.num_stages): stage = EfficientFormerStage( prev_dim, embed_dims[i], depths[i], downsample=downsamples[i], num_vit=num_vit if i == last_stage else 0, pool_size=pool_size, mlp_ratio=mlp_ratios, act_layer=act_layer, norm_layer_cl=norm_layer_cl, norm_layer=norm_layer, proj_drop=proj_drop_rate, drop_path=dpr[i], layer_scale_init_value=layer_scale_init_value, ) prev_dim = embed_dims[i] stages.append(stage) self.feature_info += [dict(num_chs=embed_dims[i], reduction=2**(i+2), module=f'stages.{i}')] self.stages = nn.Sequential(*stages) # Classifier head self.num_features = self.head_hidden_size = embed_dims[-1] self.norm = norm_layer_cl(self.num_features) self.head_drop = nn.Dropout(drop_rate) self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() # assuming model is always distilled (valid for current checkpoints, will split def if that changes) self.head_dist = nn.Linear(embed_dims[-1], num_classes) if num_classes > 0 else nn.Identity() self.distilled_training = False # must set this True to train w/ distillation token self.apply(self._init_weights) # init for classification def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) @torch.jit.ignore def no_weight_decay(self): return {k for k, _ in self.named_parameters() if 'attention_biases' in k} @torch.jit.ignore def group_matcher(self, coarse=False): matcher = dict( stem=r'^stem', # stem and embed blocks=[(r'^stages\.(\d+)', None), (r'^norm', (99999,))] ) return matcher @torch.jit.ignore def set_grad_checkpointing(self, enable=True): for s in self.stages: s.grad_checkpointing = enable @torch.jit.ignore def get_classifier(self) -> nn.Module: return self.head, self.head_dist def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None): self.num_classes = num_classes if global_pool is not None: self.global_pool = global_pool self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() self.head_dist = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() @torch.jit.ignore def set_distilled_training(self, enable=True): self.distilled_training = enable def forward_intermediates( self, x: torch.Tensor, indices: Optional[Union[int, List[int]]] = None, norm: bool = False, stop_early: bool = False, output_fmt: str = 'NCHW', intermediates_only: bool = False, ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]: """ Forward features that returns intermediates. Args: x: Input image tensor indices: Take last n blocks if int, all if None, select matching indices if sequence norm: Apply norm layer to compatible intermediates stop_early: Stop iterating over blocks when last desired intermediate hit output_fmt: Shape of intermediate feature outputs intermediates_only: Only return intermediate features Returns: """ assert output_fmt in ('NCHW',), 'Output shape must be NCHW.' intermediates = [] take_indices, max_index = feature_take_indices(len(self.stages), indices) # forward pass x = self.stem(x) B, C, H, W = x.shape last_idx = self.num_stages - 1 if torch.jit.is_scripting() or not stop_early: # can't slice blocks in torchscript stages = self.stages else: stages = self.stages[:max_index + 1] feat_idx = 0 for feat_idx, stage in enumerate(stages): x = stage(x) if feat_idx < last_idx: B, C, H, W = x.shape if feat_idx in take_indices: if feat_idx == last_idx: x_inter = self.norm(x) if norm else x intermediates.append(x_inter.reshape(B, H // 2, W // 2, -1).permute(0, 3, 1, 2)) else: intermediates.append(x) if intermediates_only: return intermediates if feat_idx == last_idx: x = self.norm(x) return x, intermediates def prune_intermediate_layers( self, indices: Union[int, List[int]] = 1, prune_norm: bool = False, prune_head: bool = True, ): """ Prune layers not required for specified intermediates. """ take_indices, max_index = feature_take_indices(len(self.stages), indices) self.stages = self.stages[:max_index + 1] # truncate blocks w/ stem as idx 0 if prune_norm: self.norm = nn.Identity() if prune_head: self.reset_classifier(0, '') return take_indices def forward_features(self, x): x = self.stem(x) x = self.stages(x) x = self.norm(x) return x def forward_head(self, x, pre_logits: bool = False): if self.global_pool == 'avg': x = x.mean(dim=1) x = self.head_drop(x) if pre_logits: return x x, x_dist = self.head(x), self.head_dist(x) if self.distilled_training and self.training and not torch.jit.is_scripting(): # only return separate classification predictions when training in distilled mode return x, x_dist else: # during standard train/finetune, inference average the classifier predictions return (x + x_dist) / 2 def forward(self, x): x = self.forward_features(x) x = self.forward_head(x) return x def checkpoint_filter_fn(state_dict, model): """ Remap original checkpoints -> timm """ if 'stem.0.weight' in state_dict: return state_dict # non-original checkpoint, no remapping needed out_dict = {} import re stage_idx = 0 for k, v in state_dict.items(): if k.startswith('patch_embed'): k = k.replace('patch_embed.0', 'stem.conv1') k = k.replace('patch_embed.1', 'stem.norm1') k = k.replace('patch_embed.3', 'stem.conv2') k = k.replace('patch_embed.4', 'stem.norm2') if re.match(r'network\.(\d+)\.proj\.weight', k): stage_idx += 1 k = re.sub(r'network.(\d+).(\d+)', f'stages.{stage_idx}.blocks.\\2', k) k = re.sub(r'network.(\d+).proj', f'stages.{stage_idx}.downsample.conv', k) k = re.sub(r'network.(\d+).norm', f'stages.{stage_idx}.downsample.norm', k) k = re.sub(r'layer_scale_([0-9])', r'ls\1.gamma', k) k = k.replace('dist_head', 'head_dist') out_dict[k] = v return out_dict def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'fixed_input_size': True, 'crop_pct': .95, 'interpolation': 'bicubic', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'first_conv': 'stem.conv1', 'classifier': ('head', 'head_dist'), **kwargs } default_cfgs = generate_default_cfgs({ 'efficientformer_l1.snap_dist_in1k': _cfg( hf_hub_id='timm/', ), 'efficientformer_l3.snap_dist_in1k': _cfg( hf_hub_id='timm/', ), 'efficientformer_l7.snap_dist_in1k': _cfg( hf_hub_id='timm/', ), }) def _create_efficientformer(variant, pretrained=False, **kwargs): out_indices = kwargs.pop('out_indices', 4) model = build_model_with_cfg( EfficientFormer, variant, pretrained, pretrained_filter_fn=checkpoint_filter_fn, feature_cfg=dict(out_indices=out_indices, feature_cls='getter'), **kwargs, ) return model @register_model def efficientformer_l1(pretrained=False, **kwargs) -> EfficientFormer: model_args = dict( depths=EfficientFormer_depth['l1'], embed_dims=EfficientFormer_width['l1'], num_vit=1, ) return _create_efficientformer('efficientformer_l1', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def efficientformer_l3(pretrained=False, **kwargs) -> EfficientFormer: model_args = dict( depths=EfficientFormer_depth['l3'], embed_dims=EfficientFormer_width['l3'], num_vit=4, ) return _create_efficientformer('efficientformer_l3', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def efficientformer_l7(pretrained=False, **kwargs) -> EfficientFormer: model_args = dict( depths=EfficientFormer_depth['l7'], embed_dims=EfficientFormer_width['l7'], num_vit=8, ) return _create_efficientformer('efficientformer_l7', pretrained=pretrained, **dict(model_args, **kwargs))
pytorch-image-models/timm/models/efficientformer.py/0
{ "file_path": "pytorch-image-models/timm/models/efficientformer.py", "repo_id": "pytorch-image-models", "token_count": 10905 }
265
""" PP-HGNet (V1 & V2) Reference: https://github.com/PaddlePaddle/PaddleClas/blob/develop/docs/zh_CN/models/ImageNet1k/PP-HGNetV2.md The Paddle Implement of PP-HGNet (https://github.com/PaddlePaddle/PaddleClas/blob/release/2.5.1/docs/en/models/PP-HGNet_en.md) PP-HGNet: https://github.com/PaddlePaddle/PaddleClas/blob/release/2.5.1/ppcls/arch/backbone/legendary_models/pp_hgnet.py PP-HGNetv2: https://github.com/PaddlePaddle/PaddleClas/blob/release/2.5.1/ppcls/arch/backbone/legendary_models/pp_hgnet_v2.py """ from typing import Dict, List, Optional, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d, DropPath, create_conv2d from ._builder import build_model_with_cfg from ._features import feature_take_indices from ._registry import register_model, generate_default_cfgs from ._manipulate import checkpoint_seq __all__ = ['HighPerfGpuNet'] class LearnableAffineBlock(nn.Module): def __init__( self, scale_value=1.0, bias_value=0.0 ): super().__init__() self.scale = nn.Parameter(torch.tensor([scale_value]), requires_grad=True) self.bias = nn.Parameter(torch.tensor([bias_value]), requires_grad=True) def forward(self, x): return self.scale * x + self.bias class ConvBNAct(nn.Module): def __init__( self, in_chs, out_chs, kernel_size, stride=1, groups=1, padding='', use_act=True, use_lab=False ): super().__init__() self.use_act = use_act self.use_lab = use_lab self.conv = create_conv2d( in_chs, out_chs, kernel_size, stride=stride, padding=padding, groups=groups, ) self.bn = nn.BatchNorm2d(out_chs) if self.use_act: self.act = nn.ReLU() else: self.act = nn.Identity() if self.use_act and self.use_lab: self.lab = LearnableAffineBlock() else: self.lab = nn.Identity() def forward(self, x): x = self.conv(x) x = self.bn(x) x = self.act(x) x = self.lab(x) return x class LightConvBNAct(nn.Module): def __init__( self, in_chs, out_chs, kernel_size, groups=1, use_lab=False ): super().__init__() self.conv1 = ConvBNAct( in_chs, out_chs, kernel_size=1, use_act=False, use_lab=use_lab, ) self.conv2 = ConvBNAct( out_chs, out_chs, kernel_size=kernel_size, groups=out_chs, use_act=True, use_lab=use_lab, ) def forward(self, x): x = self.conv1(x) x = self.conv2(x) return x class EseModule(nn.Module): def __init__(self, chs): super().__init__() self.conv = nn.Conv2d( chs, chs, kernel_size=1, stride=1, padding=0, ) self.sigmoid = nn.Sigmoid() def forward(self, x): identity = x x = x.mean((2, 3), keepdim=True) x = self.conv(x) x = self.sigmoid(x) return torch.mul(identity, x) class StemV1(nn.Module): # for PP-HGNet def __init__(self, stem_chs): super().__init__() self.stem = nn.Sequential(*[ ConvBNAct( stem_chs[i], stem_chs[i + 1], kernel_size=3, stride=2 if i == 0 else 1) for i in range( len(stem_chs) - 1) ]) self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) def forward(self, x): x = self.stem(x) x = self.pool(x) return x class StemV2(nn.Module): # for PP-HGNetv2 def __init__(self, in_chs, mid_chs, out_chs, use_lab=False): super().__init__() self.stem1 = ConvBNAct( in_chs, mid_chs, kernel_size=3, stride=2, use_lab=use_lab, ) self.stem2a = ConvBNAct( mid_chs, mid_chs // 2, kernel_size=2, stride=1, use_lab=use_lab, ) self.stem2b = ConvBNAct( mid_chs // 2, mid_chs, kernel_size=2, stride=1, use_lab=use_lab, ) self.stem3 = ConvBNAct( mid_chs * 2, mid_chs, kernel_size=3, stride=2, use_lab=use_lab, ) self.stem4 = ConvBNAct( mid_chs, out_chs, kernel_size=1, stride=1, use_lab=use_lab, ) self.pool = nn.MaxPool2d(kernel_size=2, stride=1, ceil_mode=True) def forward(self, x): x = self.stem1(x) x = F.pad(x, (0, 1, 0, 1)) x2 = self.stem2a(x) x2 = F.pad(x2, (0, 1, 0, 1)) x2 = self.stem2b(x2) x1 = self.pool(x) x = torch.cat([x1, x2], dim=1) x = self.stem3(x) x = self.stem4(x) return x class HighPerfGpuBlock(nn.Module): def __init__( self, in_chs, mid_chs, out_chs, layer_num, kernel_size=3, residual=False, light_block=False, use_lab=False, agg='ese', drop_path=0., ): super().__init__() self.residual = residual self.layers = nn.ModuleList() for i in range(layer_num): if light_block: self.layers.append( LightConvBNAct( in_chs if i == 0 else mid_chs, mid_chs, kernel_size=kernel_size, use_lab=use_lab, ) ) else: self.layers.append( ConvBNAct( in_chs if i == 0 else mid_chs, mid_chs, kernel_size=kernel_size, stride=1, use_lab=use_lab, ) ) # feature aggregation total_chs = in_chs + layer_num * mid_chs if agg == 'se': aggregation_squeeze_conv = ConvBNAct( total_chs, out_chs // 2, kernel_size=1, stride=1, use_lab=use_lab, ) aggregation_excitation_conv = ConvBNAct( out_chs // 2, out_chs, kernel_size=1, stride=1, use_lab=use_lab, ) self.aggregation = nn.Sequential( aggregation_squeeze_conv, aggregation_excitation_conv, ) else: aggregation_conv = ConvBNAct( total_chs, out_chs, kernel_size=1, stride=1, use_lab=use_lab, ) att = EseModule(out_chs) self.aggregation = nn.Sequential( aggregation_conv, att, ) self.drop_path = DropPath(drop_path) if drop_path else nn.Identity() def forward(self, x): identity = x output = [x] for layer in self.layers: x = layer(x) output.append(x) x = torch.cat(output, dim=1) x = self.aggregation(x) if self.residual: x = self.drop_path(x) + identity return x class HighPerfGpuStage(nn.Module): def __init__( self, in_chs, mid_chs, out_chs, block_num, layer_num, downsample=True, stride=2, light_block=False, kernel_size=3, use_lab=False, agg='ese', drop_path=0., ): super().__init__() self.downsample = downsample if downsample: self.downsample = ConvBNAct( in_chs, in_chs, kernel_size=3, stride=stride, groups=in_chs, use_act=False, use_lab=use_lab, ) else: self.downsample = nn.Identity() blocks_list = [] for i in range(block_num): blocks_list.append( HighPerfGpuBlock( in_chs if i == 0 else out_chs, mid_chs, out_chs, layer_num, residual=False if i == 0 else True, kernel_size=kernel_size, light_block=light_block, use_lab=use_lab, agg=agg, drop_path=drop_path[i] if isinstance(drop_path, (list, tuple)) else drop_path, ) ) self.blocks = nn.Sequential(*blocks_list) self.grad_checkpointing= False def forward(self, x): x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x class ClassifierHead(nn.Module): def __init__( self, in_features: int, num_classes: int, pool_type: str = 'avg', drop_rate: float = 0., hidden_size: Optional[int] = 2048, use_lab: bool = False ): super(ClassifierHead, self).__init__() self.num_features = in_features if pool_type is not None: if not pool_type: assert num_classes == 0, 'Classifier head must be removed if pooling is disabled' self.global_pool = SelectAdaptivePool2d(pool_type=pool_type) if hidden_size is not None: self.num_features = hidden_size last_conv = nn.Conv2d( in_features, hidden_size, kernel_size=1, stride=1, padding=0, bias=False, ) act = nn.ReLU() if use_lab: lab = LearnableAffineBlock() self.last_conv = nn.Sequential(last_conv, act, lab) else: self.last_conv = nn.Sequential(last_conv, act) else: self.last_conv = nn.Identity() self.dropout = nn.Dropout(drop_rate) self.flatten = nn.Flatten(1) if pool_type else nn.Identity() # don't flatten if pooling disabled self.fc = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() def reset(self, num_classes: int, pool_type: Optional[str] = None): if pool_type is not None: if not pool_type: assert num_classes == 0, 'Classifier head must be removed if pooling is disabled' self.global_pool = SelectAdaptivePool2d(pool_type=pool_type) self.flatten = nn.Flatten(1) if pool_type else nn.Identity() # don't flatten if pooling disabled self.fc = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() def forward(self, x, pre_logits: bool = False): x = self.global_pool(x) x = self.last_conv(x) x = self.dropout(x) x = self.flatten(x) if pre_logits: return x x = self.fc(x) return x class HighPerfGpuNet(nn.Module): def __init__( self, cfg: Dict, in_chans: int = 3, num_classes: int = 1000, global_pool: str = 'avg', head_hidden_size: Optional[int] = 2048, drop_rate: float = 0., drop_path_rate: float = 0., use_lab: bool = False, **kwargs, ): super(HighPerfGpuNet, self).__init__() stem_type = cfg["stem_type"] stem_chs = cfg["stem_chs"] stages_cfg = [cfg["stage1"], cfg["stage2"], cfg["stage3"], cfg["stage4"]] self.num_classes = num_classes self.drop_rate = drop_rate self.use_lab = use_lab assert stem_type in ['v1', 'v2'] if stem_type == 'v2': self.stem = StemV2( in_chs=in_chans, mid_chs=stem_chs[0], out_chs=stem_chs[1], use_lab=use_lab) else: self.stem = StemV1([in_chans] + stem_chs) current_stride = 4 stages = [] self.feature_info = [] block_depths = [c[3] for c in stages_cfg] dpr = [x.tolist() for x in torch.linspace(0, drop_path_rate, sum(block_depths)).split(block_depths)] for i, stage_config in enumerate(stages_cfg): in_chs, mid_chs, out_chs, block_num, downsample, light_block, kernel_size, layer_num = stage_config stages += [HighPerfGpuStage( in_chs=in_chs, mid_chs=mid_chs, out_chs=out_chs, block_num=block_num, layer_num=layer_num, downsample=downsample, light_block=light_block, kernel_size=kernel_size, use_lab=use_lab, agg='ese' if stem_type == 'v1' else 'se', drop_path=dpr[i], )] self.num_features = out_chs if downsample: current_stride *= 2 self.feature_info += [dict(num_chs=self.num_features, reduction=current_stride, module=f'stages.{i}')] self.stages = nn.Sequential(*stages) self.head = ClassifierHead( self.num_features, num_classes=num_classes, pool_type=global_pool, drop_rate=drop_rate, hidden_size=head_hidden_size, use_lab=use_lab ) self.head_hidden_size = self.head.num_features for n, m in self.named_modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, nn.BatchNorm2d): nn.init.ones_(m.weight) nn.init.zeros_(m.bias) elif isinstance(m, nn.Linear): nn.init.zeros_(m.bias) @torch.jit.ignore def group_matcher(self, coarse=False): return dict( stem=r'^stem', blocks=r'^stages\.(\d+)' if coarse else r'^stages\.(\d+).blocks\.(\d+)', ) @torch.jit.ignore def set_grad_checkpointing(self, enable=True): for s in self.stages: s.grad_checkpointing = enable @torch.jit.ignore def get_classifier(self) -> nn.Module: return self.head.fc def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None): self.num_classes = num_classes self.head.reset(num_classes, global_pool) def forward_intermediates( self, x: torch.Tensor, indices: Optional[Union[int, List[int]]] = None, norm: bool = False, stop_early: bool = False, output_fmt: str = 'NCHW', intermediates_only: bool = False, ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]: """ Forward features that returns intermediates. Args: x: Input image tensor indices: Take last n blocks if int, all if None, select matching indices if sequence norm: Apply norm layer to compatible intermediates stop_early: Stop iterating over blocks when last desired intermediate hit output_fmt: Shape of intermediate feature outputs intermediates_only: Only return intermediate features Returns: """ assert output_fmt in ('NCHW',), 'Output shape must be NCHW.' intermediates = [] take_indices, max_index = feature_take_indices(len(self.stages), indices) # forward pass x = self.stem(x) if torch.jit.is_scripting() or not stop_early: # can't slice blocks in torchscript stages = self.stages else: stages = self.stages[:max_index + 1] for feat_idx, stage in enumerate(stages): x = stage(x) if feat_idx in take_indices: intermediates.append(x) if intermediates_only: return intermediates return x, intermediates def prune_intermediate_layers( self, indices: Union[int, List[int]] = 1, prune_norm: bool = False, prune_head: bool = True, ): """ Prune layers not required for specified intermediates. """ take_indices, max_index = feature_take_indices(len(self.stages), indices) self.stages = self.stages[:max_index + 1] # truncate blocks w/ stem as idx 0 if prune_head: self.reset_classifier(0, 'avg') return take_indices def forward_features(self, x): x = self.stem(x) return self.stages(x) def forward_head(self, x, pre_logits: bool = False): return self.head(x, pre_logits=pre_logits) if pre_logits else self.head(x) def forward(self, x): x = self.forward_features(x) x = self.forward_head(x) return x model_cfgs = dict( # PP-HGNet hgnet_tiny={ "stem_type": 'v1', "stem_chs": [48, 48, 96], # in_chs, mid_chs, out_chs, blocks, downsample, light_block, kernel_size, layer_num "stage1": [96, 96, 224, 1, False, False, 3, 5], "stage2": [224, 128, 448, 1, True, False, 3, 5], "stage3": [448, 160, 512, 2, True, False, 3, 5], "stage4": [512, 192, 768, 1, True, False, 3, 5], }, hgnet_small={ "stem_type": 'v1', "stem_chs": [64, 64, 128], # in_chs, mid_chs, out_chs, blocks, downsample, light_block, kernel_size, layer_num "stage1": [128, 128, 256, 1, False, False, 3, 6], "stage2": [256, 160, 512, 1, True, False, 3, 6], "stage3": [512, 192, 768, 2, True, False, 3, 6], "stage4": [768, 224, 1024, 1, True, False, 3, 6], }, hgnet_base={ "stem_type": 'v1', "stem_chs": [96, 96, 160], # in_chs, mid_chs, out_chs, blocks, downsample, light_block, kernel_size, layer_num "stage1": [160, 192, 320, 1, False, False, 3, 7], "stage2": [320, 224, 640, 2, True, False, 3, 7], "stage3": [640, 256, 960, 3, True, False, 3, 7], "stage4": [960, 288, 1280, 2, True, False, 3, 7], }, # PP-HGNetv2 hgnetv2_b0={ "stem_type": 'v2', "stem_chs": [16, 16], # in_chs, mid_chs, out_chs, blocks, downsample, light_block, kernel_size, layer_num "stage1": [16, 16, 64, 1, False, False, 3, 3], "stage2": [64, 32, 256, 1, True, False, 3, 3], "stage3": [256, 64, 512, 2, True, True, 5, 3], "stage4": [512, 128, 1024, 1, True, True, 5, 3], }, hgnetv2_b1={ "stem_type": 'v2', "stem_chs": [24, 32], # in_chs, mid_chs, out_chs, blocks, downsample, light_block, kernel_size, layer_num "stage1": [32, 32, 64, 1, False, False, 3, 3], "stage2": [64, 48, 256, 1, True, False, 3, 3], "stage3": [256, 96, 512, 2, True, True, 5, 3], "stage4": [512, 192, 1024, 1, True, True, 5, 3], }, hgnetv2_b2={ "stem_type": 'v2', "stem_chs": [24, 32], # in_chs, mid_chs, out_chs, blocks, downsample, light_block, kernel_size, layer_num "stage1": [32, 32, 96, 1, False, False, 3, 4], "stage2": [96, 64, 384, 1, True, False, 3, 4], "stage3": [384, 128, 768, 3, True, True, 5, 4], "stage4": [768, 256, 1536, 1, True, True, 5, 4], }, hgnetv2_b3={ "stem_type": 'v2', "stem_chs": [24, 32], # in_chs, mid_chs, out_chs, blocks, downsample, light_block, kernel_size, layer_num "stage1": [32, 32, 128, 1, False, False, 3, 5], "stage2": [128, 64, 512, 1, True, False, 3, 5], "stage3": [512, 128, 1024, 3, True, True, 5, 5], "stage4": [1024, 256, 2048, 1, True, True, 5, 5], }, hgnetv2_b4={ "stem_type": 'v2', "stem_chs": [32, 48], # in_chs, mid_chs, out_chs, blocks, downsample, light_block, kernel_size, layer_num "stage1": [48, 48, 128, 1, False, False, 3, 6], "stage2": [128, 96, 512, 1, True, False, 3, 6], "stage3": [512, 192, 1024, 3, True, True, 5, 6], "stage4": [1024, 384, 2048, 1, True, True, 5, 6], }, hgnetv2_b5={ "stem_type": 'v2', "stem_chs": [32, 64], # in_chs, mid_chs, out_chs, blocks, downsample, light_block, kernel_size, layer_num "stage1": [64, 64, 128, 1, False, False, 3, 6], "stage2": [128, 128, 512, 2, True, False, 3, 6], "stage3": [512, 256, 1024, 5, True, True, 5, 6], "stage4": [1024, 512, 2048, 2, True, True, 5, 6], }, hgnetv2_b6={ "stem_type": 'v2', "stem_chs": [48, 96], # in_chs, mid_chs, out_chs, blocks, downsample, light_block, kernel_size, layer_num "stage1": [96, 96, 192, 2, False, False, 3, 6], "stage2": [192, 192, 512, 3, True, False, 3, 6], "stage3": [512, 384, 1024, 6, True, True, 5, 6], "stage4": [1024, 768, 2048, 3, True, True, 5, 6], }, ) def _create_hgnet(variant, pretrained=False, **kwargs): out_indices = kwargs.pop('out_indices', (0, 1, 2, 3)) return build_model_with_cfg( HighPerfGpuNet, variant, pretrained, model_cfg=model_cfgs[variant], feature_cfg=dict(flatten_sequential=True, out_indices=out_indices), **kwargs, ) def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7), 'crop_pct': 0.965, 'interpolation': 'bicubic', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'classifier': 'head.fc', 'first_conv': 'stem.stem1.conv', 'test_crop_pct': 1.0, 'test_input_size': (3, 288, 288), **kwargs, } default_cfgs = generate_default_cfgs({ 'hgnet_tiny.paddle_in1k': _cfg( first_conv='stem.stem.0.conv', hf_hub_id='timm/'), 'hgnet_tiny.ssld_in1k': _cfg( first_conv='stem.stem.0.conv', hf_hub_id='timm/'), 'hgnet_small.paddle_in1k': _cfg( first_conv='stem.stem.0.conv', hf_hub_id='timm/'), 'hgnet_small.ssld_in1k': _cfg( first_conv='stem.stem.0.conv', hf_hub_id='timm/'), 'hgnet_base.ssld_in1k': _cfg( first_conv='stem.stem.0.conv', hf_hub_id='timm/'), 'hgnetv2_b0.ssld_stage2_ft_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b0.ssld_stage1_in22k_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b1.ssld_stage2_ft_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b1.ssld_stage1_in22k_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b2.ssld_stage2_ft_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b2.ssld_stage1_in22k_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b3.ssld_stage2_ft_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b3.ssld_stage1_in22k_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b4.ssld_stage2_ft_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b4.ssld_stage1_in22k_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b5.ssld_stage2_ft_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b5.ssld_stage1_in22k_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b6.ssld_stage2_ft_in1k': _cfg( hf_hub_id='timm/'), 'hgnetv2_b6.ssld_stage1_in22k_in1k': _cfg( hf_hub_id='timm/'), }) @register_model def hgnet_tiny(pretrained=False, **kwargs) -> HighPerfGpuNet: return _create_hgnet('hgnet_tiny', pretrained=pretrained, **kwargs) @register_model def hgnet_small(pretrained=False, **kwargs) -> HighPerfGpuNet: return _create_hgnet('hgnet_small', pretrained=pretrained, **kwargs) @register_model def hgnet_base(pretrained=False, **kwargs) -> HighPerfGpuNet: return _create_hgnet('hgnet_base', pretrained=pretrained, **kwargs) @register_model def hgnetv2_b0(pretrained=False, **kwargs) -> HighPerfGpuNet: return _create_hgnet('hgnetv2_b0', pretrained=pretrained, use_lab=True, **kwargs) @register_model def hgnetv2_b1(pretrained=False, **kwargs) -> HighPerfGpuNet: return _create_hgnet('hgnetv2_b1', pretrained=pretrained, use_lab=True, **kwargs) @register_model def hgnetv2_b2(pretrained=False, **kwargs) -> HighPerfGpuNet: return _create_hgnet('hgnetv2_b2', pretrained=pretrained, use_lab=True, **kwargs) @register_model def hgnetv2_b3(pretrained=False, **kwargs) -> HighPerfGpuNet: return _create_hgnet('hgnetv2_b3', pretrained=pretrained, use_lab=True, **kwargs) @register_model def hgnetv2_b4(pretrained=False, **kwargs) -> HighPerfGpuNet: return _create_hgnet('hgnetv2_b4', pretrained=pretrained, **kwargs) @register_model def hgnetv2_b5(pretrained=False, **kwargs) -> HighPerfGpuNet: return _create_hgnet('hgnetv2_b5', pretrained=pretrained, **kwargs) @register_model def hgnetv2_b6(pretrained=False, **kwargs) -> HighPerfGpuNet: return _create_hgnet('hgnetv2_b6', pretrained=pretrained, **kwargs)
pytorch-image-models/timm/models/hgnet.py/0
{ "file_path": "pytorch-image-models/timm/models/hgnet.py", "repo_id": "pytorch-image-models", "token_count": 14129 }
266
from functools import partial from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import ( SelectAdaptivePool2d, Linear, LayerType, RmsNorm2d, ConvNormAct, create_conv2d, get_norm_layer, get_norm_act_layer, to_2tuple, ) from ._builder import build_model_with_cfg from ._efficientnet_blocks import SqueezeExcite, UniversalInvertedResidual from ._efficientnet_builder import ( BlockArgs, EfficientNetBuilder, decode_arch_def, efficientnet_init_weights, round_channels, ) from ._features import feature_take_indices from ._features_fx import register_notrace_module from ._manipulate import checkpoint_seq from ._registry import generate_default_cfgs, register_model __all__ = ['MobileNetV5', 'MobileNetV5Encoder'] _GELU = partial(nn.GELU, approximate='tanh') @register_notrace_module class MobileNetV5MultiScaleFusionAdapter(nn.Module): """Multi-layer fusion token adapter. Args: in_chs: List of input channel counts for each feature scale. out_chs: The number of output channels. output_resolution: The output resolution. expansion_ratio: The FFN expansion ratio. interpolation_mode: The upsampling interpolation mode. layer_scale_init_value: The initial value of the layer scale, no layer scale if None. """ def __init__( self, in_chs: Union[int, List[int]], out_chs: int, output_resolution: int, expansion_ratio: float = 2.0, interpolation_mode: str = "nearest", layer_scale_init_value: Optional[float] = None, noskip: bool = True, act_layer: Optional[LayerType] = None, norm_layer: Optional[LayerType] = None, ): super().__init__() self.in_channels = sum(in_chs) if isinstance(in_chs, Sequence) else in_chs self.out_channels = out_chs self.output_resolution = to_2tuple(output_resolution) self.expansion_ratio = expansion_ratio self.interpolation_mode = interpolation_mode self.layer_scale_init_value = layer_scale_init_value self.noskip = noskip act_layer = act_layer or _GELU norm_layer = norm_layer or RmsNorm2d self.ffn = UniversalInvertedResidual( in_chs=self.in_channels, out_chs=self.out_channels, dw_kernel_size_mid=0, exp_ratio=self.expansion_ratio, act_layer=act_layer, norm_layer=norm_layer, noskip=self.noskip, layer_scale_init_value=self.layer_scale_init_value, ) self.norm = norm_layer(self.out_channels) def forward(self, inputs: List[torch.Tensor]) -> torch.Tensor: # Inputs list of [B, C, H, W] tensors high_resolution = inputs[0].shape[-2:] # Assuming the first input is the highest resolution. resized_inputs = [] for _, img in enumerate(inputs): feat_size = img.shape[-2:] if feat_size[0] < high_resolution[0] or feat_size[1] < high_resolution[1]: img = F.interpolate(img, size=high_resolution, mode=self.interpolation_mode) resized_inputs.append(img) channel_cat_imgs = torch.cat(resized_inputs, dim=1) # Cat on channel dim, must equal self.in_channels img = self.ffn(channel_cat_imgs) if high_resolution[0] != self.output_resolution[0] or high_resolution[1] != self.output_resolution[1]: # Interpolate / pool to target output_resolution if highest feature resolution differs if ( high_resolution[0] % self.output_resolution[0] != 0 or high_resolution[1] % self.output_resolution[1] != 0 ): img = F.interpolate(img, size=self.output_resolution, mode="bilinear") else: h_strides = high_resolution[0] // self.output_resolution[0] w_strides = high_resolution[1] // self.output_resolution[1] img = F.avg_pool2d( img, kernel_size=(h_strides, w_strides), stride=(h_strides, w_strides), ) img = self.norm(img) return img class MobileNetV5(nn.Module): """ MobiletNet-V5 """ def __init__( self, block_args: BlockArgs, num_classes: int = 1000, in_chans: int = 3, stem_size: int = 16, stem_bias: bool = True, fix_stem: bool = False, num_features: int = 2048, pad_type: str = '', use_msfa: bool = True, msfa_indices: List[int] = (-2, -1), msfa_output_resolution: int = 16, act_layer: Optional[LayerType] = None, norm_layer: Optional[LayerType] = None, aa_layer: Optional[LayerType] = None, se_layer: Optional[LayerType] = None, se_from_exp: bool = True, round_chs_fn: Callable = round_channels, drop_rate: float = 0., drop_path_rate: float = 0., layer_scale_init_value: Optional[float] = None, global_pool: str = 'avg', ): """ Args: block_args: Arguments for blocks of the network. num_classes: Number of classes for classification head. in_chans: Number of input image channels. stem_size: Number of output channels of the initial stem convolution. fix_stem: If True, don't scale stem by round_chs_fn. num_features: Number of output channels of the conv head layer. head_bias: If True, add a learnable bias to the conv head layer. pad_type: Type of padding to use for convolution layers. act_layer: Type of activation layer. norm_layer: Type of normalization layer. aa_layer: Type of anti-aliasing layer. se_layer: Type of Squeeze-and-Excite layer. se_from_exp: If True, calculate SE channel reduction from expanded mid channels. round_chs_fn: Callable to round number of filters based on depth multiplier. drop_rate: Dropout rate. drop_path_rate: Stochastic depth rate. layer_scale_init_value: Enable layer scale on compatible blocks if not None. global_pool: Type of pooling to use for global pooling features of the FC head. """ super().__init__() act_layer = act_layer or _GELU norm_layer = get_norm_layer(norm_layer) or RmsNorm2d norm_act_layer = get_norm_act_layer(norm_layer, act_layer) se_layer = se_layer or SqueezeExcite self.num_classes = num_classes self.drop_rate = drop_rate self.grad_checkpointing = False self.msfa_indices = msfa_indices self.msfa_output_resolution = msfa_output_resolution # Stem if not fix_stem: stem_size = round_chs_fn(stem_size) self.conv_stem = ConvNormAct( in_chans, stem_size, kernel_size=3, stride=2, padding=pad_type, bias=stem_bias, norm_layer=norm_layer, act_layer=act_layer, ) # Middle stages (IR/ER/DS Blocks) builder = EfficientNetBuilder( output_stride=32, pad_type=pad_type, round_chs_fn=round_chs_fn, se_from_exp=se_from_exp, act_layer=act_layer, norm_layer=norm_layer, aa_layer=aa_layer, se_layer=se_layer, drop_path_rate=drop_path_rate, layer_scale_init_value=layer_scale_init_value, ) self.blocks = nn.Sequential(*builder(stem_size, block_args)) self.feature_info = builder.features self.stage_ends = [f['stage'] for f in self.feature_info] self.num_features = builder.in_chs # features of last stage, output of forward_features() # Neck (aggregation) + Head + Pooling if use_msfa: self.num_features = self.head_hidden_size = num_features # output of msfa is output of forward_features() # Map msfa indices to feature info and calculate sum of feature channels self.msfa_indices = feature_take_indices(len(self.feature_info), self.msfa_indices)[0] self.msfa_in_chs = sum([self.feature_info[mi]['num_chs'] for mi in self.msfa_indices]) self.msfa = MobileNetV5MultiScaleFusionAdapter( in_chs=self.msfa_in_chs, out_chs=num_features, output_resolution=self.msfa_output_resolution, norm_layer=norm_layer, act_layer=act_layer, ) self.global_pool = SelectAdaptivePool2d(pool_type=global_pool) self.conv_head = None self.norm_head = None else: self.num_features = builder.in_chs # features of last stage, output of forward_features() self.head_hidden_size = num_features self.msfa = None self.global_pool = SelectAdaptivePool2d(pool_type=global_pool) num_pooled_chs = self.num_features * self.global_pool.feat_mult() # mobilenet-v4 style post-pooling PW conv is followed by a norm+act layer self.conv_head = create_conv2d(num_pooled_chs, self.head_hidden_size, 1, padding=pad_type) self.norm_head = norm_act_layer(self.head_hidden_size) self.flatten = nn.Flatten(1) if global_pool else nn.Identity() # don't flatten if pooling disabled self.classifier = Linear(self.head_hidden_size, num_classes) if num_classes > 0 else nn.Identity() efficientnet_init_weights(self) def as_sequential(self): layers = [self.conv_stem, self.bn1] layers.extend(self.blocks) layers.append(self.global_pool) if self.conv_head is not None: layers.append(self.conv_head) if self.norm_head is not None: layers.append(self.norm_head) layers.extend([nn.Flatten(), nn.Dropout(self.drop_rate), self.classifier]) return nn.Sequential(*layers) @torch.jit.ignore def group_matcher(self, coarse: bool = False): return dict( stem=r'^conv_stem|bn1', blocks=r'^blocks\.(\d+)' if coarse else r'^blocks\.(\d+)\.(\d+)' ) @torch.jit.ignore def set_grad_checkpointing(self, enable: bool = True): self.grad_checkpointing = enable @torch.jit.ignore def get_classifier(self) -> nn.Module: return self.classifier def reset_classifier(self, num_classes: int, global_pool: str = 'avg'): self.num_classes = num_classes # NOTE: cannot meaningfully change pooling of efficient head after creation self.global_pool = SelectAdaptivePool2d(pool_type=global_pool) self.flatten = nn.Flatten(1) if global_pool else nn.Identity() # don't flatten if pooling disabled self.classifier = Linear(self.head_hidden_size, num_classes) if num_classes > 0 else nn.Identity() def forward_intermediates( self, x: torch.Tensor, indices: Optional[Union[int, List[int]]] = None, norm: bool = False, stop_early: bool = False, output_fmt: str = 'NCHW', intermediates_only: bool = False, extra_blocks: bool = False, ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]: """ Forward features that returns intermediates. Args: x: Input image tensor indices: Take last n blocks if int, all if None, select matching indices if sequence norm: Apply norm layer to compatible intermediates stop_early: Stop iterating over blocks when last desired intermediate hit output_fmt: Shape of intermediate feature outputs intermediates_only: Only return intermediate features extra_blocks: Include outputs of all blocks and head conv in output, does not align with feature_info Returns: """ assert output_fmt in ('NCHW',), 'Output shape must be NCHW.' if stop_early: assert intermediates_only, 'Must use intermediates_only for early stopping.' intermediates = [] if extra_blocks: take_indices, max_index = feature_take_indices(len(self.blocks) + 1, indices) else: take_indices, max_index = feature_take_indices(len(self.stage_ends), indices) take_indices = [self.stage_ends[i] for i in take_indices] max_index = self.stage_ends[max_index] # FIXME MFSA and forward_intermediates overlap, they both take indices from specific features # When a user wants to grab specific feature maps for a downstream task AND have the msfa output # what should we do? Accumulate two intermediates? One for msfa and one for take_indices? # forward pass feat_idx = 0 # stem is index 0 x = self.conv_stem(x) if feat_idx in take_indices: intermediates.append(x) if torch.jit.is_scripting() or not stop_early: # can't slice blocks in torchscript blocks = self.blocks else: blocks = self.blocks[:max_index] for blk in blocks: feat_idx += 1 x = blk(x) if feat_idx in take_indices: intermediates.append(x) if intermediates_only: return intermediates # FIXME see note above # self.msfa(msfa_intermediatse) return x, intermediates def prune_intermediate_layers( self, indices: Union[int, List[int]] = 1, prune_norm: bool = False, prune_head: bool = True, extra_blocks: bool = False, ): """ Prune layers not required for specified intermediates. """ if extra_blocks: take_indices, max_index = feature_take_indices(len(self.blocks) + 1, indices) else: take_indices, max_index = feature_take_indices(len(self.stage_ends), indices) max_index = self.stage_ends[max_index] self.blocks = self.blocks[:max_index] # truncate blocks w/ stem as idx 0 if max_index < len(self.blocks): self.conv_head = None self.norm_head = None if prune_head: self.conv_head = None self.norm_head = None self.reset_classifier(0, '') return take_indices def forward_features(self, x: torch.Tensor) -> torch.Tensor: if self.msfa is not None: # When MSFA aggregation layer is present, we gather intermediates as is forward_intermediates feat_idx = 0 # offset by one from blocks index due to stem feature intermediates = [] x = self.conv_stem(x) if feat_idx in self.msfa_indices: intermediates.append(x) for blk in self.blocks: feat_idx += 1 # FIXME fix grad checkpointing x = blk(x) if feat_idx in self.msfa_indices: intermediates.append(x) x = self.msfa(intermediates) else: x = self.conv_stem(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x, flatten=True) else: x = self.blocks(x) return x def forward_head(self, x: torch.Tensor, pre_logits: bool = False) -> torch.Tensor: x = self.global_pool(x) if self.conv_head is not None: x = self.conv_head(x) if self.norm_head is not None: x = self.norm_head(x) x = self.flatten(x) if self.drop_rate > 0.: x = F.dropout(x, p=self.drop_rate, training=self.training) if pre_logits: return x return self.classifier(x) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.forward_features(x) x = self.forward_head(x) return x class MobileNetV5Encoder(nn.Module): """MobileNetV5 Vision Encoder""" def __init__( self, block_args: BlockArgs, in_chans: int = 3, stem_size: int = 64, stem_bias: bool = True, fix_stem: bool = False, pad_type: str = '', msfa_indices: Sequence[int] = (-2, -1), msfa_output_resolution: int = 16, act_layer: Optional[LayerType] = None, norm_layer: Optional[LayerType] = None, aa_layer: Optional[LayerType] = None, se_layer: Optional[LayerType] = None, se_from_exp: bool = True, round_chs_fn: Callable = round_channels, drop_rate: float = 0., drop_path_rate: float = 0., layer_scale_init_value: Optional[float] = None, ): super().__init__() act_layer = act_layer or _GELU norm_layer = get_norm_layer(norm_layer) or RmsNorm2d se_layer = se_layer or SqueezeExcite self.num_classes = 0 # Exists to satisfy ._hub module APIs. self.drop_rate = drop_rate self.grad_checkpointing = False # Stem if not fix_stem: stem_size = round_chs_fn(stem_size) self.conv_stem = ConvNormAct( in_chans, stem_size, kernel_size=3, stride=2, padding=pad_type, bias=stem_bias, norm_layer=norm_layer, act_layer=act_layer, ) builder = EfficientNetBuilder( output_stride=32, pad_type=pad_type, round_chs_fn=round_chs_fn, se_from_exp=se_from_exp, act_layer=act_layer, norm_layer=norm_layer, aa_layer=aa_layer, se_layer=se_layer, drop_path_rate=drop_path_rate, layer_scale_init_value=layer_scale_init_value, ) self.blocks = nn.Sequential(*builder(stem_size, block_args)) self.feature_info = builder.features self.stage_ends = [f['stage'] for f in self.feature_info] self.num_features = self.head_hidden_size = 2048 # output of msfa is output of forward_features() # Map msfa indices to feature info and calculate sum of feature channels self.msfa_indices = feature_take_indices(len(self.feature_info), msfa_indices)[0] self.msfa_in_chs = sum([self.feature_info[mi]['num_chs'] for mi in self.msfa_indices]) self.msfa_output_resolution = msfa_output_resolution self.msfa = MobileNetV5MultiScaleFusionAdapter( in_chs=self.msfa_in_chs, out_chs=self.num_features, output_resolution=self.msfa_output_resolution, norm_layer=norm_layer, act_layer=act_layer, ) efficientnet_init_weights(self) def forward_intermediates( self, x: torch.Tensor, indices: Optional[Union[int, List[int]]] = None, norm: bool = False, stop_early: bool = False, output_fmt: str = 'NCHW', intermediates_only: bool = False, extra_blocks: bool = False, ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]: """ Forward features that returns intermediates. Args: x: Input image tensor indices: Take last n blocks if int, all if None, select matching indices if sequence norm: (Unused) Applies norm layer to compatible intermediates stop_early: Stop iterating over blocks when last desired intermediate hit output_fmt: Shape of intermediate feature outputs intermediates_only: Only return intermediate features extra_blocks: Include outputs of all blocks and head conv in output, does not align with feature_info Returns: """ del norm assert output_fmt in ('NCHW',), 'Output shape must be NCHW.' if stop_early: assert intermediates_only, 'Must use intermediates_only for early stopping.' # MobileNet v5's MultiScaleFusionAdapter takes intermediates from specific feature indicies and uses them in # its computation. These MSFA indices are not guaranteed to be captured by the `indices` parameter passed to # this function, so we accumulate two sets of indices, one that aligns with the `indices` parameter and one # that is required by the MSFA block. intermediates = [] msfa_intermediates = [] if extra_blocks: take_indices, max_index = feature_take_indices(len(self.blocks) + 1, indices) else: take_indices, max_index = feature_take_indices(len(self.stage_ends), indices) take_indices = [self.stage_ends[i] for i in take_indices] max_index = self.stage_ends[max_index] # forward pass feat_idx = 0 # stem is index 0 x = self.conv_stem(x) if feat_idx in take_indices: intermediates.append(x) if feat_idx in self.msfa_indices: msfa_intermediates.append(x) if torch.jit.is_scripting() or not stop_early: # can't slice blocks in torchscript blocks = self.blocks else: blocks = self.blocks[:max_index] for blk in blocks: feat_idx += 1 x = blk(x) if feat_idx in take_indices: intermediates.append(x) if feat_idx in self.msfa_indices: msfa_intermediates.append(x) if intermediates_only: return intermediates return self.msfa(msfa_intermediates), intermediates def forward_features(self, x: torch.Tensor) -> torch.Tensor: feat_idx = 0 # offset by one from blocks index due to stem feature intermediates = [] x = self.conv_stem(x) if feat_idx in self.msfa_indices: intermediates.append(x) for blk in self.blocks: feat_idx += 1 # FIXME fix grad checkpointing x = blk(x) if feat_idx in self.msfa_indices: intermediates.append(x) return self.msfa(intermediates) def forward_head(self, x: torch.Tensor) -> torch.Tensor: raise NotImplementedError("MobileNetV5Encoder does not support classification use cases.") def forward(self, x: torch.Tensor) -> torch.Tensor: return self.forward_features(x) def checkpoint_filter_fn( state_dict: Dict[str, torch.Tensor], model, ) -> Dict[str, torch.Tensor]: """ convert weights from gemma encoders """ state_dict = state_dict.get('model', state_dict) state_dict = state_dict.get('state_dict', state_dict) if 'model.vision_tower.timm_model.conv_stem.conv.weight' in state_dict: prefix = 'model.vision_tower.timm_model.' state_dict = {k.replace(prefix, ''): v for k, v in state_dict.items() if prefix in k} return state_dict def _create_mnv5_encoder(variant: str, pretrained: bool = False, **kwargs) -> MobileNetV5Encoder: out_indices = kwargs.pop('out_indices', (0, 1, 2, 3, 4)) feature_cfg = dict(out_indices=out_indices, feature_cls='getter') kwargs_filter = ( 'num_classes', 'num_features', 'head_conv', 'head_bias', 'head_norm', 'global_pool', ) model = build_model_with_cfg( MobileNetV5Encoder, variant, pretrained, pretrained_strict=False, pretrained_filter_fn=checkpoint_filter_fn, feature_cfg=feature_cfg, kwargs_filter=kwargs_filter, **kwargs, ) return model def _create_mnv5(variant: str, pretrained: bool = False, **kwargs) -> MobileNetV5: out_indices = kwargs.pop('out_indices', (0, 1, 2, 3, 4)) feature_cfg = dict(out_indices=out_indices, feature_cls='getter') model = build_model_with_cfg( MobileNetV5, variant, pretrained, pretrained_filter_fn=checkpoint_filter_fn, feature_cfg=feature_cfg, **kwargs, ) return model def _gen_mobilenet_v5( variant: str, channel_multiplier: float = 1.0, group_size=None, pretrained: bool = False, encoder: bool = False, **kwargs, ) -> MobileNetV5Encoder: if 'mobilenetv5_base' in variant: arch_def: list[list[str]] = [ # Stage 0: 128x128 in [ 'er_r1_k3_s2_e4_c128', 'er_r1_k3_s1_e4_c128', 'er_r1_k3_s1_e4_c128', ], # Stage 1: 256x256 in [ 'uir_r1_a3_k5_s2_e6_c256', 'uir_r1_a5_k0_s1_e4_c256', 'uir_r1_a3_k0_s1_e4_c256', 'uir_r1_a5_k0_s1_e4_c256', 'uir_r1_a3_k0_s1_e4_c256', ], # Stage 2: 640x640 in [ "uir_r1_a5_k5_s2_e6_c512", "uir_r1_a5_k0_s1_e4_c512", "uir_r1_a5_k0_s1_e4_c512", "uir_r1_a0_k0_s1_e1_c512", 'mqa_r1_k3_h8_s2_d64_c512', "uir_r1_a0_k0_s1_e2_c512", 'mqa_r1_k3_h8_s2_d64_c512', "uir_r1_a0_k0_s1_e2_c512", 'mqa_r1_k3_h8_s2_d64_c512', "uir_r1_a0_k0_s1_e2_c512", 'mqa_r1_k3_h8_s2_d64_c512', "uir_r1_a0_k0_s1_e2_c512", 'mqa_r1_k3_h8_s2_d64_c512', "uir_r1_a0_k0_s1_e2_c512", 'mqa_r1_k3_h8_s2_d64_c512', "uir_r1_a0_k0_s1_e2_c512", ], # Stage 3: 1280x1280 in [ "uir_r1_a5_k5_s2_e6_c1024", 'mqa_r1_k3_h16_s1_d64_c1024', "uir_r1_a0_k0_s1_e2_c1024", 'mqa_r1_k3_h16_s1_d64_c1024', "uir_r1_a0_k0_s1_e2_c1024", 'mqa_r1_k3_h16_s1_d64_c1024', "uir_r1_a0_k0_s1_e2_c1024", 'mqa_r1_k3_h16_s1_d64_c1024', "uir_r1_a0_k0_s1_e2_c1024", 'mqa_r1_k3_h16_s1_d64_c1024', "uir_r1_a0_k0_s1_e2_c1024", 'mqa_r1_k3_h16_s1_d64_c1024', "uir_r1_a0_k0_s1_e2_c1024", 'mqa_r1_k3_h16_s1_d64_c1024', "uir_r1_a0_k0_s1_e2_c1024", ], ] else: arch_def: list[list[str]] = [ # Stage 0: 128x128 in [ 'er_r1_k3_s2_e4_c128', 'er_r1_k3_s1_e4_c128', 'er_r1_k3_s1_e4_c128', ], # Stage 1: 256x256 in [ 'uir_r1_a3_k5_s2_e6_c256', 'uir_r1_a5_k0_s1_e4_c256', 'uir_r1_a3_k0_s1_e4_c256', 'uir_r1_a5_k0_s1_e4_c256', 'uir_r1_a3_k0_s1_e4_c256', ], # Stage 2: 640x640 in [ "uir_r1_a5_k5_s2_e6_c640", "uir_r1_a5_k0_s1_e4_c640", "uir_r1_a5_k0_s1_e4_c640", "uir_r1_a5_k0_s1_e4_c640", "uir_r1_a5_k0_s1_e4_c640", "uir_r1_a5_k0_s1_e4_c640", "uir_r1_a5_k0_s1_e4_c640", "uir_r1_a5_k0_s1_e4_c640", "uir_r1_a0_k0_s1_e1_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", "mqa_r1_k3_h12_v2_s1_d64_c640", "uir_r1_a0_k0_s1_e2_c640", ], # Stage 3: 1280x1280 in [ "uir_r1_a5_k5_s2_e6_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", "mqa_r1_k3_h16_s1_d96_c1280", "uir_r1_a0_k0_s1_e2_c1280", ], ] model_kwargs = dict( block_args=decode_arch_def(arch_def, group_size=group_size), stem_size=64, fix_stem=channel_multiplier < 1.0, round_chs_fn=partial(round_channels, multiplier=channel_multiplier), norm_layer=RmsNorm2d, act_layer=_GELU, layer_scale_init_value=1e-5, ) model_kwargs = dict(model_kwargs, **kwargs) if encoder: model = _create_mnv5_encoder(variant, pretrained, **model_kwargs) else: model = _create_mnv5(variant, pretrained, **model_kwargs) return model def _cfg(url: str = '', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 256, 256), 'pool_size': (16, 16), 'crop_pct': 1.0, 'interpolation': 'bicubic', 'mean': IMAGENET_INCEPTION_MEAN, 'std': IMAGENET_INCEPTION_STD, 'first_conv': 'conv_stem.conv', 'classifier': 'classifier', **kwargs } default_cfgs = generate_default_cfgs({ # Encoder-only config for Gemma 3n Transformers integration 'mobilenetv5_300m_enc': _cfg( mean=(0., 0., 0.), std=(1., 1., 1.), input_size=(3, 768, 768), num_classes=0), # Gemma 3n encoder weights for timm use / fine-tune 'mobilenetv5_300m.gemma3n': _cfg( hf_hub_id='timm/', mean=(0., 0., 0.), std=(1., 1., 1.), input_size=(3, 768, 768), num_classes=0), # WIP classification configs for testing 'mobilenetv5_base.untrained': _cfg( # hf_hub_id='timm/', num_classes=1000) }) @register_model def mobilenetv5_300m_enc(pretrained: bool = False, **kwargs) -> MobileNetV5Encoder: """MobileNet V5 Vision Encoder""" pad_type = kwargs.pop('pad_type', 'same') model = _gen_mobilenet_v5( 'mobilenetv5_300m_enc', pretrained=pretrained, encoder=True, pad_type=pad_type, **kwargs, ) return model @register_model def mobilenetv5_300m(pretrained: bool = False, **kwargs) -> MobileNetV5: model = _gen_mobilenet_v5('mobilenetv5_300m', pretrained=pretrained, **kwargs) return model @register_model def mobilenetv5_base(pretrained: bool = False, **kwargs) -> MobileNetV5: model = _gen_mobilenet_v5('mobilenetv5_base', pretrained=pretrained, **kwargs) return model
pytorch-image-models/timm/models/mobilenetv5.py/0
{ "file_path": "pytorch-image-models/timm/models/mobilenetv5.py", "repo_id": "pytorch-image-models", "token_count": 17451 }
267
""" Res2Net and Res2NeXt Adapted from Official Pytorch impl at: https://github.com/gasvn/Res2Net/ Paper: `Res2Net: A New Multi-scale Backbone Architecture` - https://arxiv.org/abs/1904.01169 """ import math import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from ._builder import build_model_with_cfg from ._registry import register_model, generate_default_cfgs from .resnet import ResNet __all__ = [] class Bottle2neck(nn.Module): """ Res2Net/Res2NeXT Bottleneck Adapted from https://github.com/gasvn/Res2Net/blob/master/res2net.py """ expansion = 4 def __init__( self, inplanes, planes, stride=1, downsample=None, cardinality=1, base_width=26, scale=4, dilation=1, first_dilation=None, act_layer=nn.ReLU, norm_layer=None, attn_layer=None, **_, ): super(Bottle2neck, self).__init__() self.scale = scale self.is_first = stride > 1 or downsample is not None self.num_scales = max(1, scale - 1) width = int(math.floor(planes * (base_width / 64.0))) * cardinality self.width = width outplanes = planes * self.expansion first_dilation = first_dilation or dilation self.conv1 = nn.Conv2d(inplanes, width * scale, kernel_size=1, bias=False) self.bn1 = norm_layer(width * scale) convs = [] bns = [] for i in range(self.num_scales): convs.append(nn.Conv2d( width, width, kernel_size=3, stride=stride, padding=first_dilation, dilation=first_dilation, groups=cardinality, bias=False)) bns.append(norm_layer(width)) self.convs = nn.ModuleList(convs) self.bns = nn.ModuleList(bns) if self.is_first: # FIXME this should probably have count_include_pad=False, but hurts original weights self.pool = nn.AvgPool2d(kernel_size=3, stride=stride, padding=1) else: self.pool = None self.conv3 = nn.Conv2d(width * scale, outplanes, kernel_size=1, bias=False) self.bn3 = norm_layer(outplanes) self.se = attn_layer(outplanes) if attn_layer is not None else None self.relu = act_layer(inplace=True) self.downsample = downsample def zero_init_last(self): if getattr(self.bn3, 'weight', None) is not None: nn.init.zeros_(self.bn3.weight) def forward(self, x): shortcut = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) spx = torch.split(out, self.width, 1) spo = [] sp = spx[0] # redundant, for torchscript for i, (conv, bn) in enumerate(zip(self.convs, self.bns)): if i == 0 or self.is_first: sp = spx[i] else: sp = sp + spx[i] sp = conv(sp) sp = bn(sp) sp = self.relu(sp) spo.append(sp) if self.scale > 1: if self.pool is not None: # self.is_first == True, None check for torchscript spo.append(self.pool(spx[-1])) else: spo.append(spx[-1]) out = torch.cat(spo, 1) out = self.conv3(out) out = self.bn3(out) if self.se is not None: out = self.se(out) if self.downsample is not None: shortcut = self.downsample(x) out += shortcut out = self.relu(out) return out def _create_res2net(variant, pretrained=False, **kwargs): return build_model_with_cfg(ResNet, variant, pretrained, **kwargs) def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7), 'crop_pct': 0.875, 'interpolation': 'bilinear', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'first_conv': 'conv1', 'classifier': 'fc', **kwargs } default_cfgs = generate_default_cfgs({ 'res2net50_26w_4s.in1k': _cfg(hf_hub_id='timm/'), 'res2net50_48w_2s.in1k': _cfg(hf_hub_id='timm/'), 'res2net50_14w_8s.in1k': _cfg(hf_hub_id='timm/'), 'res2net50_26w_6s.in1k': _cfg(hf_hub_id='timm/'), 'res2net50_26w_8s.in1k': _cfg(hf_hub_id='timm/'), 'res2net101_26w_4s.in1k': _cfg(hf_hub_id='timm/'), 'res2next50.in1k': _cfg(hf_hub_id='timm/'), 'res2net50d.in1k': _cfg(hf_hub_id='timm/', first_conv='conv1.0'), 'res2net101d.in1k': _cfg(hf_hub_id='timm/', first_conv='conv1.0'), }) @register_model def res2net50_26w_4s(pretrained=False, **kwargs) -> ResNet: """Constructs a Res2Net-50 26w4s model. """ model_args = dict( block=Bottle2neck, layers=[3, 4, 6, 3], base_width=26, block_args=dict(scale=4)) return _create_res2net('res2net50_26w_4s', pretrained, **dict(model_args, **kwargs)) @register_model def res2net101_26w_4s(pretrained=False, **kwargs) -> ResNet: """Constructs a Res2Net-101 26w4s model. """ model_args = dict( block=Bottle2neck, layers=[3, 4, 23, 3], base_width=26, block_args=dict(scale=4)) return _create_res2net('res2net101_26w_4s', pretrained, **dict(model_args, **kwargs)) @register_model def res2net50_26w_6s(pretrained=False, **kwargs) -> ResNet: """Constructs a Res2Net-50 26w6s model. """ model_args = dict( block=Bottle2neck, layers=[3, 4, 6, 3], base_width=26, block_args=dict(scale=6)) return _create_res2net('res2net50_26w_6s', pretrained, **dict(model_args, **kwargs)) @register_model def res2net50_26w_8s(pretrained=False, **kwargs) -> ResNet: """Constructs a Res2Net-50 26w8s model. """ model_args = dict( block=Bottle2neck, layers=[3, 4, 6, 3], base_width=26, block_args=dict(scale=8)) return _create_res2net('res2net50_26w_8s', pretrained, **dict(model_args, **kwargs)) @register_model def res2net50_48w_2s(pretrained=False, **kwargs) -> ResNet: """Constructs a Res2Net-50 48w2s model. """ model_args = dict( block=Bottle2neck, layers=[3, 4, 6, 3], base_width=48, block_args=dict(scale=2)) return _create_res2net('res2net50_48w_2s', pretrained, **dict(model_args, **kwargs)) @register_model def res2net50_14w_8s(pretrained=False, **kwargs) -> ResNet: """Constructs a Res2Net-50 14w8s model. """ model_args = dict( block=Bottle2neck, layers=[3, 4, 6, 3], base_width=14, block_args=dict(scale=8)) return _create_res2net('res2net50_14w_8s', pretrained, **dict(model_args, **kwargs)) @register_model def res2next50(pretrained=False, **kwargs) -> ResNet: """Construct Res2NeXt-50 4s """ model_args = dict( block=Bottle2neck, layers=[3, 4, 6, 3], base_width=4, cardinality=8, block_args=dict(scale=4)) return _create_res2net('res2next50', pretrained, **dict(model_args, **kwargs)) @register_model def res2net50d(pretrained=False, **kwargs) -> ResNet: """Construct Res2Net-50 """ model_args = dict( block=Bottle2neck, layers=[3, 4, 6, 3], base_width=26, stem_type='deep', avg_down=True, stem_width=32, block_args=dict(scale=4)) return _create_res2net('res2net50d', pretrained, **dict(model_args, **kwargs)) @register_model def res2net101d(pretrained=False, **kwargs) -> ResNet: """Construct Res2Net-50 """ model_args = dict( block=Bottle2neck, layers=[3, 4, 23, 3], base_width=26, stem_type='deep', avg_down=True, stem_width=32, block_args=dict(scale=4)) return _create_res2net('res2net101d', pretrained, **dict(model_args, **kwargs))
pytorch-image-models/timm/models/res2net.py/0
{ "file_path": "pytorch-image-models/timm/models/res2net.py", "repo_id": "pytorch-image-models", "token_count": 3659 }
268
""" Transformer in Transformer (TNT) in PyTorch A PyTorch implement of TNT as described in 'Transformer in Transformer' - https://arxiv.org/abs/2103.00112 The official mindspore code is released and available at https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT The official pytorch code is released and available at https://github.com/huawei-noah/Efficient-AI-Backbones/tree/master/tnt_pytorch """ import math from typing import List, Optional, Tuple, Union import torch import torch.nn as nn from timm.data import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import Mlp, DropPath, trunc_normal_, _assert, to_2tuple, resample_abs_pos_embed from ._builder import build_model_with_cfg from ._features import feature_take_indices from ._manipulate import checkpoint from ._registry import generate_default_cfgs, register_model __all__ = ['TNT'] # model_registry will add each entrypoint fn to this class Attention(nn.Module): """ Multi-Head Attention """ def __init__(self, dim, hidden_dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): super().__init__() self.hidden_dim = hidden_dim self.num_heads = num_heads head_dim = hidden_dim // num_heads self.head_dim = head_dim self.scale = head_dim ** -0.5 self.qk = nn.Linear(dim, hidden_dim * 2, bias=qkv_bias) self.v = nn.Linear(dim, dim, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop, inplace=True) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop, inplace=True) def forward(self, x): B, N, C = x.shape qk = self.qk(x).reshape(B, N, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) q, k = qk.unbind(0) # make torchscript happy (cannot use tensor as tuple) v = self.v(x).reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, -1) x = self.proj(x) x = self.proj_drop(x) return x class Block(nn.Module): """ TNT Block """ def __init__( self, dim, dim_out, num_pixel, num_heads_in=4, num_heads_out=12, mlp_ratio=4., qkv_bias=False, proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, legacy=False, ): super().__init__() # Inner transformer self.norm_in = norm_layer(dim) self.attn_in = Attention( dim, dim, num_heads=num_heads_in, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=proj_drop, ) self.norm_mlp_in = norm_layer(dim) self.mlp_in = Mlp( in_features=dim, hidden_features=int(dim * 4), out_features=dim, act_layer=act_layer, drop=proj_drop, ) self.legacy = legacy if self.legacy: self.norm1_proj = norm_layer(dim) self.proj = nn.Linear(dim * num_pixel, dim_out, bias=True) self.norm2_proj = None else: self.norm1_proj = norm_layer(dim * num_pixel) self.proj = nn.Linear(dim * num_pixel, dim_out, bias=False) self.norm2_proj = norm_layer(dim_out) # Outer transformer self.norm_out = norm_layer(dim_out) self.attn_out = Attention( dim_out, dim_out, num_heads=num_heads_out, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=proj_drop, ) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm_mlp = norm_layer(dim_out) self.mlp = Mlp( in_features=dim_out, hidden_features=int(dim_out * mlp_ratio), out_features=dim_out, act_layer=act_layer, drop=proj_drop, ) def forward(self, pixel_embed, patch_embed): # inner pixel_embed = pixel_embed + self.drop_path(self.attn_in(self.norm_in(pixel_embed))) pixel_embed = pixel_embed + self.drop_path(self.mlp_in(self.norm_mlp_in(pixel_embed))) # outer B, N, C = patch_embed.size() if self.norm2_proj is None: patch_embed = torch.cat([ patch_embed[:, 0:1], patch_embed[:, 1:] + self.proj(self.norm1_proj(pixel_embed).reshape(B, N - 1, -1)), ], dim=1) else: patch_embed = torch.cat([ patch_embed[:, 0:1], patch_embed[:, 1:] + self.norm2_proj(self.proj(self.norm1_proj(pixel_embed.reshape(B, N - 1, -1)))), ], dim=1) patch_embed = patch_embed + self.drop_path(self.attn_out(self.norm_out(patch_embed))) patch_embed = patch_embed + self.drop_path(self.mlp(self.norm_mlp(patch_embed))) return pixel_embed, patch_embed class PixelEmbed(nn.Module): """ Image to Pixel Embedding """ def __init__( self, img_size=224, patch_size=16, in_chans=3, in_dim=48, stride=4, legacy=False, ): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) # grid_size property necessary for resizing positional embedding self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) num_patches = (self.grid_size[0]) * (self.grid_size[1]) self.img_size = img_size self.patch_size = patch_size self.legacy = legacy self.num_patches = num_patches self.in_dim = in_dim new_patch_size = [math.ceil(ps / stride) for ps in patch_size] self.new_patch_size = new_patch_size self.proj = nn.Conv2d(in_chans, self.in_dim, kernel_size=7, padding=3, stride=stride) if self.legacy: self.unfold = nn.Unfold(kernel_size=new_patch_size, stride=new_patch_size) else: self.unfold = nn.Unfold(kernel_size=patch_size, stride=patch_size) def feat_ratio(self, as_scalar=True) -> Union[Tuple[int, int], int]: if as_scalar: return max(self.patch_size) else: return self.patch_size def dynamic_feat_size(self, img_size: Tuple[int, int]) -> Tuple[int, int]: return img_size[0] // self.patch_size[0], img_size[1] // self.patch_size[1] def forward(self, x: torch.Tensor, pixel_pos: torch.Tensor) -> torch.Tensor: B, C, H, W = x.shape _assert( H == self.img_size[0], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]}).") _assert( W == self.img_size[1], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]}).") if self.legacy: x = self.proj(x) x = self.unfold(x) x = x.transpose(1, 2).reshape( B * self.num_patches, self.in_dim, self.new_patch_size[0], self.new_patch_size[1]) else: x = self.unfold(x) x = x.transpose(1, 2).reshape(B * self.num_patches, C, self.patch_size[0], self.patch_size[1]) x = self.proj(x) x = x + pixel_pos x = x.reshape(B * self.num_patches, self.in_dim, -1).transpose(1, 2) return x class TNT(nn.Module): """ Transformer in Transformer - https://arxiv.org/abs/2103.00112 """ def __init__( self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, global_pool='token', embed_dim=768, inner_dim=48, depth=12, num_heads_inner=4, num_heads_outer=12, mlp_ratio=4., qkv_bias=False, drop_rate=0., pos_drop_rate=0., proj_drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm, first_stride=4, legacy=False, ): super().__init__() assert global_pool in ('', 'token', 'avg') self.num_classes = num_classes self.global_pool = global_pool self.num_features = self.head_hidden_size = self.embed_dim = embed_dim # for consistency with other models self.num_prefix_tokens = 1 self.grad_checkpointing = False self.pixel_embed = PixelEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, in_dim=inner_dim, stride=first_stride, legacy=legacy, ) num_patches = self.pixel_embed.num_patches r = self.pixel_embed.feat_ratio() if hasattr(self.pixel_embed, 'feat_ratio') else patch_size self.num_patches = num_patches new_patch_size = self.pixel_embed.new_patch_size num_pixel = new_patch_size[0] * new_patch_size[1] self.norm1_proj = norm_layer(num_pixel * inner_dim) self.proj = nn.Linear(num_pixel * inner_dim, embed_dim) self.norm2_proj = norm_layer(embed_dim) self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.patch_pos = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) self.pixel_pos = nn.Parameter(torch.zeros(1, inner_dim, new_patch_size[0], new_patch_size[1])) self.pos_drop = nn.Dropout(p=pos_drop_rate) dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule blocks = [] for i in range(depth): blocks.append(Block( dim=inner_dim, dim_out=embed_dim, num_pixel=num_pixel, num_heads_in=num_heads_inner, num_heads_out=num_heads_outer, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, proj_drop=proj_drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, legacy=legacy, )) self.blocks = nn.ModuleList(blocks) self.feature_info = [ dict(module=f'blocks.{i}', num_chs=embed_dim, reduction=r) for i in range(depth)] self.norm = norm_layer(embed_dim) self.head_drop = nn.Dropout(drop_rate) self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() trunc_normal_(self.cls_token, std=.02) trunc_normal_(self.patch_pos, std=.02) trunc_normal_(self.pixel_pos, std=.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'patch_pos', 'pixel_pos', 'cls_token'} @torch.jit.ignore def group_matcher(self, coarse=False): matcher = dict( stem=r'^cls_token|patch_pos|pixel_pos|pixel_embed|norm[12]_proj|proj', # stem and embed / pos blocks=[ (r'^blocks\.(\d+)', None), (r'^norm', (99999,)), ] ) return matcher @torch.jit.ignore def set_grad_checkpointing(self, enable=True): self.grad_checkpointing = enable @torch.jit.ignore def get_classifier(self) -> nn.Module: return self.head def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None): self.num_classes = num_classes if global_pool is not None: assert global_pool in ('', 'token', 'avg') self.global_pool = global_pool self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() def forward_intermediates( self, x: torch.Tensor, indices: Optional[Union[int, List[int]]] = None, return_prefix_tokens: bool = False, norm: bool = False, stop_early: bool = False, output_fmt: str = 'NCHW', intermediates_only: bool = False, ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]: """ Forward features that returns intermediates. Args: x: Input image tensor indices: Take last n blocks if an int, if is a sequence, select by matching indices return_prefix_tokens: Return both prefix and spatial intermediate tokens norm: Apply norm layer to all intermediates stop_early: Stop iterating over blocks when last desired intermediate hit output_fmt: Shape of intermediate feature outputs intermediates_only: Only return intermediate features Returns: """ assert output_fmt in ('NCHW', 'NLC'), 'Output format must be one of NCHW or NLC.' reshape = output_fmt == 'NCHW' intermediates = [] take_indices, max_index = feature_take_indices(len(self.blocks), indices) # forward pass B, _, height, width = x.shape pixel_embed = self.pixel_embed(x, self.pixel_pos) patch_embed = self.norm2_proj(self.proj(self.norm1_proj(pixel_embed.reshape(B, self.num_patches, -1)))) patch_embed = torch.cat((self.cls_token.expand(B, -1, -1), patch_embed), dim=1) patch_embed = patch_embed + self.patch_pos patch_embed = self.pos_drop(patch_embed) if torch.jit.is_scripting() or not stop_early: # can't slice blocks in torchscript blocks = self.blocks else: blocks = self.blocks[:max_index + 1] for i, blk in enumerate(blocks): if self.grad_checkpointing and not torch.jit.is_scripting(): pixel_embed, patch_embed = checkpoint(blk, pixel_embed, patch_embed) else: pixel_embed, patch_embed = blk(pixel_embed, patch_embed) if i in take_indices: # normalize intermediates with final norm layer if enabled intermediates.append(self.norm(patch_embed) if norm else patch_embed) # process intermediates if self.num_prefix_tokens: # split prefix (e.g. class, distill) and spatial feature tokens prefix_tokens = [y[:, 0:self.num_prefix_tokens] for y in intermediates] intermediates = [y[:, self.num_prefix_tokens:] for y in intermediates] if reshape: # reshape to BCHW output format H, W = self.pixel_embed.dynamic_feat_size((height, width)) intermediates = [y.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() for y in intermediates] if not torch.jit.is_scripting() and return_prefix_tokens: # return_prefix not support in torchscript due to poor type handling intermediates = list(zip(intermediates, prefix_tokens)) if intermediates_only: return intermediates patch_embed = self.norm(patch_embed) return patch_embed, intermediates def prune_intermediate_layers( self, indices: Union[int, List[int]] = 1, prune_norm: bool = False, prune_head: bool = True, ): """ Prune layers not required for specified intermediates. """ take_indices, max_index = feature_take_indices(len(self.blocks), indices) self.blocks = self.blocks[:max_index + 1] # truncate blocks if prune_norm: self.norm = nn.Identity() if prune_head: self.reset_classifier(0, '') return take_indices def forward_features(self, x): B = x.shape[0] pixel_embed = self.pixel_embed(x, self.pixel_pos) patch_embed = self.norm2_proj(self.proj(self.norm1_proj(pixel_embed.reshape(B, self.num_patches, -1)))) patch_embed = torch.cat((self.cls_token.expand(B, -1, -1), patch_embed), dim=1) patch_embed = patch_embed + self.patch_pos patch_embed = self.pos_drop(patch_embed) for blk in self.blocks: if self.grad_checkpointing and not torch.jit.is_scripting(): pixel_embed, patch_embed = checkpoint(blk, pixel_embed, patch_embed) else: pixel_embed, patch_embed = blk(pixel_embed, patch_embed) patch_embed = self.norm(patch_embed) return patch_embed def forward_head(self, x, pre_logits: bool = False): if self.global_pool: x = x[:, self.num_prefix_tokens:].mean(dim=1) if self.global_pool == 'avg' else x[:, 0] x = self.head_drop(x) return x if pre_logits else self.head(x) def forward(self, x): x = self.forward_features(x) x = self.forward_head(x) return x def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'crop_pct': .9, 'interpolation': 'bicubic', 'fixed_input_size': True, 'mean': IMAGENET_INCEPTION_MEAN, 'std': IMAGENET_INCEPTION_STD, 'first_conv': 'pixel_embed.proj', 'classifier': 'head', 'paper_ids': 'arXiv:2103.00112', 'paper_name': 'Transformer in Transformer', 'origin_url': 'https://github.com/huawei-noah/Efficient-AI-Backbones/tree/master/tnt_pytorch', **kwargs } default_cfgs = generate_default_cfgs({ 'tnt_s_legacy_patch16_224.in1k': _cfg( hf_hub_id='timm/', #url='https://github.com/contrastive/pytorch-image-models/releases/download/TNT/tnt_s_patch16_224.pth.tar', ), 'tnt_s_patch16_224.in1k': _cfg( hf_hub_id='timm/', #url='https://github.com/huawei-noah/Efficient-AI-Backbones/releases/download/tnt/tnt_s_81.5.pth.tar', ), 'tnt_b_patch16_224.in1k': _cfg( hf_hub_id='timm/', #url='https://github.com/huawei-noah/Efficient-AI-Backbones/releases/download/tnt/tnt_b_82.9.pth.tar', ), }) def checkpoint_filter_fn(state_dict, model): state_dict.pop('outer_tokens', None) if 'patch_pos' in state_dict: out_dict = state_dict else: out_dict = {} for k, v in state_dict.items(): k = k.replace('outer_pos', 'patch_pos') k = k.replace('inner_pos', 'pixel_pos') k = k.replace('patch_embed', 'pixel_embed') k = k.replace('proj_norm1', 'norm1_proj') k = k.replace('proj_norm2', 'norm2_proj') k = k.replace('inner_norm1', 'norm_in') k = k.replace('inner_attn', 'attn_in') k = k.replace('inner_norm2', 'norm_mlp_in') k = k.replace('inner_mlp', 'mlp_in') k = k.replace('outer_norm1', 'norm_out') k = k.replace('outer_attn', 'attn_out') k = k.replace('outer_norm2', 'norm_mlp') k = k.replace('outer_mlp', 'mlp') if k == 'pixel_pos' and model.pixel_embed.legacy == False: B, N, C = v.shape H = W = int(N ** 0.5) assert H * W == N v = v.permute(0, 2, 1).reshape(B, C, H, W) out_dict[k] = v """ convert patch embedding weight from manual patchify + linear proj to conv""" if out_dict['patch_pos'].shape != model.patch_pos.shape: out_dict['patch_pos'] = resample_abs_pos_embed( out_dict['patch_pos'], new_size=model.pixel_embed.grid_size, num_prefix_tokens=1, ) return out_dict def _create_tnt(variant, pretrained=False, **kwargs): out_indices = kwargs.pop('out_indices', 3) model = build_model_with_cfg( TNT, variant, pretrained, pretrained_filter_fn=checkpoint_filter_fn, feature_cfg=dict(out_indices=out_indices, feature_cls='getter'), **kwargs) return model @register_model def tnt_s_legacy_patch16_224(pretrained=False, **kwargs) -> TNT: model_cfg = dict( patch_size=16, embed_dim=384, inner_dim=24, depth=12, num_heads_outer=6, qkv_bias=False, legacy=True) model = _create_tnt('tnt_s_legacy_patch16_224', pretrained=pretrained, **dict(model_cfg, **kwargs)) return model @register_model def tnt_s_patch16_224(pretrained=False, **kwargs) -> TNT: model_cfg = dict( patch_size=16, embed_dim=384, inner_dim=24, depth=12, num_heads_outer=6, qkv_bias=False) model = _create_tnt('tnt_s_patch16_224', pretrained=pretrained, **dict(model_cfg, **kwargs)) return model @register_model def tnt_b_patch16_224(pretrained=False, **kwargs) -> TNT: model_cfg = dict( patch_size=16, embed_dim=640, inner_dim=40, depth=12, num_heads_outer=10, qkv_bias=False) model = _create_tnt('tnt_b_patch16_224', pretrained=pretrained, **dict(model_cfg, **kwargs)) return model
pytorch-image-models/timm/models/tnt.py/0
{ "file_path": "pytorch-image-models/timm/models/tnt.py", "repo_id": "pytorch-image-models", "token_count": 10582 }
269
""" Optimizer Factory w/ custom Weight Decay & Layer Decay support Hacked together by / Copyright 2021 Ross Wightman """ import logging from dataclasses import dataclass from functools import partial from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union from fnmatch import fnmatch import importlib import torch import torch.nn as nn import torch.optim from ._param_groups import param_groups_layer_decay, param_groups_weight_decay from ._types import ParamsT, OptimType, OptimizerCallable from .adabelief import AdaBelief from .adafactor import Adafactor from .adafactor_bv import AdafactorBigVision from .adahessian import Adahessian from .adamp import AdamP from .adamw import AdamWLegacy from .adan import Adan from .adopt import Adopt from .kron import Kron from .lamb import Lamb from .laprop import LaProp from .lars import Lars from .lion import Lion from .lookahead import Lookahead from .madgrad import MADGRAD from .mars import Mars from .nadam import NAdamLegacy from .nadamw import NAdamW from .nvnovograd import NvNovoGrad from .radam import RAdamLegacy from .rmsprop_tf import RMSpropTF from .sgdp import SGDP from .sgdw import SGDW _logger = logging.getLogger(__name__) def _import_class(class_string: str) -> Type: """Dynamically import a class from a string.""" try: module_name, class_name = class_string.rsplit(".", 1) module = importlib.import_module(module_name) return getattr(module, class_name) except (ImportError, AttributeError) as e: raise ImportError(f"Could not import {class_string}: {e}") @dataclass(frozen=True) class OptimInfo: """Immutable configuration for an optimizer. Attributes: name: Unique identifier for the optimizer opt_class: The optimizer class description: Brief description of the optimizer's characteristics and behavior has_eps: Whether the optimizer accepts epsilon parameter has_momentum: Whether the optimizer accepts momentum parameter has_betas: Whether the optimizer accepts a tuple of beta parameters num_betas: number of betas in tuple (valid IFF has_betas = True) defaults: Optional default parameters for the optimizer """ name: str opt_class: Union[str, OptimType] description: str = '' has_eps: bool = True has_momentum: bool = False has_betas: bool = False num_betas: int = 2 second_order: bool = False defaults: Optional[Dict[str, Any]] = None class OptimizerRegistry: """Registry managing optimizer configurations and instantiation. This class provides a central registry for optimizer configurations and handles their instantiation with appropriate parameter groups and settings. """ def __init__(self) -> None: self._optimizers: Dict[str, OptimInfo] = {} self._foreach_defaults: Set[str] = {'lion'} def register(self, info: OptimInfo) -> None: """Register an optimizer configuration. Args: info: The OptimInfo configuration containing name, type and description """ name = info.name.lower() if name in self._optimizers: _logger.warning(f'Optimizer {name} already registered, overwriting') self._optimizers[name] = info def register_alias(self, alias: str, target: str) -> None: """Register an alias for an existing optimizer. Args: alias: The alias name target: The target optimizer name Raises: KeyError: If target optimizer doesn't exist """ target = target.lower() if target not in self._optimizers: raise KeyError(f'Cannot create alias for non-existent optimizer {target}') self._optimizers[alias.lower()] = self._optimizers[target] def register_foreach_default(self, name: str) -> None: """Register an optimizer as defaulting to foreach=True.""" self._foreach_defaults.add(name.lower()) def list_optimizers( self, filter: Union[str, List[str]] = '', exclude_filters: Optional[List[str]] = None, with_description: bool = False ) -> List[Union[str, Tuple[str, str]]]: """List available optimizer names, optionally filtered. Args: filter: Wildcard style filter string (e.g., 'adam*') exclude_filters: Optional list of wildcard patterns to exclude with_description: If True, return tuples of (name, description) Returns: List of either optimizer names or (name, description) tuples """ names = sorted(self._optimizers.keys()) if filter: if isinstance(filter, str): filters = [filter] else: filters = filter filtered_names = set() for f in filters: filtered_names.update(n for n in names if fnmatch(n, f)) names = sorted(filtered_names) if exclude_filters: for exclude_filter in exclude_filters: names = [n for n in names if not fnmatch(n, exclude_filter)] if with_description: return [(name, self._optimizers[name].description) for name in names] return names def get_optimizer_info(self, name: str) -> OptimInfo: """Get the OptimInfo for an optimizer. Args: name: Name of the optimizer Returns: OptimInfo configuration Raises: ValueError: If optimizer is not found """ name = name.lower() if name not in self._optimizers: raise ValueError(f'Optimizer {name} not found in registry') return self._optimizers[name] def get_optimizer_class( self, name_or_info: Union[str, OptimInfo], bind_defaults: bool = True, ) -> Union[OptimType, OptimizerCallable]: """Get the optimizer class with any default arguments applied. This allows direct instantiation of optimizers with their default configs without going through the full factory. Args: name_or_info: Name of the optimizer bind_defaults: Bind default arguments to optimizer class via `partial` before returning Returns: Optimizer class or partial with defaults applied Raises: ValueError: If optimizer not found """ if isinstance(name_or_info, str): opt_info = self.get_optimizer_info(name_or_info) else: assert isinstance(name_or_info, OptimInfo) opt_info = name_or_info if isinstance(opt_info.opt_class, str): # Special handling for APEX and BNB optimizers if opt_info.opt_class.startswith('apex.'): assert torch.cuda.is_available(), 'CUDA required for APEX optimizers' try: opt_class = _import_class(opt_info.opt_class) except ImportError as e: raise ImportError('APEX optimizers require apex to be installed') from e elif opt_info.opt_class.startswith('bitsandbytes.'): assert torch.cuda.is_available(), 'CUDA required for bitsandbytes optimizers' try: opt_class = _import_class(opt_info.opt_class) except ImportError as e: raise ImportError('bitsandbytes optimizers require bitsandbytes to be installed') from e else: opt_class = _import_class(opt_info.opt_class) else: opt_class = opt_info.opt_class # Return class or partial with defaults if bind_defaults and opt_info.defaults: opt_class = partial(opt_class, **opt_info.defaults) return opt_class def create_optimizer( self, model_or_params: Union[nn.Module, ParamsT], opt: str, lr: Optional[float] = None, weight_decay: float = 0., momentum: float = 0.9, foreach: Optional[bool] = None, weight_decay_exclude_1d: bool = True, layer_decay: Optional[float] = None, layer_decay_min_scale: Optional[float] = None, layer_decay_no_opt_scale: Optional[float] = None, param_group_fn: Optional[Callable[[nn.Module], ParamsT]] = None, **kwargs: Any, ) -> torch.optim.Optimizer: """Create an optimizer instance. Args: model_or_params: Model or parameters to optimize opt: Name of optimizer to create lr: Learning rate weight_decay: Weight decay factor momentum: Momentum factor for applicable optimizers foreach: Enable/disable foreach operation weight_decay_exclude_1d: Whether to skip weight decay for 1d params (biases and norm affine) layer_decay: Layer-wise learning rate decay layer_scale_min_scale: Minimum layer scale factor clamp value layer_scale_no_opt_scale: Layer scale below which optimization is disabled param_group_fn: Optional custom parameter grouping function **kwargs: Additional optimizer-specific arguments Returns: Configured optimizer instance Raises: ValueError: If optimizer not found or configuration invalid """ # Get parameters to optimize if isinstance(model_or_params, nn.Module): # Extract parameters from a nn.Module, build param groups w/ weight-decay and/or layer-decay applied no_weight_decay = getattr(model_or_params, 'no_weight_decay', lambda: set())() if param_group_fn: # run custom fn to generate param groups from nn.Module params = param_group_fn(model_or_params) elif layer_decay is not None: params = param_groups_layer_decay( model_or_params, weight_decay=weight_decay, layer_decay=layer_decay, no_weight_decay_list=no_weight_decay, weight_decay_exclude_1d=weight_decay_exclude_1d, min_scale=layer_decay_min_scale, no_opt_scale=layer_decay_no_opt_scale, ) weight_decay = 0. elif weight_decay and weight_decay_exclude_1d: params = param_groups_weight_decay( model_or_params, weight_decay=weight_decay, no_weight_decay_list=no_weight_decay, ) weight_decay = 0. else: params = model_or_params.parameters() else: # pass parameters / parameter groups through to optimizer params = model_or_params # Parse optimizer name opt_split = opt.lower().split('_') opt_name = opt_split[-1] use_lookahead = opt_split[0] == 'lookahead' if len(opt_split) > 1 else False opt_info = self.get_optimizer_info(opt_name) # Build optimizer arguments opt_args: Dict[str, Any] = {'weight_decay': weight_decay, **kwargs} # Add LR to args, if None optimizer default is used, some optimizers manage LR internally if None. if lr is not None: opt_args['lr'] = lr # Apply optimizer-specific settings if opt_info.defaults: for k, v in opt_info.defaults.items(): opt_args.setdefault(k, v) # timm has always defaulted momentum to 0.9 if optimizer supports momentum, keep for backward compat. if opt_info.has_momentum: opt_args.setdefault('momentum', momentum) # Remove commonly used kwargs that aren't always supported if not opt_info.has_eps: opt_args.pop('eps', None) if not opt_info.has_betas: opt_args.pop('betas', None) if foreach is not None: # Explicitly activate or deactivate multi-tensor foreach impl. # Not all optimizers support this, and those that do usually default to using # multi-tensor impl if foreach is left as default 'None' and can be enabled. opt_args.setdefault('foreach', foreach) # Create optimizer opt_class = self.get_optimizer_class(opt_info, bind_defaults=False) optimizer = opt_class(params, **opt_args) # Apply Lookahead if requested if use_lookahead: optimizer = Lookahead(optimizer) return optimizer def _register_sgd_variants(registry: OptimizerRegistry) -> None: """Register SGD-based optimizers""" sgd_optimizers = [ OptimInfo( name='sgd', opt_class=torch.optim.SGD, description='torch.Optim Stochastic Gradient Descent (SGD) with Nesterov momentum', has_eps=False, has_momentum=True, defaults={'nesterov': True} ), OptimInfo( name='momentum', opt_class=torch.optim.SGD, description='torch.Optim Stochastic Gradient Descent (SGD) with classical momentum', has_eps=False, has_momentum=True, defaults={'nesterov': False} ), OptimInfo( name='sgdp', opt_class=SGDP, description='SGD with built-in projection to unit norm sphere', has_momentum=True, defaults={'nesterov': True} ), OptimInfo( name='sgdw', opt_class=SGDW, description='SGD with decoupled weight decay and Nesterov momentum', has_eps=False, has_momentum=True, defaults={'nesterov': True} ), ] for opt in sgd_optimizers: registry.register(opt) def _register_adam_variants(registry: OptimizerRegistry) -> None: """Register Adam-based optimizers""" adam_optimizers = [ OptimInfo( name='adam', opt_class=torch.optim.Adam, description='torch.optim.Adam, Adaptive Moment Estimation', has_betas=True ), OptimInfo( name='adamw', opt_class=torch.optim.AdamW, description='torch.optim.AdamW, Adam with decoupled weight decay', has_betas=True ), OptimInfo( name='adamwlegacy', opt_class=AdamWLegacy, description='legacy impl of AdamW that pre-dates inclusion to torch.optim', has_betas=True ), OptimInfo( name='adamp', opt_class=AdamP, description='Adam with built-in projection to unit norm sphere', has_betas=True, defaults={'wd_ratio': 0.01, 'nesterov': True} ), OptimInfo( name='nadam', opt_class=torch.optim.NAdam, description='torch.optim.NAdam, Adam with Nesterov momentum', has_betas=True ), OptimInfo( name='nadamlegacy', opt_class=NAdamLegacy, description='legacy impl of NAdam that pre-dates inclusion in torch.optim', has_betas=True ), OptimInfo( name='nadamw', opt_class=NAdamW, description='Adam with Nesterov momentum and decoupled weight decay, mlcommons/algorithmic-efficiency impl', has_betas=True ), OptimInfo( name='radam', opt_class=torch.optim.RAdam, description='torch.optim.RAdam, Rectified Adam with variance adaptation', has_betas=True ), OptimInfo( name='radamlegacy', opt_class=RAdamLegacy, description='legacy impl of RAdam that predates inclusion in torch.optim', has_betas=True ), OptimInfo( name='radamw', opt_class=torch.optim.RAdam, description='torch.optim.RAdamW, Rectified Adam with variance adaptation and decoupled weight decay', has_betas=True, defaults={'decoupled_weight_decay': True} ), OptimInfo( name='adamax', opt_class=torch.optim.Adamax, description='torch.optim.Adamax, Adam with infinity norm for more stable updates', has_betas=True ), OptimInfo( name='adafactor', opt_class=Adafactor, description='Memory-efficient implementation of Adam with factored gradients', ), OptimInfo( name='adafactorbv', opt_class=AdafactorBigVision, description='Big Vision variant of Adafactor with factored gradients, half precision momentum', ), OptimInfo( name='adopt', opt_class=Adopt, description='Modified Adam that can converge with any β2 with the optimal rate', ), OptimInfo( name='adoptw', opt_class=Adopt, description='Modified AdamW (decoupled decay) that can converge with any β2 with the optimal rate', defaults={'decoupled': True} ), ] for opt in adam_optimizers: registry.register(opt) def _register_lamb_lars(registry: OptimizerRegistry) -> None: """Register LAMB and LARS variants""" lamb_lars_optimizers = [ OptimInfo( name='lamb', opt_class=Lamb, description='Layer-wise Adaptive Moments for batch optimization', has_betas=True ), OptimInfo( name='lambc', opt_class=Lamb, description='LAMB with trust ratio clipping for stability', has_betas=True, defaults={'trust_clip': True} ), OptimInfo( name='lambw', opt_class=Lamb, description='LAMB with decoupled weight decay', has_betas=True, defaults={'decoupled_decay': True} ), OptimInfo( name='lambcw', opt_class=Lamb, description='LAMB with trust ratio clipping for stability and decoupled decay', has_betas=True, defaults={'trust_clip': True, 'decoupled_decay': True} ), OptimInfo( name='lars', opt_class=Lars, description='Layer-wise Adaptive Rate Scaling', has_momentum=True ), OptimInfo( name='larc', opt_class=Lars, description='LARS with trust ratio clipping for stability', has_momentum=True, defaults={'trust_clip': True} ), OptimInfo( name='nlars', opt_class=Lars, description='LARS with Nesterov momentum', has_momentum=True, defaults={'nesterov': True} ), OptimInfo( name='nlarc', opt_class=Lars, description='LARS with Nesterov momentum & trust ratio clipping', has_momentum=True, defaults={'nesterov': True, 'trust_clip': True} ), ] for opt in lamb_lars_optimizers: registry.register(opt) def _register_corrected_decay_optimizers(registry: OptimizerRegistry) -> None: """Register corrected weight decay optimizer variants""" corrected_optimizers = [ OptimInfo( name='adamc', opt_class=AdamWLegacy, description='AdamW with corrected weight decay (lr²/max_lr scaling)', has_betas=True, defaults={'corrected_weight_decay': True} ), OptimInfo( name='nadamc', opt_class=NAdamW, description='NAdamW with corrected weight decay (lr²/max_lr scaling)', has_betas=True, defaults={'corrected_weight_decay': True} ), OptimInfo( name='sgdc', opt_class=SGDW, description='SGD with corrected decoupled weight decay (lr²/max_lr scaling)', has_eps=False, has_momentum=True, defaults={'nesterov': True, 'corrected_weight_decay': True} ), OptimInfo( name='adoptc', opt_class=Adopt, description='Adopt with corrected decoupled weight decay (lr²/max_lr scaling)', defaults={'decoupled': True, 'corrected_weight_decay': True} ), OptimInfo( name='lambcd', opt_class=Lamb, description='LAMB with corrected decoupled weight decay (lr²/max_lr scaling)', has_betas=True, defaults={'decoupled_decay': True, 'corrected_weight_decay': True} ), OptimInfo( name='kronc', opt_class=Kron, description='PSGD Kron with corrected decoupled weight decay (lr²/max_lr scaling)', has_momentum=True, defaults={'decoupled_decay': True, 'corrected_weight_decay': True} ), OptimInfo( name='lionc', opt_class=Lion, description='Lion with corrected weight decay (lr²/max_lr scaling)', has_eps=False, has_betas=True, defaults={'corrected_weight_decay': True} ), OptimInfo( name='lapropc', opt_class=LaProp, description='LaProp with corrected weight decay (lr²/max_lr scaling)', has_betas=True, defaults={'corrected_weight_decay': True} ), OptimInfo( name='rmsproptfc', opt_class=RMSpropTF, description='RMSprop TF-style with corrected decoupled weight decay (lr²/max_lr scaling)', has_momentum=True, defaults={'alpha': 0.9, 'decoupled_decay': True, 'corrected_weight_decay': True} ), OptimInfo( name='adafactorbvc', opt_class=AdafactorBigVision, description='Adafactor Big Vision with corrected weight decay (lr²/max_lr or lr/max_lr scaling)', defaults={'corrected_weight_decay': True} ), ] for opt in corrected_optimizers: registry.register(opt) # Cautious + corrected variants cautious_corrected = [ OptimInfo( name='cadamc', opt_class=AdamWLegacy, description='Cautious AdamW with corrected weight decay (lr²/max_lr scaling)', has_betas=True, defaults={'caution': True, 'corrected_weight_decay': True} ), OptimInfo( name='cadoptc', opt_class=Adopt, description='Cautious Adopt with corrected decoupled weight decay (lr²/max_lr scaling)', defaults={'decoupled': True, 'caution': True, 'corrected_weight_decay': True} ), OptimInfo( name='cnadamc', opt_class=NAdamW, description='Cautious NAdamW with corrected weight decay (lr²/max_lr scaling)', has_betas=True, defaults={'caution': True, 'corrected_weight_decay': True} ), OptimInfo( name='csgdc', opt_class=SGDW, description='Cautious SGD with corrected decoupled weight decay (lr²/max_lr scaling)', has_eps=False, has_momentum=True, defaults={'nesterov': True, 'caution': True, 'corrected_weight_decay': True} ), OptimInfo( name='clionc', opt_class=Lion, description='Cautious Lion with corrected weight decay (lr²/max_lr scaling)', has_eps=False, has_betas=True, defaults={'caution': True, 'corrected_weight_decay': True} ), OptimInfo( name='cadafactorbvc', opt_class=AdafactorBigVision, description='Cautious Adafactor Big Vision with corrected weight decay', defaults={'caution': True, 'corrected_weight_decay': True} ), ] for opt in cautious_corrected: registry.register(opt) def _register_cautious_optimizers(registry: OptimizerRegistry) -> None: cautious_optimizers = [ OptimInfo( name='cadafactor', opt_class=Adafactor, description='Cautious Adafactor', defaults={'caution': True} ), OptimInfo( name='cadafactorbv', opt_class=AdafactorBigVision, description='Cautious Big Vision Adafactor', defaults={'caution': True} ), OptimInfo( name='cadamw', opt_class=AdamWLegacy, description='Cautious AdamW', has_betas=True, defaults={'caution': True} ), OptimInfo( name='cadopt', opt_class=Adopt, description='Cautious Adopt', defaults={'caution': True} ), OptimInfo( name='cadan', opt_class=Adan, description='Cautious Adaptive Nesterov Momentum Algorithm', defaults={'caution': True, 'no_prox': False}, has_betas=True, num_betas=3 ), OptimInfo( name='cadanw', opt_class=Adan, description='Cautious Adaptive Nesterov Momentum with decoupled weight decay', defaults={'caution': True, 'no_prox': True}, has_betas=True, num_betas=3 ), OptimInfo( name='cadoptw', opt_class=Adopt, description='Cautious AdoptW (decoupled decay)', defaults={'decoupled': True, 'caution': True} ), OptimInfo( name='clamb', opt_class=Lamb, description='Cautious LAMB', has_betas=True, defaults={'caution': True} ), OptimInfo( name='clambw', opt_class=Lamb, description='Cautious LAMB with decoupled weight decay', has_betas=True, defaults={'caution': True, 'decoupled_decay': True} ), OptimInfo( name='claprop', opt_class=LaProp, description='Cautious LaProp', has_betas=True, defaults={'caution': True} ), OptimInfo( name='clion', opt_class=Lion, description='Cautious Lion', has_eps=False, has_betas=True, defaults = {'caution': True} ), OptimInfo( name='cmars', opt_class=Mars, description='Cautious MARS', has_betas=True, defaults={'caution': True} ), OptimInfo( name='cnadamw', opt_class=NAdamW, description='Cautious NAdamW', has_betas=True, defaults={'caution': True} ), OptimInfo( name='crmsproptf', opt_class=RMSpropTF, description='Cautious TensorFlow-style RMSprop', has_momentum=True, defaults={'alpha': 0.9, 'caution': True} ), OptimInfo( name='csgdw', opt_class=SGDW, description='Cautious SGD with decoupled weight decay and Nesterov momentum', has_eps=False, has_momentum=True, defaults={'nesterov': True, 'caution': True} ), ] for opt in cautious_optimizers: registry.register(opt) def _register_other_optimizers(registry: OptimizerRegistry) -> None: """Register miscellaneous optimizers""" other_optimizers = [ OptimInfo( name='adabelief', opt_class=AdaBelief, description='Adapts learning rate based on gradient prediction error', has_betas=True, defaults={'rectify': False} ), OptimInfo( name='radabelief', opt_class=AdaBelief, description='Rectified AdaBelief with variance adaptation', has_betas=True, defaults={'rectify': True} ), OptimInfo( name='adadelta', opt_class=torch.optim.Adadelta, description='torch.optim.Adadelta, Adapts learning rates based on running windows of gradients' ), OptimInfo( name='adagrad', opt_class=torch.optim.Adagrad, description='torch.optim.Adagrad, Adapts learning rates using cumulative squared gradients', defaults={'eps': 1e-8} ), OptimInfo( name='adan', opt_class=Adan, description='Adaptive Nesterov Momentum Algorithm', defaults={'no_prox': False}, has_betas=True, num_betas=3 ), OptimInfo( name='adanw', opt_class=Adan, description='Adaptive Nesterov Momentum with decoupled weight decay', defaults={'no_prox': True}, has_betas=True, num_betas=3 ), OptimInfo( name='adahessian', opt_class=Adahessian, description='An Adaptive Second Order Optimizer', has_betas=True, second_order=True, ), OptimInfo( name='kron', opt_class=Kron, description='PSGD optimizer with Kronecker-factored preconditioner', has_momentum=True, ), OptimInfo( name='kronw', opt_class=Kron, description='PSGD optimizer with Kronecker-factored preconditioner and decoupled weight decay', has_momentum=True, defaults={'decoupled_decay': True} ), OptimInfo( name='laprop', opt_class=LaProp, description='Separating Momentum and Adaptivity in Adam', has_betas=True, ), OptimInfo( name='lion', opt_class=Lion, description='Evolved Sign Momentum optimizer for improved convergence', has_eps=False, has_betas=True ), OptimInfo( name='madgrad', opt_class=MADGRAD, description='Momentum-based Adaptive gradient method', has_momentum=True ), OptimInfo( name='madgradw', opt_class=MADGRAD, description='MADGRAD with decoupled weight decay', has_momentum=True, defaults={'decoupled_decay': True} ), OptimInfo( name='mars', opt_class=Mars, description='Unleashing the Power of Variance Reduction for Training Large Models', has_betas=True, ), OptimInfo( name='novograd', opt_class=NvNovoGrad, description='Normalized Adam with L2 norm gradient normalization', has_betas=True ), OptimInfo( name='rmsprop', opt_class=torch.optim.RMSprop, description='torch.optim.RMSprop, Root Mean Square Propagation', has_momentum=True, defaults={'alpha': 0.9} ), OptimInfo( name='rmsproptf', opt_class=RMSpropTF, description='TensorFlow-style RMSprop implementation, Root Mean Square Propagation', has_momentum=True, defaults={'alpha': 0.9} ), ] for opt in other_optimizers: registry.register(opt) registry.register_foreach_default('lion') def _register_apex_optimizers(registry: OptimizerRegistry) -> None: """Register APEX optimizers (lazy import)""" apex_optimizers = [ OptimInfo( name='fusedsgd', opt_class='apex.optimizers.FusedSGD', description='NVIDIA APEX fused SGD implementation for faster training', has_eps=False, has_momentum=True, defaults={'nesterov': True} ), OptimInfo( name='fusedadam', opt_class='apex.optimizers.FusedAdam', description='NVIDIA APEX fused Adam implementation', has_betas=True, defaults={'adam_w_mode': False} ), OptimInfo( name='fusedadamw', opt_class='apex.optimizers.FusedAdam', description='NVIDIA APEX fused AdamW implementation', has_betas=True, defaults={'adam_w_mode': True} ), OptimInfo( name='fusedlamb', opt_class='apex.optimizers.FusedLAMB', description='NVIDIA APEX fused LAMB implementation', has_betas=True ), OptimInfo( name='fusednovograd', opt_class='apex.optimizers.FusedNovoGrad', description='NVIDIA APEX fused NovoGrad implementation', has_betas=True, defaults={'betas': (0.95, 0.98)} ), ] for opt in apex_optimizers: registry.register(opt) def _register_bnb_optimizers(registry: OptimizerRegistry) -> None: """Register bitsandbytes optimizers (lazy import)""" bnb_optimizers = [ OptimInfo( name='bnbsgd', opt_class='bitsandbytes.optim.SGD', description='bitsandbytes SGD', has_eps=False, has_momentum=True, defaults={'nesterov': True} ), OptimInfo( name='bnbsgd8bit', opt_class='bitsandbytes.optim.SGD8bit', description='bitsandbytes 8-bit SGD with dynamic quantization', has_eps=False, has_momentum=True, defaults={'nesterov': True} ), OptimInfo( name='bnbadam', opt_class='bitsandbytes.optim.Adam', description='bitsandbytes Adam', has_betas=True ), OptimInfo( name='bnbadam8bit', opt_class='bitsandbytes.optim.Adam', description='bitsandbytes 8-bit Adam with dynamic quantization', has_betas=True ), OptimInfo( name='bnbadamw', opt_class='bitsandbytes.optim.AdamW', description='bitsandbytes AdamW', has_betas=True ), OptimInfo( name='bnbadamw8bit', opt_class='bitsandbytes.optim.AdamW', description='bitsandbytes 8-bit AdamW with dynamic quantization', has_betas=True ), OptimInfo( 'bnblion', 'bitsandbytes.optim.Lion', description='bitsandbytes Lion', has_eps=False, has_betas=True ), OptimInfo( 'bnblion8bit', 'bitsandbytes.optim.Lion8bit', description='bitsandbytes 8-bit Lion with dynamic quantization', has_eps=False, has_betas=True ), OptimInfo( 'bnbademamix', 'bitsandbytes.optim.AdEMAMix', description='bitsandbytes AdEMAMix', has_betas=True, num_betas=3, ), OptimInfo( 'bnbademamix8bit', 'bitsandbytes.optim.AdEMAMix8bit', description='bitsandbytes 8-bit AdEMAMix with dynamic quantization', has_betas=True, num_betas=3, ), ] for opt in bnb_optimizers: registry.register(opt) default_registry = OptimizerRegistry() def _register_default_optimizers() -> None: """Register all default optimizers to the global registry.""" # Register all optimizer groups _register_sgd_variants(default_registry) _register_adam_variants(default_registry) _register_lamb_lars(default_registry) _register_other_optimizers(default_registry) _register_apex_optimizers(default_registry) _register_bnb_optimizers(default_registry) _register_cautious_optimizers(default_registry) _register_corrected_decay_optimizers(default_registry) # Register aliases default_registry.register_alias('nesterov', 'sgd') default_registry.register_alias('nesterovw', 'sgdw') # Initialize default registry _register_default_optimizers() # Public API def list_optimizers( filter: Union[str, List[str]] = '', exclude_filters: Optional[List[str]] = None, with_description: bool = False, ) -> List[Union[str, Tuple[str, str]]]: """List available optimizer names, optionally filtered. List all registered optimizers, with optional filtering using wildcard patterns. Optimizers can be filtered using include and exclude patterns, and can optionally return descriptions with each optimizer name. Args: filter: Wildcard style filter string or list of filter strings (e.g., 'adam*' for all Adam variants, or ['adam*', '*8bit'] for Adam variants and 8-bit optimizers). Empty string means no filtering. exclude_filters: Optional list of wildcard patterns to exclude. For example, ['*8bit', 'fused*'] would exclude 8-bit and fused implementations. with_description: If True, returns tuples of (name, description) instead of just names. Descriptions provide brief explanations of optimizer characteristics. Returns: If with_description is False: List of optimizer names as strings (e.g., ['adam', 'adamw', ...]) If with_description is True: List of tuples of (name, description) (e.g., [('adam', 'Adaptive Moment...'), ...]) Examples: >>> list_optimizers() ['adam', 'adamw', 'sgd', ...] >>> list_optimizers(['la*', 'nla*']) # List lamb & lars ['lamb', 'lambc', 'larc', 'lars', 'nlarc', 'nlars'] >>> list_optimizers('*adam*', exclude_filters=['bnb*', 'fused*']) # Exclude bnb & apex adam optimizers ['adam', 'adamax', 'adamp', 'adamw', 'nadam', 'nadamw', 'radam'] >>> list_optimizers(with_description=True) # Get descriptions [('adabelief', 'Adapts learning rate based on gradient prediction error'), ('adadelta', 'torch.optim Adadelta, Adapts learning rates based on running windows of gradients'), ('adafactor', 'Memory-efficient implementation of Adam with factored gradients'), ...] """ return default_registry.list_optimizers(filter, exclude_filters, with_description) def get_optimizer_info(name: str) -> OptimInfo: """Get the OptimInfo for an optimizer. Args: name: Name of the optimizer Returns: OptimInfo configuration Raises: ValueError: If optimizer is not found """ return default_registry.get_optimizer_info(name) def get_optimizer_class( name: str, bind_defaults: bool = True, ) -> Union[OptimType, OptimizerCallable]: """Get optimizer class by name with option to bind default arguments. Retrieves the optimizer class or a partial function with default arguments bound. This allows direct instantiation of optimizers with their default configurations without going through the full factory. Args: name: Name of the optimizer to retrieve (e.g., 'adam', 'sgd') bind_defaults: If True, returns a partial function with default arguments from OptimInfo bound. If False, returns the raw optimizer class. Returns: If bind_defaults is False: The optimizer class (e.g., torch.optim.Adam) If bind_defaults is True: A partial function with default arguments bound Raises: ValueError: If optimizer name is not found in registry Examples: >>> # Get SGD with nesterov momentum default >>> SGD = get_optimizer_class('sgd') # nesterov=True bound >>> opt = SGD(model.parameters(), lr=0.1, momentum=0.9) >>> # Get raw optimizer class >>> SGD = get_optimizer_class('sgd') >>> opt = SGD(model.parameters(), lr=1e-3, momentum=0.9) """ return default_registry.get_optimizer_class(name, bind_defaults=bind_defaults) def create_optimizer_v2( model_or_params: Union[nn.Module, ParamsT], opt: str = 'sgd', lr: Optional[float] = None, weight_decay: float = 0., momentum: float = 0.9, foreach: Optional[bool] = None, filter_bias_and_bn: bool = True, layer_decay: Optional[float] = None, layer_decay_min_scale: float = 0.0, layer_decay_no_opt_scale: Optional[float] = None, param_group_fn: Optional[Callable[[nn.Module], ParamsT]] = None, **kwargs: Any, ) -> torch.optim.Optimizer: """Create an optimizer instance via timm registry. Creates and configures an optimizer with appropriate parameter groups and settings. Supports automatic parameter group creation for weight decay and layer-wise learning rates, as well as custom parameter grouping. Args: model_or_params: A PyTorch model or an iterable of parameters/parameter groups. If a model is provided, parameters will be automatically extracted and grouped based on the other arguments. opt: Name of the optimizer to create (e.g., 'adam', 'adamw', 'sgd'). Use list_optimizers() to see available options. lr: Learning rate. If None, will use the optimizer's default. weight_decay: Weight decay factor. Will be used to create param groups if model_or_params is a model. momentum: Momentum factor for optimizers that support it. Only used if the chosen optimizer accepts a momentum parameter. foreach: Enable/disable foreach (multi-tensor) implementation if available. If None, will use optimizer-specific defaults. filter_bias_and_bn: If True, bias, norm layer parameters (all 1d params) will not have weight decay applied. Only used when model_or_params is a model and weight_decay > 0. layer_decay: Optional layer-wise learning rate decay factor. If provided, learning rates will be scaled by layer_decay^(max_depth - layer_depth). Only used when model_or_params is a model. param_group_fn: Optional function to create custom parameter groups. If provided, other parameter grouping options will be ignored. **kwargs: Additional optimizer-specific arguments (e.g., betas for Adam). Returns: Configured optimizer instance. Examples: >>> # Basic usage with a model >>> optimizer = create_optimizer_v2(model, 'adamw', lr=1e-3) >>> # SGD with momentum and weight decay >>> optimizer = create_optimizer_v2( ... model, 'sgd', lr=0.1, momentum=0.9, weight_decay=1e-4 ... ) >>> # Adam with layer-wise learning rate decay >>> optimizer = create_optimizer_v2( ... model, 'adam', lr=1e-3, layer_decay=0.7 ... ) >>> # Custom parameter groups >>> def group_fn(model): ... return [ ... {'params': model.backbone.parameters(), 'lr': 1e-4}, ... {'params': model.head.parameters(), 'lr': 1e-3} ... ] >>> optimizer = create_optimizer_v2( ... model, 'sgd', param_group_fn=group_fn ... ) Note: Parameter group handling precedence: 1. If param_group_fn is provided, it will be used exclusively 2. If layer_decay is provided, layer-wise groups will be created 3. If weight_decay > 0 and filter_bias_and_bn is True, weight decay groups will be created 4. Otherwise, all parameters will be in a single group """ return default_registry.create_optimizer( model_or_params, opt=opt, lr=lr, weight_decay=weight_decay, momentum=momentum, foreach=foreach, weight_decay_exclude_1d=filter_bias_and_bn, layer_decay=layer_decay, layer_decay_min_scale=layer_decay_min_scale, layer_decay_no_opt_scale=layer_decay_no_opt_scale, param_group_fn=param_group_fn, **kwargs ) def optimizer_kwargs(cfg): """Convert argparse-style `cfg` object to kwargs for an optimizer factory.""" kwargs = { 'opt': cfg.opt, 'lr': cfg.lr, 'weight_decay': cfg.weight_decay, 'momentum': cfg.momentum, } if (eps := getattr(cfg, 'opt_eps', None)) is not None: kwargs['eps'] = eps if (betas := getattr(cfg, 'opt_betas', None)) is not None: kwargs['betas'] = betas if (layer_decay := getattr(cfg, 'layer_decay', None)) is not None: kwargs['layer_decay'] = layer_decay if (ld_min := getattr(cfg, 'layer_decay_min_scale', None)) is not None: kwargs['layer_decay_min_scale'] = ld_min if (ld_no_opt := getattr(cfg, 'layer_decay_no_opt_scale', None)) is not None: kwargs['layer_decay_no_opt_scale'] = ld_no_opt if (opt_args := getattr(cfg, 'opt_args', None)) is not None: kwargs.update(opt_args) if (foreach := getattr(cfg, 'opt_foreach', None)) is not None: kwargs['foreach'] = foreach return kwargs def create_optimizer( args, model: Union[nn.Module, ParamsT], filter_bias_and_bn: bool = True, ) -> torch.optim.Optimizer: """ Legacy optimizer factory for backwards compatibility. NOTE: Use create_optimizer_v2 for new code. """ return create_optimizer_v2( model, **optimizer_kwargs(cfg=args), filter_bias_and_bn=filter_bias_and_bn, )
pytorch-image-models/timm/optim/_optim_factory.py/0
{ "file_path": "pytorch-image-models/timm/optim/_optim_factory.py", "repo_id": "pytorch-image-models", "token_count": 21291 }
270
""" Lookahead Optimizer Wrapper. Implementation modified from: https://github.com/alphadl/lookahead.pytorch Paper: `Lookahead Optimizer: k steps forward, 1 step back` - https://arxiv.org/abs/1907.08610 Hacked together by / Copyright 2020 Ross Wightman """ from collections import OrderedDict from typing import Callable, Dict import torch from torch.optim.optimizer import Optimizer from collections import defaultdict class Lookahead(Optimizer): def __init__(self, base_optimizer, alpha=0.5, k=6): # NOTE super().__init__() not called on purpose self._optimizer_step_pre_hooks: Dict[int, Callable] = OrderedDict() self._optimizer_step_post_hooks: Dict[int, Callable] = OrderedDict() if not 0.0 <= alpha <= 1.0: raise ValueError(f'Invalid slow update rate: {alpha}') if not 1 <= k: raise ValueError(f'Invalid lookahead steps: {k}') defaults = dict(lookahead_alpha=alpha, lookahead_k=k, lookahead_step=0) self._base_optimizer = base_optimizer self.param_groups = base_optimizer.param_groups self.defaults = base_optimizer.defaults self.defaults.update(defaults) self.state = defaultdict(dict) # manually add our defaults to the param groups for name, default in defaults.items(): for group in self._base_optimizer.param_groups: group.setdefault(name, default) @torch.no_grad() def update_slow(self, group): for fast_p in group["params"]: if fast_p.grad is None: continue param_state = self._base_optimizer.state[fast_p] if 'lookahead_slow_buff' not in param_state: param_state['lookahead_slow_buff'] = torch.empty_like(fast_p) param_state['lookahead_slow_buff'].copy_(fast_p) slow = param_state['lookahead_slow_buff'] slow.add_(fast_p - slow, alpha=group['lookahead_alpha']) fast_p.copy_(slow) def sync_lookahead(self): for group in self._base_optimizer.param_groups: self.update_slow(group) @torch.no_grad() def step(self, closure=None): loss = self._base_optimizer.step(closure) for group in self._base_optimizer.param_groups: group['lookahead_step'] += 1 if group['lookahead_step'] % group['lookahead_k'] == 0: self.update_slow(group) return loss def state_dict(self): return self._base_optimizer.state_dict() def load_state_dict(self, state_dict): self._base_optimizer.load_state_dict(state_dict) self.param_groups = self._base_optimizer.param_groups
pytorch-image-models/timm/optim/lookahead.py/0
{ "file_path": "pytorch-image-models/timm/optim/lookahead.py", "repo_id": "pytorch-image-models", "token_count": 1134 }
271
""" Misc utils Hacked together by / Copyright 2020 Ross Wightman """ import argparse import ast import re def natural_key(string_): """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] def add_bool_arg(parser, name, default=False, help=''): dest_name = name.replace('-', '_') group = parser.add_mutually_exclusive_group(required=False) group.add_argument('--' + name, dest=dest_name, action='store_true', help=help) group.add_argument('--no-' + name, dest=dest_name, action='store_false', help=help) parser.set_defaults(**{dest_name: default}) class ParseKwargs(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): kw = {} for value in values: key, value = value.split('=') try: kw[key] = ast.literal_eval(value) except ValueError: kw[key] = str(value) # fallback to string (avoid need to escape on command line) setattr(namespace, self.dest, kw)
pytorch-image-models/timm/utils/misc.py/0
{ "file_path": "pytorch-image-models/timm/utils/misc.py", "repo_id": "pytorch-image-models", "token_count": 451 }
272
# Contributor Guidelines - Follow OOP principles - Be Pythonic: follow Python best practices and idiomatic patterns - Write unit tests for new functionality
smolagents/AGENTS.md/0
{ "file_path": "smolagents/AGENTS.md", "repo_id": "smolagents", "token_count": 33 }
273
# Text-to-SQL [[open-in-colab]] In this tutorial, we’ll see how to implement an agent that leverages SQL using `smolagents`. > Let's start with the golden question: why not keep it simple and use a standard text-to-SQL pipeline? A standard text-to-sql pipeline is brittle, since the generated SQL query can be incorrect. Even worse, the query could be incorrect, but not raise an error, instead giving some incorrect/useless outputs without raising an alarm. 👉 Instead, an agent system is able to critically inspect outputs and decide if the query needs to be changed or not, thus giving it a huge performance boost. Let’s build this agent! 💪 Run the line below to install required dependencies: ```bash !pip install smolagents python-dotenv sqlalchemy --upgrade -q ``` To call Inference Providers, you will need a valid token as your environment variable `HF_TOKEN`. We use python-dotenv to load it. ```py from dotenv import load_dotenv load_dotenv() ``` Then, we setup the SQL environment: ```py from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, Float, insert, inspect, text, ) engine = create_engine("sqlite:///:memory:") metadata_obj = MetaData() def insert_rows_into_table(rows, table, engine=engine): for row in rows: stmt = insert(table).values(**row) with engine.begin() as connection: connection.execute(stmt) table_name = "receipts" receipts = Table( table_name, metadata_obj, Column("receipt_id", Integer, primary_key=True), Column("customer_name", String(16), primary_key=True), Column("price", Float), Column("tip", Float), ) metadata_obj.create_all(engine) rows = [ {"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20}, {"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24}, {"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43}, {"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00}, ] insert_rows_into_table(rows, receipts) ``` ### Build our agent Now let’s make our SQL table retrievable by a tool. The tool’s description attribute will be embedded in the LLM’s prompt by the agent system: it gives the LLM information about how to use the tool. This is where we want to describe the SQL table. ```py inspector = inspect(engine) columns_info = [(col["name"], col["type"]) for col in inspector.get_columns("receipts")] table_description = "Columns:\n" + "\n".join([f" - {name}: {col_type}" for name, col_type in columns_info]) print(table_description) ``` ```text Columns: - receipt_id: INTEGER - customer_name: VARCHAR(16) - price: FLOAT - tip: FLOAT ``` Now let’s build our tool. It needs the following: (read [the tool doc](../tutorials/tools) for more detail) - A docstring with an `Args:` part listing arguments. - Type hints on both inputs and output. ```py from smolagents import tool @tool def sql_engine(query: str) -> str: """ Allows you to perform SQL queries on the table. Returns a string representation of the result. The table is named 'receipts'. Its description is as follows: Columns: - receipt_id: INTEGER - customer_name: VARCHAR(16) - price: FLOAT - tip: FLOAT Args: query: The query to perform. This should be correct SQL. """ output = "" with engine.connect() as con: rows = con.execute(text(query)) for row in rows: output += "\n" + str(row) return output ``` Now let us create an agent that leverages this tool. We use the `CodeAgent`, which is smolagents’ main agent class: an agent that writes actions in code and can iterate on previous output according to the ReAct framework. The model is the LLM that powers the agent system. `InferenceClientModel` allows you to call LLMs using HF’s Inference API, either via Serverless or Dedicated endpoint, but you could also use any proprietary API. ```py from smolagents import CodeAgent, InferenceClientModel agent = CodeAgent( tools=[sql_engine], model=InferenceClientModel(model_id="meta-llama/Llama-3.1-8B-Instruct"), ) agent.run("Can you give me the name of the client who got the most expensive receipt?") ``` ### Level 2: Table joins Now let’s make it more challenging! We want our agent to handle joins across multiple tables. So let’s make a second table recording the names of waiters for each receipt_id! ```py table_name = "waiters" waiters = Table( table_name, metadata_obj, Column("receipt_id", Integer, primary_key=True), Column("waiter_name", String(16), primary_key=True), ) metadata_obj.create_all(engine) rows = [ {"receipt_id": 1, "waiter_name": "Corey Johnson"}, {"receipt_id": 2, "waiter_name": "Michael Watts"}, {"receipt_id": 3, "waiter_name": "Michael Watts"}, {"receipt_id": 4, "waiter_name": "Margaret James"}, ] insert_rows_into_table(rows, waiters) ``` Since we changed the table, we update the `SQLExecutorTool` with this table’s description to let the LLM properly leverage information from this table. ```py updated_description = """Allows you to perform SQL queries on the table. Beware that this tool's output is a string representation of the execution output. It can use the following tables:""" inspector = inspect(engine) for table in ["receipts", "waiters"]: columns_info = [(col["name"], col["type"]) for col in inspector.get_columns(table)] table_description = f"Table '{table}':\n" table_description += "Columns:\n" + "\n".join([f" - {name}: {col_type}" for name, col_type in columns_info]) updated_description += "\n\n" + table_description print(updated_description) ``` Since this request is a bit harder than the previous one, we’ll switch the LLM engine to use the more powerful [Qwen/Qwen2.5-Coder-32B-Instruct](https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct)! ```py sql_engine.description = updated_description agent = CodeAgent( tools=[sql_engine], model=InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct"), ) agent.run("Which waiter got more total money from tips?") ``` It directly works! The setup was surprisingly simple, wasn’t it? This example is done! We've touched upon these concepts: - Building new tools. - Updating a tool's description. - Switching to a stronger LLM helps agent reasoning. ✅ Now you can go build this text-to-SQL system you’ve always dreamt of! ✨
smolagents/docs/source/en/examples/text_to_sql.md/0
{ "file_path": "smolagents/docs/source/en/examples/text_to_sql.md", "repo_id": "smolagents", "token_count": 2218 }
274
- title: Get started sections: - local: index title: 🤗 Agents - local: guided_tour title: गाइडेड टूर - title: Tutorials sections: - local: tutorials/building_good_agents title: ✨ अच्छे Agents का निर्माण - local: tutorials/inspect_runs title: 📊 OpenTelemetry के साथ runs का निरीक्षण - local: tutorials/tools title: 🛠️ Tools - in-depth guide - local: tutorials/secure_code_execution title: 🛡️ E2B के साथ अपने कोड एक्जीक्यूशन को सुरक्षित करें - title: Conceptual guides sections: - local: conceptual_guides/intro_agents title: 🤖 Agentic सिस्टम का परिचय - local: conceptual_guides/react title: 🤔 मल्टी-स्टेप एजेंट कैसे काम करते हैं? - title: Examples sections: - local: examples/text_to_sql title: सेल्फ करेक्टिंग Text-to-SQL - local: examples/rag title: एजेंटिक RAG के साथ अपनी ज्ञान आधारित को मास्टर करें - local: examples/multiagents title: एक बहु-एजेंट प्रणाली का आयोजन करें - title: Reference sections: - local: reference/agents title: एजेंट से संबंधित ऑब्जेक्ट्स - local: reference/tools title: टूल्स से संबंधित ऑब्जेक्ट्स
smolagents/docs/source/hi/_toctree.yml/0
{ "file_path": "smolagents/docs/source/hi/_toctree.yml", "repo_id": "smolagents", "token_count": 783 }
275
# 멀티 에이전트 시스템 오케스트레이션 🤖🤝🤖 [[Colab에서 열기]] 이 노트북에서는 **멀티 에이전트 웹 브라우저**를 만들어보겠습니다. 이는 웹을 사용하여 문제를 해결하기 위해 여러 에이전트가 협력하는 에이전트 시스템입니다! 멀티 에이전트는 간단한 계층 구조로 구성됩니다. ``` +----------------+ | Manager agent | +----------------+ | _______________|______________ | | Code Interpreter +------------------+ tool | Web Search agent | +------------------+ | | Web Search tool | Visit webpage tool ``` 이 시스템을 설정해보겠습니다. 다음 명령어를 실행하여 필요한 종속성을 설치합니다. ```py !pip install smolagents[toolkit] --upgrade -q ``` Inference Providers를 사용하기 위해 Hugging Face에 로그인합니다: ```py from huggingface_hub import login login() ``` ⚡️ 에이전트는 Hugging Face의 Inference API를 사용하는 `InferenceClientModel` 클래스를 통해 [Qwen/Qwen2.5-Coder-32B-Instruct](https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct)로 구동됩니다. Inference API를 사용하면 모든 오픈소스 모델을 빠르고 쉽게 실행할 수 있습니다. > [!TIP] > Inference Providers는 서버리스 추론 파트너가 지원하는 수백 개의 모델에 대한 액세스를 제공합니다. 지원되는 프로바이더 목록은 [여기](https://huggingface.co/docs/inference-providers/index)에서 확인할 수 있습니다. ```py model_id = "Qwen/Qwen2.5-Coder-32B-Instruct" ``` ## 🔍 웹 검색 도구 생성 웹 브라우징을 위해 Google 검색과 동등한 기능을 제공하는 기본 [`WebSearchTool`] 도구를 이미 사용할 수 있습니다. 하지만 `WebSearchTool`에서 찾은 페이지를 확인할 수 있는 기능도 필요합니다. 이를 위해 라이브러리에 내장된 `VisitWebpageTool`을 사용할 수도 있지만, 작동 원리를 이해하기 위해 직접 구현해보겠습니다. `markdownify`를 사용하여 `VisitWebpageTool` 도구를 처음부터 만들어보겠습니다. ```py import re import requests from markdownify import markdownify from requests.exceptions import RequestException from smolagents import tool @tool def visit_webpage(url: str) -> str: """주어진 URL의 웹페이지에 접속하여 그 내용을 마크다운 형식의 반환합니다. 매개변수: url: 방문할 웹페이지의 URL. 반환값: 마크다운으로 변환된 웹페이지 내용, 또는 요청이 실패할 경우 오류 메시지. """ try: # URL에 GET 요청 전송 response = requests.get(url) response.raise_for_status() # 잘못된 상태 코드에 대해 예외 발생 # HTML 내용을 마크다운으로 변환 markdown_content = markdownify(response.text).strip() # 여러 줄 바꿈 제거 markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content) return markdown_content except RequestException as e: return f"Error fetching the webpage: {str(e)}" except Exception as e: return f"An unexpected error occurred: {str(e)}" ``` 이제 도구를 초기화하고 테스트해보겠습니다! ```py print(visit_webpage("https://en.wikipedia.org/wiki/Hugging_Face")[:500]) ``` ## 멀티 에이전트 시스템 구축 🤖🤝🤖 이제 `search`와 `visit_webpage` 도구가 모두 준비되었으므로, 이를 사용하여 웹 에이전트를 생성할 수 있습니다. 이 에이전트에 어떤 구성을 선택할까요? - 웹 브라우징은 병렬 도구 호출이 필요없는 단일 타임라인 작업이므로, JSON 도구 호출 방식이 적합합니다. 따라서 `ToolCallingAgent`를 선택합니다. - 또한 웹 검색은 올바른 답을 찾기 전에 많은 페이지를 탐색해야 하는 경우가 있으므로, `max_steps`를 10으로 늘리는 것이 좋습니다. ```py from smolagents import ( CodeAgent, ToolCallingAgent, InferenceClientModel, WebSearchTool, LiteLLMModel, ) model = InferenceClientModel(model_id=model_id) web_agent = ToolCallingAgent( tools=[WebSearchTool(), visit_webpage], model=model, max_steps=10, name="web_search_agent", description="Runs web searches for you.", ) ``` 이 에이전트에 `name`과 `description` 속성을 부여했습니다. 이는 이 에이전트가 매니저 에이전트에 의해 호출될 수 있도록 하는 필수 속성입니다. 그 다음 매니저 에이전트를 생성하고, 초기화 시 `managed_agents` 인수에 관리되는 에이전트를 전달합니다. 이 에이전트는 계획과 사고를 담당하므로, 고급 추론이 유용할 것입니다. 따라서 `CodeAgent`가 잘 작동할 것입니다. 또한 현재 연도를 포함하고 추가 데이터 계산을 수행하는 질문을 하고 싶으므로, 에이전트가 이러한 패키지를 필요로 할 경우에 대비해 `additional_authorized_imports=["time", "numpy", "pandas"]`를 추가해보겠습니다. ```py manager_agent = CodeAgent( tools=[], model=model, managed_agents=[web_agent], additional_authorized_imports=["time", "numpy", "pandas"], ) ``` 이게 전부입니다! 이제 시스템을 실행해보겠습니다! 계산과 연구가 모두 필요한 질문을 선택합니다. ```py answer = manager_agent.run("LLM 훈련이 현재 속도로 2030년까지 계속 확장된다면, 2030년까지 가장 큰 훈련 실행에 전력을 공급하는 데 필요한 전력량은 GW 단위로 얼마가 될까요? 이는 일부 국가들과 비교했을 때 무엇에 해당할까요? 사용된 모든 수치에 대한 출처를 제공해주세요.") ``` 답변으로 이런 보고서를 받습니다. ``` 현재 성장 전망과 에너지 소비량 추정에 따르면, 2030년까지 LLM 교육이 현재 속도로 계속 확장된다면 다음과 같이 예상됩니다. 1. 2030년까지 가장 큰 훈련 실행에 전력을 공급하는 데 필요한 전력량은 약 303.74 GW가 될 것이며, 이는 연간 약 2,660,762 GWh로 환산됩니다. 2. 국가별 전력 소비량 비교 - 중국 총 전력 소비량의 약 34%에 해당합니다. - 인도(184%), 러시아(267%), 일본(291%)의 총 전력 소비량을 초과할 것입니다. - 이탈리아나 멕시코 같은 국가들의 전력 소비량의 거의 9배가 됩니다. 3. 수치 출처 - 미래 LLM 훈련을 위한 5 GW의 초기 추정치는 AWS CEO Matt Garman에서 나온 것입니다. - 성장 예측은 Springs의 시장 조사에서 79.80%의 CAGR을 사용했습니다. - 국가 전력 소비 데이터는 주로 2021년 기준으로 미국 에너지 정보 관리청에서 나온 것입니다. ``` [스케일링 가설](https://gwern.net/scaling-hypothesis)이 계속 참이라면 상당히 큰 발전소가 필요할 것 같습니다. 에이전트들이 작업을 해결하기 위해 효율적으로 협력했습니다! ✅ 💡 이 오케스트레이션을 더 많은 에이전트로 쉽게 확장할 수 있습니다: 하나는 코드 실행을, 다른 하나는 웹 검색을, 또 다른 하나는 파일 처리를 담당하는 식으로...
smolagents/docs/source/ko/examples/multiagents.md/0
{ "file_path": "smolagents/docs/source/ko/examples/multiagents.md", "repo_id": "smolagents", "token_count": 5355 }
276
# 构建好用的 agent [[open-in-colab]] 能良好工作的 agent 和不能工作的 agent 之间,有天壤之别。 我们怎么样才能构建出属于前者的 agent 呢? 在本指南中,我们将看到构建 agent 的最佳实践。 > [!TIP] > 如果你是 agent 构建的新手,请确保首先阅读 [agent 介绍](../conceptual_guides/intro_agents) 和 [smolagents 导览](../guided_tour)。 ### 最好的 agent 系统是最简单的:尽可能简化工作流 在你的工作流中赋予 LLM 一些自主权,会引入一些错误风险。 经过良好编程的 agent 系统,通常具有良好的错误日志记录和重试机制,因此 LLM 引擎有机会自我纠错。但为了最大限度地降低 LLM 错误的风险,你应该简化你的工作流! 让我们回顾一下 [agent 介绍](../conceptual_guides/intro_agents) 中的例子:一个为冲浪旅行公司回答用户咨询的机器人。 与其让 agent 每次被问及新的冲浪地点时,都分别调用 "旅行距离 API" 和 "天气 API",你可以只创建一个统一的工具 "return_spot_information",一个同时调用这两个 API,并返回它们连接输出的函数。 这可以降低成本、延迟和错误风险! 主要的指导原则是:尽可能减少 LLM 调用的次数。 这可以带来一些启发: - 尽可能把两个工具合并为一个,就像我们两个 API 的例子。 - 尽可能基于确定性函数,而不是 agent 决策,来实现逻辑。 ### 改善流向 LLM 引擎的信息流 记住,你的 LLM 引擎就像一个 ~智能~ 机器人,被关在一个房间里,与外界唯一的交流方式是通过门缝传递的纸条。 如果你没有明确地将信息放入其提示中,它将不知道发生的任何事情。 所以首先要让你的任务非常清晰! 由于 agent 由 LLM 驱动,任务表述的微小变化可能会产生完全不同的结果。 然后,改善工具使用中流向 agent 的信息流。 需要遵循的具体指南: - 每个工具都应该记录(只需在工具的 `forward` 方法中使用 `print` 语句)对 LLM 引擎可能有用的所有信息。 - 特别是,记录工具执行错误的详细信息会很有帮助! 例如,这里有一个根据位置和日期时间检索天气数据的工具: 首先,这是一个糟糕的版本: ```python import datetime from smolagents import tool def get_weather_report_at_coordinates(coordinates, date_time): # 虚拟函数,返回 [温度(°C),降雨风险(0-1),浪高(m)] return [28.0, 0.35, 0.85] def get_coordinates_from_location(location): # 返回虚拟坐标 return [3.3, -42.0] @tool def get_weather_api(location: str, date_time: str) -> str: """ Returns the weather report. Args: location: the name of the place that you want the weather for. date_time: the date and time for which you want the report. """ lon, lat = convert_location_to_coordinates(location) date_time = datetime.strptime(date_time) return str(get_weather_report_at_coordinates((lon, lat), date_time)) ``` 为什么它不好? - 没有说明 `date_time` 应该使用的格式 - 没有说明位置应该如何指定 - 没有记录机制来处理明确的报错情况,如位置格式不正确或 date_time 格式不正确 - 输出格式难以理解 如果工具调用失败,内存中记录的错误跟踪,可以帮助 LLM 逆向工程工具来修复错误。但为什么要让它做这么多繁重的工作呢? 构建这个工具的更好方式如下: ```python @tool def get_weather_api(location: str, date_time: str) -> str: """ Returns the weather report. Args: location: the name of the place that you want the weather for. Should be a place name, followed by possibly a city name, then a country, like "Anchor Point, Taghazout, Morocco". date_time: the date and time for which you want the report, formatted as '%m/%d/%y %H:%M:%S'. """ lon, lat = convert_location_to_coordinates(location) try: date_time = datetime.strptime(date_time) except Exception as e: raise ValueError("Conversion of `date_time` to datetime format failed, make sure to provide a string in format '%m/%d/%y %H:%M:%S'. Full trace:" + str(e)) temperature_celsius, risk_of_rain, wave_height = get_weather_report_at_coordinates((lon, lat), date_time) return f"Weather report for {location}, {date_time}: Temperature will be {temperature_celsius}°C, risk of rain is {risk_of_rain*100:.0f}%, wave height is {wave_height}m." ``` 一般来说,为了减轻 LLM 的负担,要问自己的好问题是:"如果我是一个第一次使用这个工具的傻瓜,使用这个工具编程并纠正自己的错误有多容易?"。 ### 给 agent 更多参数 除了简单的任务描述字符串外,你还可以使用 `additional_args` 参数传递任何类型的对象: ```py from smolagents import CodeAgent, InferenceClientModel model_id = "meta-llama/Llama-3.3-70B-Instruct" agent = CodeAgent(tools=[], model=InferenceClientModel(model_id=model_id), add_base_tools=True) agent.run( "Why does Mike not know many people in New York?", additional_args={"mp3_sound_file_url":'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/recording.mp3'} ) ``` 例如,你可以使用这个 `additional_args` 参数传递你希望 agent 利用的图像或字符串。 ## 如何调试你的 agent ### 1. 使用更强大的 LLM 在 agent 工作流中,有些错误是实际错误,有些则是你的 LLM 引擎没有正确推理的结果。 例如,参考这个我要求创建一个汽车图片的 `CodeAgent` 的运行记录: ```text ==================================================================================================== New task ==================================================================================================== Make me a cool car picture ──────────────────────────────────────────────────────────────────────────────────────────────────── New step ───────────────────────────────────────────────────────────────────────────────────────────────────── Agent is executing the code below: ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── image_generator(prompt="A cool, futuristic sports car with LED headlights, aerodynamic design, and vibrant color, high-res, photorealistic") ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Last output from code snippet: ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── /var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png Step 1: - Time taken: 16.35 seconds - Input tokens: 1,383 - Output tokens: 77 ──────────────────────────────────────────────────────────────────────────────────────────────────── New step ───────────────────────────────────────────────────────────────────────────────────────────────────── Agent is executing the code below: ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── final_answer("/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png") ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Print outputs: Last output from code snippet: ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── /var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png Final answer: /var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png ``` 用户看到的是返回了一个路径,而不是图像。 这看起来像是系统的错误,但实际上 agent 系统并没有导致错误:只是 LLM 大脑犯了一个错误,没有把图像输出,保存到变量中。 因此,它无法再次访问图像,只能利用保存图像时记录的路径,所以它返回的是路径,而不是图像。 调试 agent 的第一步是"使用更强大的 LLM"。像 `Qwen2.5-72B-Instruct` 这样的替代方案不会犯这种错误。 ### 2. 提供更多指导/更多信息 你也可以使用不太强大的模型,只要你更有效地指导它们。 站在模型的角度思考:如果你是模型在解决任务,你会因为系统提示+任务表述+工具描述中提供的信息而挣扎吗? 你需要一些额外的说明吗? 为了提供额外信息,我们不建议立即更改系统提示:默认系统提示有许多调整,除非你非常了解提示,否则你很容易翻车。 更好的指导 LLM 引擎的方法是: - 如果是关于要解决的任务:把所有细节添加到任务中。任务可以有几百页长。 - 如果是关于如何使用工具:你的工具的 description 属性。 ### 3. 更改系统提示(通常不建议) 如果上述说明不够,你可以更改系统提示。 让我们看看它是如何工作的。例如,让我们检查 [`CodeAgent`] 的默认系统提示(下面的版本通过跳过零样本示例进行了缩短)。 ```python print(agent.prompt_templates["system_prompt"]) ``` 你会得到: ```text You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can. To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code. To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences. At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use. Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence. During each intermediate step, you can use 'print()' to save whatever important information you will then need. These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step. In the end you have to return a final answer using the `final_answer` tool. Here are a few examples using notional tools: --- Task: "Generate an image of the oldest person in this document." Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer. Code: ```py answer = document_qa(document=document, question="Who is the oldest person mentioned?") print(answer) ```<end_code> Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland." Thought: I will now generate an image showcasing the oldest person. Code: ```py image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.") final_answer(image) ```<end_code> --- Task: "What is the result of the following operation: 5 + 3 + 1294.678?" Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool Code: ```py result = 5 + 3 + 1294.678 final_answer(result) ```<end_code> --- Task: "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French. You have been provided with these additional arguments, that you can access using the keys as variables in your python code: {'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}" Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image. Code: ```py translated_question = translator(question=question, src_lang="French", tgt_lang="English") print(f"The translated question is {translated_question}.") answer = image_qa(image=image, question=translated_question) final_answer(f"The answer is {answer}") ```<end_code> --- Task: In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer. What does he say was the consequence of Einstein learning too much math on his creativity, in one word? Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin. Code: ```py pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein") print(pages) ```<end_code> Observation: No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein". Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query. Code: ```py pages = search(query="1979 interview Stanislaus Ulam") print(pages) ```<end_code> Observation: Found 6 pages: [Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/) [Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/) (truncated) Thought: I will read the first 2 pages to know more. Code: ```py for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]: whole_page = visit_webpage(url) print(whole_page) print("\n" + "="*80 + "\n") # Print separator between pages ```<end_code> Observation: Manhattan Project Locations: Los Alamos, NM Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at (truncated) Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word. Code: ```py final_answer("diminished") ```<end_code> --- Task: "Which city has the highest population: Guangzhou or Shanghai?" Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities. Code: ```py for city in ["Guangzhou", "Shanghai"]: print(f"Population {city}:", search(f"{city} population") ```<end_code> Observation: Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.'] Population Shanghai: '26 million (2019)' Thought: Now I know that Shanghai has the highest population. Code: ```py final_answer("Shanghai") ```<end_code> --- Task: "What is the current age of the pope, raised to the power 0.36?" Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search. Code: ```py pope_age_wiki = wiki(query="current pope age") print("Pope age as per wikipedia:", pope_age_wiki) pope_age_search = web_search(query="current pope age") print("Pope age as per google search:", pope_age_search) ```<end_code> Observation: Pope age: "The pope Francis is currently 88 years old." Thought: I know that the pope is 88 years old. Let's compute the result using python code. Code: ```py pope_current_age = 88 ** 0.36 final_answer(pope_current_age) ```<end_code> Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools: {%- for tool in tools.values() %} - {{ tool.to_tool_calling_prompt() }} {%- endfor %} {%- if managed_agents and managed_agents.values() | list %} You can also give tasks to team members. Calling a team member works similarly to calling a tool: provide the task description as the 'task' argument. Since this team member is a real human, be as detailed and verbose as necessary in your task description. You can also include any relevant variables or context using the 'additional_args' argument. Here is a list of the team members that you can call: {%- for agent in managed_agents.values() %} - {{ agent.name }}: {{ agent.description }} {%- endfor %} {%- endif %} Here are the rules you should always follow to solve your task: 1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail. 2. Use only variables that you have defined! 3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'. 4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block. 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters. 6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'. 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables. 8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}} 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist. 10. Don't give up! You're in charge of solving the task, not providing directions to solve it. Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000. ``` 如你所见,有一些占位符,如 `"{{ tool.description }}"`:这些将在 agent 初始化时用于插入某些自动生成的工具或管理 agent 的描述。 因此,虽然你可以通过将自定义提示作为参数传递给 `system_prompt` 参数来覆盖此系统提示模板,但你的新系统提示必须包含以下占位符: - 用于插入工具描述。 ``` {%- for tool in tools.values() %} - {{ tool.to_tool_calling_prompt() }} {%- endfor %} ``` - 用于插入 managed agent 的描述(如果有)。 ``` {%- if managed_agents and managed_agents.values() | list %} You can also give tasks to team members. Calling a team member works similarly to calling a tool: provide the task description as the 'task' argument. Since this team member is a real human, be as detailed and verbose as necessary in your task description. You can also include any relevant variables or context using the 'additional_args' argument. Here is a list of the team members that you can call: {%- for agent in managed_agents.values() %} - {{ agent.name }}: {{ agent.description }} {%- endfor %} {%- endif %} ``` - 仅限 `CodeAgent`:`"{{authorized_imports}}"` 用于插入授权导入列表。 然后你可以根据如下,更改系统提示: ```py agent.prompt_templates["system_prompt"] = agent.prompt_templates["system_prompt"] + "\nHere you go!" ``` 这也适用于 [`ToolCallingAgent`]。 ### 4. 额外规划 我们提供了一个用于补充规划步骤的模型,agent 可以在正常操作步骤之间定期运行。在此步骤中,没有工具调用,LLM 只是被要求更新它知道的事实列表,并根据这些事实反推它应该采取的下一步。 ```py from smolagents import load_tool, CodeAgent, InferenceClientModel, WebSearchTool from dotenv import load_dotenv load_dotenv() # 从 Hub 导入工具 image_generation_tool = load_tool("m-ric/text-to-image", trust_remote_code=True) search_tool = WebSearchTool() agent = CodeAgent( tools=[search_tool], model=InferenceClientModel(model_id="Qwen/Qwen2.5-72B-Instruct"), planning_interval=3 # 这是你激活规划的地方! ) # 运行它! result = agent.run( "How long would a cheetah at full speed take to run the length of Pont Alexandre III?", ) ```
smolagents/docs/source/zh/tutorials/building_good_agents.md/0
{ "file_path": "smolagents/docs/source/zh/tutorials/building_good_agents.md", "repo_id": "smolagents", "token_count": 8362 }
277
from run import create_agent from smolagents.gradio_ui import GradioUI agent = create_agent() demo = GradioUI(agent) if __name__ == "__main__": demo.launch()
smolagents/examples/open_deep_research/app.py/0
{ "file_path": "smolagents/examples/open_deep_research/app.py", "repo_id": "smolagents", "token_count": 61 }
278
import os import datasets from langchain.docstore.document import Document from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_chroma import Chroma # from langchain_community.document_loaders import PyPDFLoader from langchain_huggingface import HuggingFaceEmbeddings from tqdm import tqdm from transformers import AutoTokenizer # from langchain_openai import OpenAIEmbeddings from smolagents import LiteLLMModel, Tool from smolagents.agents import CodeAgent # from smolagents.agents import ToolCallingAgent knowledge_base = datasets.load_dataset("m-ric/huggingface_doc", split="train") source_docs = [ Document(page_content=doc["text"], metadata={"source": doc["source"].split("/")[1]}) for doc in knowledge_base ] ## For your own PDFs, you can use the following code to load them into source_docs # pdf_directory = "pdfs" # pdf_files = [ # os.path.join(pdf_directory, f) # for f in os.listdir(pdf_directory) # if f.endswith(".pdf") # ] # source_docs = [] # for file_path in pdf_files: # loader = PyPDFLoader(file_path) # docs.extend(loader.load()) text_splitter = RecursiveCharacterTextSplitter.from_huggingface_tokenizer( AutoTokenizer.from_pretrained("thenlper/gte-small"), chunk_size=200, chunk_overlap=20, add_start_index=True, strip_whitespace=True, separators=["\n\n", "\n", ".", " ", ""], ) # Split docs and keep only unique ones print("Splitting documents...") docs_processed = [] unique_texts = {} for doc in tqdm(source_docs): new_docs = text_splitter.split_documents([doc]) for new_doc in new_docs: if new_doc.page_content not in unique_texts: unique_texts[new_doc.page_content] = True docs_processed.append(new_doc) print("Embedding documents... This should take a few minutes (5 minutes on MacBook with M1 Pro)") # Initialize embeddings and ChromaDB vector store embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2") # embeddings = OpenAIEmbeddings(model="text-embedding-3-small") vector_store = Chroma.from_documents(docs_processed, embeddings, persist_directory="./chroma_db") class RetrieverTool(Tool): name = "retriever" description = ( "Uses semantic search to retrieve the parts of documentation that could be most relevant to answer your query." ) inputs = { "query": { "type": "string", "description": "The query to perform. This should be semantically close to your target documents. Use the affirmative form rather than a question.", } } output_type = "string" def __init__(self, vector_store, **kwargs): super().__init__(**kwargs) self.vector_store = vector_store def forward(self, query: str) -> str: assert isinstance(query, str), "Your search query must be a string" docs = self.vector_store.similarity_search(query, k=3) return "\nRetrieved documents:\n" + "".join( [f"\n\n===== Document {str(i)} =====\n" + doc.page_content for i, doc in enumerate(docs)] ) retriever_tool = RetrieverTool(vector_store) # Choose which LLM engine to use! # from smolagents import InferenceClientModel # model = InferenceClientModel(model_id="meta-llama/Llama-3.3-70B-Instruct") # from smolagents import TransformersModel # model = TransformersModel(model_id="meta-llama/Llama-3.2-2B-Instruct") # For anthropic: change model_id below to 'anthropic/claude-3-5-sonnet-20240620' and also change 'os.environ.get("ANTHROPIC_API_KEY")' model = LiteLLMModel( model_id="groq/llama-3.3-70b-versatile", api_key=os.environ.get("GROQ_API_KEY"), ) # # You can also use the ToolCallingAgent class # agent = ToolCallingAgent( # tools=[retriever_tool], # model=model, # verbose=True, # ) agent = CodeAgent( tools=[retriever_tool], model=model, max_steps=4, verbosity_level=2, stream_outputs=True, ) agent_output = agent.run("How can I push a model to the Hub?") print("Final output:") print(agent_output)
smolagents/examples/rag_using_chromadb.py/0
{ "file_path": "smolagents/examples/rag_using_chromadb.py", "repo_id": "smolagents", "token_count": 1508 }
279
#!/usr/bin/env python # coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import ast import builtins import difflib import inspect import logging import math import re from abc import ABC, abstractmethod from collections.abc import Callable, Generator, Mapping from dataclasses import dataclass from functools import wraps from importlib import import_module from importlib.util import find_spec from types import BuiltinFunctionType, FunctionType, ModuleType from typing import Any from .tools import Tool from .utils import BASE_BUILTIN_MODULES, truncate_content logger = logging.getLogger(__name__) class InterpreterError(ValueError): """ An error raised when the interpreter cannot evaluate a Python expression, due to syntax error or unsupported operations. """ pass ERRORS = { name: getattr(builtins, name) for name in dir(builtins) if isinstance(getattr(builtins, name), type) and issubclass(getattr(builtins, name), BaseException) } DEFAULT_MAX_LEN_OUTPUT = 50000 MAX_OPERATIONS = 10000000 MAX_WHILE_ITERATIONS = 1000000 ALLOWED_DUNDER_METHODS = ["__init__", "__str__", "__repr__"] def custom_print(*args): return None def nodunder_getattr(obj, name, default=None): if name.startswith("__") and name.endswith("__"): raise InterpreterError(f"Forbidden access to dunder attribute: {name}") return getattr(obj, name, default) BASE_PYTHON_TOOLS = { "print": custom_print, "isinstance": isinstance, "range": range, "float": float, "int": int, "bool": bool, "str": str, "set": set, "list": list, "dict": dict, "tuple": tuple, "round": round, "ceil": math.ceil, "floor": math.floor, "log": math.log, "exp": math.exp, "sin": math.sin, "cos": math.cos, "tan": math.tan, "asin": math.asin, "acos": math.acos, "atan": math.atan, "atan2": math.atan2, "degrees": math.degrees, "radians": math.radians, "pow": pow, "sqrt": math.sqrt, "len": len, "sum": sum, "max": max, "min": min, "abs": abs, "enumerate": enumerate, "zip": zip, "reversed": reversed, "sorted": sorted, "all": all, "any": any, "map": map, "filter": filter, "ord": ord, "chr": chr, "next": next, "iter": iter, "divmod": divmod, "callable": callable, "getattr": nodunder_getattr, "hasattr": hasattr, "setattr": setattr, "issubclass": issubclass, "type": type, "complex": complex, } # Non-exhaustive list of dangerous modules that should not be imported DANGEROUS_MODULES = [ "builtins", "io", "multiprocessing", "os", "pathlib", "pty", "shutil", "socket", "subprocess", "sys", ] DANGEROUS_FUNCTIONS = [ "builtins.compile", "builtins.eval", "builtins.exec", "builtins.globals", "builtins.locals", "builtins.__import__", "os.popen", "os.system", "posix.system", ] def check_safer_result(result: Any, static_tools: dict[str, Callable] = None, authorized_imports: list[str] = None): """ Checks if a result is safer according to authorized imports and static tools. Args: result (Any): The result to check. static_tools (dict[str, Callable]): Dictionary of static tools. authorized_imports (list[str]): List of authorized imports. Raises: InterpreterError: If the result is not safe """ if isinstance(result, ModuleType): if not check_import_authorized(result.__name__, authorized_imports): raise InterpreterError(f"Forbidden access to module: {result.__name__}") elif isinstance(result, dict) and result.get("__spec__"): if not check_import_authorized(result["__name__"], authorized_imports): raise InterpreterError(f"Forbidden access to module: {result['__name__']}") elif isinstance(result, (FunctionType, BuiltinFunctionType)): for qualified_function_name in DANGEROUS_FUNCTIONS: module_name, function_name = qualified_function_name.rsplit(".", 1) if ( (static_tools is None or function_name not in static_tools) and result.__name__ == function_name and result.__module__ == module_name ): raise InterpreterError(f"Forbidden access to function: {function_name}") def safer_eval(func: Callable): """ Decorator to enhance the security of an evaluation function by checking its return value. Args: func (Callable): Evaluation function to be made safer. Returns: Callable: Safer evaluation function with return value check. """ @wraps(func) def _check_return( expression, state, static_tools, custom_tools, authorized_imports=BASE_BUILTIN_MODULES, ): result = func(expression, state, static_tools, custom_tools, authorized_imports=authorized_imports) check_safer_result(result, static_tools, authorized_imports) return result return _check_return def safer_func( func: Callable, static_tools: dict[str, Callable] = BASE_PYTHON_TOOLS, authorized_imports: list[str] = BASE_BUILTIN_MODULES, ): """ Decorator to enhance the security of a function call by checking its return value. Args: func (Callable): Function to be made safer. static_tools (dict[str, Callable]): Dictionary of static tools. authorized_imports (list[str]): List of authorized imports. Returns: Callable: Safer function with return value check. """ # If the function is a type, return it directly without wrapping if isinstance(func, type): return func @wraps(func) def _check_return(*args, **kwargs): result = func(*args, **kwargs) check_safer_result(result, static_tools, authorized_imports) return result return _check_return class PrintContainer: def __init__(self): self.value = "" def append(self, text): self.value += text return self def __iadd__(self, other): """Implements the += operator""" self.value += str(other) return self def __str__(self): """String representation""" return self.value def __repr__(self): """Representation for debugging""" return f"PrintContainer({self.value})" def __len__(self): """Implements len() function support""" return len(self.value) class BreakException(Exception): pass class ContinueException(Exception): pass class ReturnException(Exception): def __init__(self, value): self.value = value def get_iterable(obj): if isinstance(obj, list): return obj elif hasattr(obj, "__iter__"): return list(obj) else: raise InterpreterError("Object is not iterable") def fix_final_answer_code(code: str) -> str: """ Sometimes an LLM can try to assign a variable to final_answer, which would break the final_answer() tool. This function fixes this behaviour by replacing variable assignments to final_answer with final_answer_variable, while preserving function calls to final_answer(). """ # First, find if there's a direct assignment to final_answer # Use word boundary and negative lookbehind to ensure it's not an object attribute assignment_pattern = r"(?<!\.)(?<!\w)\bfinal_answer\s*=" if "final_answer(" not in code or not re.search(assignment_pattern, code): # If final_answer tool is not called in this blob, then doing the replacement is hazardous because it could false the model's memory for next steps. # Let's not modify the code and leave the subsequent assignment error happen. return code # Pattern for replacing variable assignments # Looks for 'final_answer' followed by '=' with optional whitespace # Negative lookbehind ensures we don't match object attributes assignment_regex = r"(?<!\.)(?<!\w)(\bfinal_answer)(\s*=)" code = re.sub(assignment_regex, r"final_answer_variable\2", code) # Pattern for replacing variable usage but not function calls # Negative lookahead (?!\s*\() ensures we don't match function calls # Negative lookbehind (?<!\.|\w) ensures we don't match object methods or other variables variable_regex = r"(?<!\.)(?<!\w)(\bfinal_answer\b)(?!\s*\()" code = re.sub(variable_regex, "final_answer_variable", code) return code def build_import_tree(authorized_imports: list[str]) -> dict[str, Any]: tree = {} for import_path in authorized_imports: parts = import_path.split(".") current = tree for part in parts: if part not in current: current[part] = {} current = current[part] return tree def check_import_authorized(import_to_check: str, authorized_imports: list[str]) -> bool: current_node = build_import_tree(authorized_imports) for part in import_to_check.split("."): if "*" in current_node: return True if part not in current_node: return False current_node = current_node[part] return True def evaluate_attribute( expression: ast.Attribute, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: if expression.attr.startswith("__") and expression.attr.endswith("__"): raise InterpreterError(f"Forbidden access to dunder attribute: {expression.attr}") value = evaluate_ast(expression.value, state, static_tools, custom_tools, authorized_imports) return getattr(value, expression.attr) def evaluate_unaryop( expression: ast.UnaryOp, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: operand = evaluate_ast(expression.operand, state, static_tools, custom_tools, authorized_imports) if isinstance(expression.op, ast.USub): return -operand elif isinstance(expression.op, ast.UAdd): return operand elif isinstance(expression.op, ast.Not): return not operand elif isinstance(expression.op, ast.Invert): return ~operand else: raise InterpreterError(f"Unary operation {expression.op.__class__.__name__} is not supported.") def evaluate_lambda( lambda_expression: ast.Lambda, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Callable: args = [arg.arg for arg in lambda_expression.args.args] def lambda_func(*values: Any) -> Any: new_state = state.copy() for arg, value in zip(args, values): new_state[arg] = value return evaluate_ast( lambda_expression.body, new_state, static_tools, custom_tools, authorized_imports, ) return lambda_func def evaluate_while( while_loop: ast.While, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> None: iterations = 0 while evaluate_ast(while_loop.test, state, static_tools, custom_tools, authorized_imports): for node in while_loop.body: try: evaluate_ast(node, state, static_tools, custom_tools, authorized_imports) except BreakException: return None except ContinueException: break iterations += 1 if iterations > MAX_WHILE_ITERATIONS: raise InterpreterError(f"Maximum number of {MAX_WHILE_ITERATIONS} iterations in While loop exceeded") return None def create_function( func_def: ast.FunctionDef, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Callable: source_code = ast.unparse(func_def) def new_func(*args: Any, **kwargs: Any) -> Any: func_state = state.copy() arg_names = [arg.arg for arg in func_def.args.args] default_values = [ evaluate_ast(d, state, static_tools, custom_tools, authorized_imports) for d in func_def.args.defaults ] # Apply default values defaults = dict(zip(arg_names[-len(default_values) :], default_values)) # Set positional arguments for name, value in zip(arg_names, args): func_state[name] = value # Set keyword arguments for name, value in kwargs.items(): func_state[name] = value # Handle variable arguments if func_def.args.vararg: vararg_name = func_def.args.vararg.arg func_state[vararg_name] = args if func_def.args.kwarg: kwarg_name = func_def.args.kwarg.arg func_state[kwarg_name] = kwargs # Set default values for arguments that were not provided for name, value in defaults.items(): if name not in func_state: func_state[name] = value # Update function state with self and __class__ if func_def.args.args and func_def.args.args[0].arg == "self": if args: func_state["self"] = args[0] func_state["__class__"] = args[0].__class__ result = None try: for stmt in func_def.body: result = evaluate_ast(stmt, func_state, static_tools, custom_tools, authorized_imports) except ReturnException as e: result = e.value if func_def.name == "__init__": return None return result # Store original AST, source code, and name new_func.__ast__ = func_def new_func.__source__ = source_code new_func.__name__ = func_def.name return new_func def evaluate_function_def( func_def: ast.FunctionDef, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Callable: custom_tools[func_def.name] = create_function(func_def, state, static_tools, custom_tools, authorized_imports) return custom_tools[func_def.name] def evaluate_class_def( class_def: ast.ClassDef, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> type: class_name = class_def.name bases = [evaluate_ast(base, state, static_tools, custom_tools, authorized_imports) for base in class_def.bases] class_dict = {} for stmt in class_def.body: if isinstance(stmt, ast.FunctionDef): class_dict[stmt.name] = evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports) elif isinstance(stmt, ast.AnnAssign): if stmt.value: value = evaluate_ast(stmt.value, state, static_tools, custom_tools, authorized_imports) target = stmt.target # Handle target types for annotation if isinstance(target, ast.Name): # Simple variable annotation like "x: int" annotation = evaluate_ast(stmt.annotation, state, static_tools, custom_tools, authorized_imports) class_dict.setdefault("__annotations__", {})[target.id] = annotation # Assign value if provided if stmt.value: class_dict[target.id] = value elif isinstance(target, ast.Attribute): # Attribute annotation like "obj.attr: int" obj = evaluate_ast(target.value, class_dict, static_tools, custom_tools, authorized_imports) # If there's a value assignment, set the attribute if stmt.value: setattr(obj, target.attr, value) elif isinstance(target, ast.Subscript): # Subscript annotation like "dict[key]: int" container = evaluate_ast(target.value, class_dict, static_tools, custom_tools, authorized_imports) index = evaluate_ast(target.slice, state, static_tools, custom_tools, authorized_imports) # If there's a value assignment, set the item if stmt.value: container[index] = value else: raise InterpreterError(f"Unsupported AnnAssign target in class body: {type(target).__name__}") elif isinstance(stmt, ast.Assign): value = evaluate_ast(stmt.value, state, static_tools, custom_tools, authorized_imports) for target in stmt.targets: if isinstance(target, ast.Name): class_dict[target.id] = value elif isinstance(target, ast.Attribute): obj = evaluate_ast(target.value, class_dict, static_tools, custom_tools, authorized_imports) setattr(obj, target.attr, value) elif isinstance(stmt, ast.Pass): pass elif ( isinstance(stmt, ast.Expr) and stmt == class_def.body[0] and isinstance(stmt.value, ast.Constant) and isinstance(stmt.value.value, str) ): # Check if it is a docstring: first statement in class body which is a string literal expression class_dict["__doc__"] = stmt.value.value else: raise InterpreterError(f"Unsupported statement in class body: {stmt.__class__.__name__}") new_class = type(class_name, tuple(bases), class_dict) state[class_name] = new_class return new_class def evaluate_annassign( annassign: ast.AnnAssign, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: # If there's a value to assign, evaluate it if annassign.value: value = evaluate_ast(annassign.value, state, static_tools, custom_tools, authorized_imports) # Set the value for the target set_value(annassign.target, value, state, static_tools, custom_tools, authorized_imports) return value # For declarations without values (x: int), just return None return None def evaluate_augassign( expression: ast.AugAssign, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: def get_current_value(target: ast.AST) -> Any: if isinstance(target, ast.Name): return state.get(target.id, 0) elif isinstance(target, ast.Subscript): obj = evaluate_ast(target.value, state, static_tools, custom_tools, authorized_imports) key = evaluate_ast(target.slice, state, static_tools, custom_tools, authorized_imports) return obj[key] elif isinstance(target, ast.Attribute): obj = evaluate_ast(target.value, state, static_tools, custom_tools, authorized_imports) return getattr(obj, target.attr) elif isinstance(target, ast.Tuple): return tuple(get_current_value(elt) for elt in target.elts) elif isinstance(target, ast.List): return [get_current_value(elt) for elt in target.elts] else: raise InterpreterError("AugAssign not supported for {type(target)} targets.") current_value = get_current_value(expression.target) value_to_add = evaluate_ast(expression.value, state, static_tools, custom_tools, authorized_imports) if isinstance(expression.op, ast.Add): if isinstance(current_value, list): if not isinstance(value_to_add, list): raise InterpreterError(f"Cannot add non-list value {value_to_add} to a list.") current_value += value_to_add else: current_value += value_to_add elif isinstance(expression.op, ast.Sub): current_value -= value_to_add elif isinstance(expression.op, ast.Mult): current_value *= value_to_add elif isinstance(expression.op, ast.Div): current_value /= value_to_add elif isinstance(expression.op, ast.Mod): current_value %= value_to_add elif isinstance(expression.op, ast.Pow): current_value **= value_to_add elif isinstance(expression.op, ast.FloorDiv): current_value //= value_to_add elif isinstance(expression.op, ast.BitAnd): current_value &= value_to_add elif isinstance(expression.op, ast.BitOr): current_value |= value_to_add elif isinstance(expression.op, ast.BitXor): current_value ^= value_to_add elif isinstance(expression.op, ast.LShift): current_value <<= value_to_add elif isinstance(expression.op, ast.RShift): current_value >>= value_to_add else: raise InterpreterError(f"Operation {type(expression.op).__name__} is not supported.") # Update the state: current_value has been updated in-place set_value( expression.target, current_value, state, static_tools, custom_tools, authorized_imports, ) return current_value def evaluate_boolop( node: ast.BoolOp, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: # Determine which value should trigger short-circuit based on operation type: # - 'and' returns the first falsy value encountered (or the last value if all are truthy) # - 'or' returns the first truthy value encountered (or the last value if all are falsy) is_short_circuit_value = (lambda x: not x) if isinstance(node.op, ast.And) else (lambda x: bool(x)) for value in node.values: result = evaluate_ast(value, state, static_tools, custom_tools, authorized_imports) # Short-circuit: return immediately if the condition is met if is_short_circuit_value(result): return result # If no short-circuit occurred, return the last evaluated value return result def evaluate_binop( binop: ast.BinOp, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: # Recursively evaluate the left and right operands left_val = evaluate_ast(binop.left, state, static_tools, custom_tools, authorized_imports) right_val = evaluate_ast(binop.right, state, static_tools, custom_tools, authorized_imports) # Determine the operation based on the type of the operator in the BinOp if isinstance(binop.op, ast.Add): return left_val + right_val elif isinstance(binop.op, ast.Sub): return left_val - right_val elif isinstance(binop.op, ast.Mult): return left_val * right_val elif isinstance(binop.op, ast.Div): return left_val / right_val elif isinstance(binop.op, ast.Mod): return left_val % right_val elif isinstance(binop.op, ast.Pow): return left_val**right_val elif isinstance(binop.op, ast.FloorDiv): return left_val // right_val elif isinstance(binop.op, ast.BitAnd): return left_val & right_val elif isinstance(binop.op, ast.BitOr): return left_val | right_val elif isinstance(binop.op, ast.BitXor): return left_val ^ right_val elif isinstance(binop.op, ast.LShift): return left_val << right_val elif isinstance(binop.op, ast.RShift): return left_val >> right_val else: raise NotImplementedError(f"Binary operation {type(binop.op).__name__} is not implemented.") def evaluate_assign( assign: ast.Assign, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: result = evaluate_ast(assign.value, state, static_tools, custom_tools, authorized_imports) if len(assign.targets) == 1: target = assign.targets[0] set_value(target, result, state, static_tools, custom_tools, authorized_imports) else: expanded_values = [] for tgt in assign.targets: if isinstance(tgt, ast.Starred): expanded_values.extend(result) else: expanded_values.append(result) for tgt, val in zip(assign.targets, expanded_values): set_value(tgt, val, state, static_tools, custom_tools, authorized_imports) return result def set_value( target: ast.AST, value: Any, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> None: if isinstance(target, ast.Name): if target.id in static_tools: raise InterpreterError(f"Cannot assign to name '{target.id}': doing this would erase the existing tool!") state[target.id] = value elif isinstance(target, ast.Tuple): if not isinstance(value, tuple): if hasattr(value, "__iter__") and not isinstance(value, (str, bytes)): value = tuple(value) else: raise InterpreterError("Cannot unpack non-tuple value") if len(target.elts) != len(value): raise InterpreterError("Cannot unpack tuple of wrong size") for i, elem in enumerate(target.elts): set_value(elem, value[i], state, static_tools, custom_tools, authorized_imports) elif isinstance(target, ast.Subscript): obj = evaluate_ast(target.value, state, static_tools, custom_tools, authorized_imports) key = evaluate_ast(target.slice, state, static_tools, custom_tools, authorized_imports) obj[key] = value elif isinstance(target, ast.Attribute): obj = evaluate_ast(target.value, state, static_tools, custom_tools, authorized_imports) setattr(obj, target.attr, value) def evaluate_call( call: ast.Call, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: if not isinstance(call.func, (ast.Call, ast.Lambda, ast.Attribute, ast.Name, ast.Subscript)): raise InterpreterError(f"This is not a correct function: {call.func}).") func, func_name = None, None if isinstance(call.func, ast.Call): func = evaluate_ast(call.func, state, static_tools, custom_tools, authorized_imports) elif isinstance(call.func, ast.Lambda): func = evaluate_ast(call.func, state, static_tools, custom_tools, authorized_imports) elif isinstance(call.func, ast.Attribute): obj = evaluate_ast(call.func.value, state, static_tools, custom_tools, authorized_imports) func_name = call.func.attr if not hasattr(obj, func_name): raise InterpreterError(f"Object {obj} has no attribute {func_name}") func = getattr(obj, func_name) elif isinstance(call.func, ast.Name): func_name = call.func.id if func_name in state: func = state[func_name] elif func_name in static_tools: func = static_tools[func_name] elif func_name in custom_tools: func = custom_tools[func_name] elif func_name in ERRORS: func = ERRORS[func_name] else: raise InterpreterError( f"Forbidden function evaluation: '{call.func.id}' is not among the explicitly allowed tools or defined/imported in the preceding code" ) elif isinstance(call.func, ast.Subscript): func = evaluate_ast(call.func, state, static_tools, custom_tools, authorized_imports) if not callable(func): raise InterpreterError(f"This is not a correct function: {call.func}).") func_name = None args = [] for arg in call.args: if isinstance(arg, ast.Starred): args.extend(evaluate_ast(arg.value, state, static_tools, custom_tools, authorized_imports)) else: args.append(evaluate_ast(arg, state, static_tools, custom_tools, authorized_imports)) kwargs = {} for keyword in call.keywords: if keyword.arg is None: # **kwargs unpacking starred_dict = evaluate_ast(keyword.value, state, static_tools, custom_tools, authorized_imports) if not isinstance(starred_dict, dict): raise InterpreterError(f"Cannot unpack non-dict value in **kwargs: {type(starred_dict).__name__}") kwargs.update(starred_dict) else: # Normal keyword argument kwargs[keyword.arg] = evaluate_ast(keyword.value, state, static_tools, custom_tools, authorized_imports) if func_name == "super": if not args: if "__class__" in state and "self" in state: return super(state["__class__"], state["self"]) else: raise InterpreterError("super() needs at least one argument") cls = args[0] if not isinstance(cls, type): raise InterpreterError("super() argument 1 must be type") if len(args) == 1: return super(cls) elif len(args) == 2: instance = args[1] return super(cls, instance) else: raise InterpreterError("super() takes at most 2 arguments") elif func_name == "print": state["_print_outputs"] += " ".join(map(str, args)) + "\n" return None else: # Assume it's a callable object if (inspect.getmodule(func) == builtins) and inspect.isbuiltin(func) and (func not in static_tools.values()): raise InterpreterError( f"Invoking a builtin function that has not been explicitly added as a tool is not allowed ({func_name})." ) if ( hasattr(func, "__name__") and func.__name__.startswith("__") and func.__name__.endswith("__") and (func.__name__ not in static_tools) and (func.__name__ not in ALLOWED_DUNDER_METHODS) ): raise InterpreterError(f"Forbidden call to dunder function: {func.__name__}") return func(*args, **kwargs) def evaluate_subscript( subscript: ast.Subscript, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: index = evaluate_ast(subscript.slice, state, static_tools, custom_tools, authorized_imports) value = evaluate_ast(subscript.value, state, static_tools, custom_tools, authorized_imports) try: return value[index] except (KeyError, IndexError, TypeError) as e: error_message = f"Could not index {value} with '{index}': {type(e).__name__}: {e}" if isinstance(index, str) and isinstance(value, Mapping): close_matches = difflib.get_close_matches(index, list(value.keys())) if len(close_matches) > 0: error_message += f". Maybe you meant one of these indexes instead: {str(close_matches)}" raise InterpreterError(error_message) from e def evaluate_name( name: ast.Name, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: if name.id in state: return state[name.id] elif name.id in static_tools: return safer_func(static_tools[name.id], static_tools=static_tools, authorized_imports=authorized_imports) elif name.id in custom_tools: return custom_tools[name.id] elif name.id in ERRORS: return ERRORS[name.id] close_matches = difflib.get_close_matches(name.id, list(state.keys())) if len(close_matches) > 0: return state[close_matches[0]] raise InterpreterError(f"The variable `{name.id}` is not defined.") def evaluate_condition( condition: ast.Compare, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> bool | object: result = True left = evaluate_ast(condition.left, state, static_tools, custom_tools, authorized_imports) for i, (op, comparator) in enumerate(zip(condition.ops, condition.comparators)): op = type(op) right = evaluate_ast(comparator, state, static_tools, custom_tools, authorized_imports) if op == ast.Eq: current_result = left == right elif op == ast.NotEq: current_result = left != right elif op == ast.Lt: current_result = left < right elif op == ast.LtE: current_result = left <= right elif op == ast.Gt: current_result = left > right elif op == ast.GtE: current_result = left >= right elif op == ast.Is: current_result = left is right elif op == ast.IsNot: current_result = left is not right elif op == ast.In: current_result = left in right elif op == ast.NotIn: current_result = left not in right else: raise InterpreterError(f"Unsupported comparison operator: {op}") if current_result is False: return False result = current_result if i == 0 else (result and current_result) left = right return result def evaluate_if( if_statement: ast.If, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: result = None test_result = evaluate_ast(if_statement.test, state, static_tools, custom_tools, authorized_imports) if test_result: for line in if_statement.body: line_result = evaluate_ast(line, state, static_tools, custom_tools, authorized_imports) if line_result is not None: result = line_result else: for line in if_statement.orelse: line_result = evaluate_ast(line, state, static_tools, custom_tools, authorized_imports) if line_result is not None: result = line_result return result def evaluate_for( for_loop: ast.For, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Any: result = None iterator = evaluate_ast(for_loop.iter, state, static_tools, custom_tools, authorized_imports) for counter in iterator: set_value( for_loop.target, counter, state, static_tools, custom_tools, authorized_imports, ) for node in for_loop.body: try: line_result = evaluate_ast(node, state, static_tools, custom_tools, authorized_imports) if line_result is not None: result = line_result except BreakException: return result except ContinueException: break return result def evaluate_listcomp( listcomp: ast.ListComp, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> list[Any]: def inner_evaluate(generators: list[ast.comprehension], index: int, current_state: dict[str, Any]) -> list[Any]: if index >= len(generators): return [ evaluate_ast( listcomp.elt, current_state, static_tools, custom_tools, authorized_imports, ) ] generator = generators[index] iter_value = evaluate_ast( generator.iter, current_state, static_tools, custom_tools, authorized_imports, ) result = [] for value in iter_value: new_state = current_state.copy() if isinstance(generator.target, ast.Tuple): for idx, elem in enumerate(generator.target.elts): new_state[elem.id] = value[idx] else: new_state[generator.target.id] = value if all( evaluate_ast(if_clause, new_state, static_tools, custom_tools, authorized_imports) for if_clause in generator.ifs ): result.extend(inner_evaluate(generators, index + 1, new_state)) return result return inner_evaluate(listcomp.generators, 0, state) def evaluate_setcomp( setcomp: ast.SetComp, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> set[Any]: result = set() for gen in setcomp.generators: iter_value = evaluate_ast(gen.iter, state, static_tools, custom_tools, authorized_imports) for value in iter_value: new_state = state.copy() set_value( gen.target, value, new_state, static_tools, custom_tools, authorized_imports, ) if all( evaluate_ast(if_clause, new_state, static_tools, custom_tools, authorized_imports) for if_clause in gen.ifs ): element = evaluate_ast( setcomp.elt, new_state, static_tools, custom_tools, authorized_imports, ) result.add(element) return result def evaluate_try( try_node: ast.Try, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> None: try: for stmt in try_node.body: evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports) except Exception as e: matched = False for handler in try_node.handlers: if handler.type is None or isinstance( e, evaluate_ast(handler.type, state, static_tools, custom_tools, authorized_imports), ): matched = True if handler.name: state[handler.name] = e for stmt in handler.body: evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports) break if not matched: raise e else: if try_node.orelse: for stmt in try_node.orelse: evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports) finally: if try_node.finalbody: for stmt in try_node.finalbody: evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports) def evaluate_raise( raise_node: ast.Raise, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> None: if raise_node.exc is not None: exc = evaluate_ast(raise_node.exc, state, static_tools, custom_tools, authorized_imports) else: exc = None if raise_node.cause is not None: cause = evaluate_ast(raise_node.cause, state, static_tools, custom_tools, authorized_imports) else: cause = None if exc is not None: if cause is not None: raise exc from cause else: raise exc else: raise InterpreterError("Re-raise is not supported without an active exception") def evaluate_assert( assert_node: ast.Assert, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> None: test_result = evaluate_ast(assert_node.test, state, static_tools, custom_tools, authorized_imports) if not test_result: if assert_node.msg: msg = evaluate_ast(assert_node.msg, state, static_tools, custom_tools, authorized_imports) raise AssertionError(msg) else: # Include the failing condition in the assertion message test_code = ast.unparse(assert_node.test) raise AssertionError(f"Assertion failed: {test_code}") def evaluate_with( with_node: ast.With, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> None: contexts = [] for item in with_node.items: context_expr = evaluate_ast(item.context_expr, state, static_tools, custom_tools, authorized_imports) if item.optional_vars: state[item.optional_vars.id] = context_expr.__enter__() contexts.append(state[item.optional_vars.id]) else: context_var = context_expr.__enter__() contexts.append(context_var) try: for stmt in with_node.body: evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports) except Exception as e: for context in reversed(contexts): context.__exit__(type(e), e, e.__traceback__) raise else: for context in reversed(contexts): context.__exit__(None, None, None) def get_safe_module(raw_module, authorized_imports, visited=None): """Creates a safe copy of a module or returns the original if it's a function""" # If it's a function or non-module object, return it directly if not isinstance(raw_module, ModuleType): return raw_module # Handle circular references: Initialize visited set for the first call if visited is None: visited = set() module_id = id(raw_module) if module_id in visited: return raw_module # Return original for circular refs visited.add(module_id) # Create new module for actual modules safe_module = ModuleType(raw_module.__name__) # Copy all attributes by reference, recursively checking modules for attr_name in dir(raw_module): try: attr_value = getattr(raw_module, attr_name) except (ImportError, AttributeError) as e: # lazy / dynamic loading module -> INFO log and skip logger.info( f"Skipping import error while copying {raw_module.__name__}.{attr_name}: {type(e).__name__} - {e}" ) continue # Recursively process nested modules, passing visited set if isinstance(attr_value, ModuleType): attr_value = get_safe_module(attr_value, authorized_imports, visited=visited) setattr(safe_module, attr_name, attr_value) return safe_module def evaluate_import(expression, state, authorized_imports): if isinstance(expression, ast.Import): for alias in expression.names: if check_import_authorized(alias.name, authorized_imports): raw_module = import_module(alias.name) state[alias.asname or alias.name] = get_safe_module(raw_module, authorized_imports) else: raise InterpreterError( f"Import of {alias.name} is not allowed. Authorized imports are: {str(authorized_imports)}" ) return None elif isinstance(expression, ast.ImportFrom): if check_import_authorized(expression.module, authorized_imports): raw_module = __import__(expression.module, fromlist=[alias.name for alias in expression.names]) module = get_safe_module(raw_module, authorized_imports) if expression.names[0].name == "*": # Handle "from module import *" if hasattr(module, "__all__"): # If module has __all__, import only those names for name in module.__all__: state[name] = getattr(module, name) else: # If no __all__, import all public names (those not starting with '_') for name in dir(module): if not name.startswith("_"): state[name] = getattr(module, name) else: # regular from imports for alias in expression.names: if hasattr(module, alias.name): state[alias.asname or alias.name] = getattr(module, alias.name) else: raise InterpreterError(f"Module {expression.module} has no attribute {alias.name}") else: raise InterpreterError( f"Import from {expression.module} is not allowed. Authorized imports are: {str(authorized_imports)}" ) return None def evaluate_dictcomp( dictcomp: ast.DictComp, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> dict[Any, Any]: result = {} for gen in dictcomp.generators: iter_value = evaluate_ast(gen.iter, state, static_tools, custom_tools, authorized_imports) for value in iter_value: new_state = state.copy() set_value( gen.target, value, new_state, static_tools, custom_tools, authorized_imports, ) if all( evaluate_ast(if_clause, new_state, static_tools, custom_tools, authorized_imports) for if_clause in gen.ifs ): key = evaluate_ast( dictcomp.key, new_state, static_tools, custom_tools, authorized_imports, ) val = evaluate_ast( dictcomp.value, new_state, static_tools, custom_tools, authorized_imports, ) result[key] = val return result def evaluate_generatorexp( genexp: ast.GeneratorExp, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> Generator[Any]: def generator(): for gen in genexp.generators: iter_value = evaluate_ast(gen.iter, state, static_tools, custom_tools, authorized_imports) for value in iter_value: new_state = state.copy() set_value( gen.target, value, new_state, static_tools, custom_tools, authorized_imports, ) if all( evaluate_ast(if_clause, new_state, static_tools, custom_tools, authorized_imports) for if_clause in gen.ifs ): yield evaluate_ast( genexp.elt, new_state, static_tools, custom_tools, authorized_imports, ) return generator() def evaluate_delete( delete_node: ast.Delete, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str], ) -> None: """ Evaluate a delete statement (del x, del x[y]). Args: delete_node: The AST Delete node to evaluate state: The current state dictionary static_tools: Dictionary of static tools custom_tools: Dictionary of custom tools authorized_imports: List of authorized imports """ for target in delete_node.targets: if isinstance(target, ast.Name): # Handle simple variable deletion (del x) if target.id in state: del state[target.id] else: raise InterpreterError(f"Cannot delete name '{target.id}': name is not defined") elif isinstance(target, ast.Subscript): # Handle index/key deletion (del x[y]) obj = evaluate_ast(target.value, state, static_tools, custom_tools, authorized_imports) index = evaluate_ast(target.slice, state, static_tools, custom_tools, authorized_imports) try: del obj[index] except (TypeError, KeyError, IndexError) as e: raise InterpreterError(f"Cannot delete index/key: {str(e)}") else: raise InterpreterError(f"Deletion of {type(target).__name__} targets is not supported") @safer_eval def evaluate_ast( expression: ast.AST, state: dict[str, Any], static_tools: dict[str, Callable], custom_tools: dict[str, Callable], authorized_imports: list[str] = BASE_BUILTIN_MODULES, ): """ Evaluate an abstract syntax tree using the content of the variables stored in a state and only evaluating a given set of functions. This function will recurse through the nodes of the tree provided. Args: expression (`ast.AST`): The code to evaluate, as an abstract syntax tree. state (`Dict[str, Any]`): A dictionary mapping variable names to values. The `state` is updated if need be when the evaluation encounters assignments. static_tools (`Dict[str, Callable]`): Functions that may be called during the evaluation. Trying to change one of these static_tools will raise an error. custom_tools (`Dict[str, Callable]`): Functions that may be called during the evaluation. These custom_tools can be overwritten. authorized_imports (`List[str]`): The list of modules that can be imported by the code. By default, only a few safe modules are allowed. If it contains "*", it will authorize any import. Use this at your own risk! """ if state.setdefault("_operations_count", {"counter": 0})["counter"] >= MAX_OPERATIONS: raise InterpreterError( f"Reached the max number of operations of {MAX_OPERATIONS}. Maybe there is an infinite loop somewhere in the code, or you're just asking too many calculations." ) state["_operations_count"]["counter"] += 1 common_params = (state, static_tools, custom_tools, authorized_imports) if isinstance(expression, ast.Assign): # Assignment -> we evaluate the assignment which should update the state # We return the variable assigned as it may be used to determine the final result. return evaluate_assign(expression, *common_params) elif isinstance(expression, ast.AnnAssign): return evaluate_annassign(expression, *common_params) elif isinstance(expression, ast.AugAssign): return evaluate_augassign(expression, *common_params) elif isinstance(expression, ast.Call): # Function call -> we return the value of the function call return evaluate_call(expression, *common_params) elif isinstance(expression, ast.Constant): # Constant -> just return the value return expression.value elif isinstance(expression, ast.Tuple): return tuple((evaluate_ast(elt, *common_params) for elt in expression.elts)) elif isinstance(expression, ast.GeneratorExp): return evaluate_generatorexp(expression, *common_params) elif isinstance(expression, ast.ListComp): return evaluate_listcomp(expression, *common_params) elif isinstance(expression, ast.DictComp): return evaluate_dictcomp(expression, *common_params) elif isinstance(expression, ast.SetComp): return evaluate_setcomp(expression, *common_params) elif isinstance(expression, ast.UnaryOp): return evaluate_unaryop(expression, *common_params) elif isinstance(expression, ast.Starred): return evaluate_ast(expression.value, *common_params) elif isinstance(expression, ast.BoolOp): # Boolean operation -> evaluate the operation return evaluate_boolop(expression, *common_params) elif isinstance(expression, ast.Break): raise BreakException() elif isinstance(expression, ast.Continue): raise ContinueException() elif isinstance(expression, ast.BinOp): # Binary operation -> execute operation return evaluate_binop(expression, *common_params) elif isinstance(expression, ast.Compare): # Comparison -> evaluate the comparison return evaluate_condition(expression, *common_params) elif isinstance(expression, ast.Lambda): return evaluate_lambda(expression, *common_params) elif isinstance(expression, ast.FunctionDef): return evaluate_function_def(expression, *common_params) elif isinstance(expression, ast.Dict): # Dict -> evaluate all keys and values keys = (evaluate_ast(k, *common_params) for k in expression.keys) values = (evaluate_ast(v, *common_params) for v in expression.values) return dict(zip(keys, values)) elif isinstance(expression, ast.Expr): # Expression -> evaluate the content return evaluate_ast(expression.value, *common_params) elif isinstance(expression, ast.For): # For loop -> execute the loop return evaluate_for(expression, *common_params) elif isinstance(expression, ast.FormattedValue): # Formatted value (part of f-string) -> evaluate the content and format it value = evaluate_ast(expression.value, *common_params) # Early return if no format spec if not expression.format_spec: return value # Apply format specification format_spec = evaluate_ast(expression.format_spec, *common_params) return format(value, format_spec) elif isinstance(expression, ast.If): # If -> execute the right branch return evaluate_if(expression, *common_params) elif hasattr(ast, "Index") and isinstance(expression, ast.Index): return evaluate_ast(expression.value, *common_params) elif isinstance(expression, ast.JoinedStr): return "".join([str(evaluate_ast(v, *common_params)) for v in expression.values]) elif isinstance(expression, ast.List): # List -> evaluate all elements return [evaluate_ast(elt, *common_params) for elt in expression.elts] elif isinstance(expression, ast.Name): # Name -> pick up the value in the state return evaluate_name(expression, *common_params) elif isinstance(expression, ast.Subscript): # Subscript -> return the value of the indexing return evaluate_subscript(expression, *common_params) elif isinstance(expression, ast.IfExp): test_val = evaluate_ast(expression.test, *common_params) if test_val: return evaluate_ast(expression.body, *common_params) else: return evaluate_ast(expression.orelse, *common_params) elif isinstance(expression, ast.Attribute): return evaluate_attribute(expression, *common_params) elif isinstance(expression, ast.Slice): return slice( evaluate_ast(expression.lower, *common_params) if expression.lower is not None else None, evaluate_ast(expression.upper, *common_params) if expression.upper is not None else None, evaluate_ast(expression.step, *common_params) if expression.step is not None else None, ) elif isinstance(expression, ast.While): return evaluate_while(expression, *common_params) elif isinstance(expression, (ast.Import, ast.ImportFrom)): return evaluate_import(expression, state, authorized_imports) elif isinstance(expression, ast.ClassDef): return evaluate_class_def(expression, *common_params) elif isinstance(expression, ast.Try): return evaluate_try(expression, *common_params) elif isinstance(expression, ast.Raise): return evaluate_raise(expression, *common_params) elif isinstance(expression, ast.Assert): return evaluate_assert(expression, *common_params) elif isinstance(expression, ast.With): return evaluate_with(expression, *common_params) elif isinstance(expression, ast.Set): return set((evaluate_ast(elt, *common_params) for elt in expression.elts)) elif isinstance(expression, ast.Return): raise ReturnException(evaluate_ast(expression.value, *common_params) if expression.value else None) elif isinstance(expression, ast.Pass): return None elif isinstance(expression, ast.Delete): return evaluate_delete(expression, *common_params) else: # For now we refuse anything else. Let's add things as we need them. raise InterpreterError(f"{expression.__class__.__name__} is not supported.") class FinalAnswerException(Exception): def __init__(self, value): self.value = value def evaluate_python_code( code: str, static_tools: dict[str, Callable] | None = None, custom_tools: dict[str, Callable] | None = None, state: dict[str, Any] | None = None, authorized_imports: list[str] = BASE_BUILTIN_MODULES, max_print_outputs_length: int = DEFAULT_MAX_LEN_OUTPUT, ): """ Evaluate a python expression using the content of the variables stored in a state and only evaluating a given set of functions. This function will recurse through the nodes of the tree provided. Args: code (`str`): The code to evaluate. static_tools (`Dict[str, Callable]`): The functions that may be called during the evaluation. These can also be agents in a multiagent setting. These tools cannot be overwritten in the code: any assignment to their name will raise an error. custom_tools (`Dict[str, Callable]`): The functions that may be called during the evaluation. These tools can be overwritten in the code: any assignment to their name will overwrite them. state (`Dict[str, Any]`): A dictionary mapping variable names to values. The `state` should contain the initial inputs but will be updated by this function to contain all variables as they are evaluated. The print outputs will be stored in the state under the key "_print_outputs". """ try: expression = ast.parse(code) except SyntaxError as e: raise InterpreterError( f"Code parsing failed on line {e.lineno} due to: {type(e).__name__}\n" f"{e.text}" f"{' ' * (e.offset or 0)}^\n" f"Error: {str(e)}" ) if state is None: state = {} static_tools = static_tools.copy() if static_tools is not None else {} custom_tools = custom_tools if custom_tools is not None else {} result = None state["_print_outputs"] = PrintContainer() state["_operations_count"] = {"counter": 0} if "final_answer" in static_tools: previous_final_answer = static_tools["final_answer"] def final_answer(*args, **kwargs): # Allow arbitrary arguments to be passed raise FinalAnswerException(previous_final_answer(*args, **kwargs)) static_tools["final_answer"] = final_answer try: for node in expression.body: result = evaluate_ast(node, state, static_tools, custom_tools, authorized_imports) state["_print_outputs"].value = truncate_content( str(state["_print_outputs"]), max_length=max_print_outputs_length ) is_final_answer = False return result, is_final_answer except FinalAnswerException as e: state["_print_outputs"].value = truncate_content( str(state["_print_outputs"]), max_length=max_print_outputs_length ) is_final_answer = True return e.value, is_final_answer except Exception as e: state["_print_outputs"].value = truncate_content( str(state["_print_outputs"]), max_length=max_print_outputs_length ) raise InterpreterError( f"Code execution failed at line '{ast.get_source_segment(code, node)}' due to: {type(e).__name__}: {e}" ) @dataclass class CodeOutput: output: Any logs: str is_final_answer: bool class PythonExecutor(ABC): @abstractmethod def send_tools(self, tools: dict[str, Tool]) -> None: ... @abstractmethod def send_variables(self, variables: dict[str, Any]) -> None: ... @abstractmethod def __call__(self, code_action: str) -> CodeOutput: ... class LocalPythonExecutor(PythonExecutor): """ Executor of Python code in a local environment. This executor evaluates Python code with restricted access to imports and built-in functions, making it suitable for running untrusted code. It maintains state between executions, allows for custom tools and functions to be made available to the code, and captures print outputs separately from return values. Args: additional_authorized_imports (`list[str]`): Additional authorized imports for the executor. max_print_outputs_length (`int`, defaults to `DEFAULT_MAX_LEN_OUTPUT=50_000`): Maximum length of the print outputs. additional_functions (`dict[str, Callable]`, *optional*): Additional Python functions to be added to the executor. """ def __init__( self, additional_authorized_imports: list[str], max_print_outputs_length: int | None = None, additional_functions: dict[str, Callable] | None = None, ): self.custom_tools = {} self.state = {"__name__": "__main__"} self.max_print_outputs_length = max_print_outputs_length if max_print_outputs_length is None: self.max_print_outputs_length = DEFAULT_MAX_LEN_OUTPUT self.additional_authorized_imports = additional_authorized_imports self.authorized_imports = list(set(BASE_BUILTIN_MODULES) | set(self.additional_authorized_imports)) self._check_authorized_imports_are_installed() self.static_tools = None self.additional_functions = additional_functions or {} def _check_authorized_imports_are_installed(self): """ Check that all authorized imports are installed on the system. Handles wildcard imports ("*") and partial star-pattern imports (e.g., "os.*"). Raises: InterpreterError: If any of the authorized modules are not installed. """ missing_modules = [ base_module for imp in self.authorized_imports if imp != "*" and find_spec(base_module := imp.split(".")[0]) is None ] if missing_modules: raise InterpreterError( f"Non-installed authorized modules: {', '.join(missing_modules)}. " f"Please install these modules or remove them from the authorized imports list." ) def __call__(self, code_action: str) -> CodeOutput: output, is_final_answer = evaluate_python_code( code_action, static_tools=self.static_tools, custom_tools=self.custom_tools, state=self.state, authorized_imports=self.authorized_imports, max_print_outputs_length=self.max_print_outputs_length, ) logs = str(self.state["_print_outputs"]) return CodeOutput(output=output, logs=logs, is_final_answer=is_final_answer) def send_variables(self, variables: dict[str, Any]): self.state.update(variables) def send_tools(self, tools: dict[str, Tool]): # Combine agent tools, base Python tools, and additional Python functions self.static_tools = {**tools, **BASE_PYTHON_TOOLS.copy(), **self.additional_functions} __all__ = ["evaluate_python_code", "LocalPythonExecutor"]
smolagents/src/smolagents/local_python_executor.py/0
{ "file_path": "smolagents/src/smolagents/local_python_executor.py", "repo_id": "smolagents", "token_count": 26909 }
280
import pytest AGENT_DICTS = { "v1.9": { "tools": [], "model": { "class": "InferenceClientModel", "data": { "last_input_token_count": None, "last_output_token_count": None, "model_id": "Qwen/Qwen2.5-Coder-32B-Instruct", "provider": None, }, }, "managed_agents": {}, "prompt_templates": { "system_prompt": "dummy system prompt", "planning": { "initial_facts": "dummy planning initial facts", "initial_plan": "dummy planning initial plan", "update_facts_pre_messages": "dummy planning update facts pre messages", "update_facts_post_messages": "dummy planning update facts post messages", "update_plan_pre_messages": "dummy planning update plan pre messages", "update_plan_post_messages": "dummy planning update plan post messages", }, "managed_agent": { "task": "dummy managed agent task", "report": "dummy managed agent report", }, "final_answer": { "pre_messages": "dummy final answer pre messages", "post_messages": "dummy final answer post messages", }, }, "max_steps": 10, "verbosity_level": 2, "grammar": None, "planning_interval": 2, "name": "test_agent", "description": "dummy description", "requirements": ["smolagents"], "authorized_imports": ["pandas"], }, # Added: executor_type, executor_kwargs, max_print_outputs_length "v1.10": { "tools": [], "model": { "class": "InferenceClientModel", "data": { "last_input_token_count": None, "last_output_token_count": None, "model_id": "Qwen/Qwen2.5-Coder-32B-Instruct", "provider": None, }, }, "managed_agents": {}, "prompt_templates": { "system_prompt": "dummy system prompt", "planning": { "initial_facts": "dummy planning initial facts", "initial_plan": "dummy planning initial plan", "update_facts_pre_messages": "dummy planning update facts pre messages", "update_facts_post_messages": "dummy planning update facts post messages", "update_plan_pre_messages": "dummy planning update plan pre messages", "update_plan_post_messages": "dummy planning update plan post messages", }, "managed_agent": { "task": "dummy managed agent task", "report": "dummy managed agent report", }, "final_answer": { "pre_messages": "dummy final answer pre messages", "post_messages": "dummy final answer post messages", }, }, "max_steps": 10, "verbosity_level": 2, "grammar": None, "planning_interval": 2, "name": "test_agent", "description": "dummy description", "requirements": ["smolagents"], "authorized_imports": ["pandas"], "executor_type": "local", "executor_kwargs": {}, "max_print_outputs_length": None, }, # Removed: grammar, last_input_token_count, last_output_token_count "v1.20": { "tools": [], "model": { "class": "InferenceClientModel", "data": { "model_id": "Qwen/Qwen2.5-Coder-32B-Instruct", "provider": None, }, }, "managed_agents": {}, "prompt_templates": { "system_prompt": "dummy system prompt", "planning": { "initial_facts": "dummy planning initial facts", "initial_plan": "dummy planning initial plan", "update_facts_pre_messages": "dummy planning update facts pre messages", "update_facts_post_messages": "dummy planning update facts post messages", "update_plan_pre_messages": "dummy planning update plan pre messages", "update_plan_post_messages": "dummy planning update plan post messages", }, "managed_agent": { "task": "dummy managed agent task", "report": "dummy managed agent report", }, "final_answer": { "pre_messages": "dummy final answer pre messages", "post_messages": "dummy final answer post messages", }, }, "max_steps": 10, "verbosity_level": 2, "planning_interval": 2, "name": "test_agent", "description": "dummy description", "requirements": ["smolagents"], "authorized_imports": ["pandas"], "executor_type": "local", "executor_kwargs": {}, "max_print_outputs_length": None, }, } @pytest.fixture def get_agent_dict(): def _get_agent_dict(agent_dict_key): return AGENT_DICTS[agent_dict_key] return _get_agent_dict
smolagents/tests/fixtures/agents.py/0
{ "file_path": "smolagents/tests/fixtures/agents.py", "repo_id": "smolagents", "token_count": 2600 }
281
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from smolagents import DuckDuckGoSearchTool from .test_tools import ToolTesterMixin from .utils.markers import require_run_all class TestDuckDuckGoSearchTool(ToolTesterMixin): def setup_method(self): self.tool = DuckDuckGoSearchTool() self.tool.setup() @require_run_all def test_exact_match_arg(self): result = self.tool("Agents") assert isinstance(result, str) @require_run_all def test_agent_type_output(self): super().test_agent_type_output()
smolagents/tests/test_search.py/0
{ "file_path": "smolagents/tests/test_search.py", "repo_id": "smolagents", "token_count": 361 }
282
# Fetch and extract the TGI sources FROM alpine AS tgi RUN mkdir -p /tgi # Fetch the optimum-neuron sources directly to avoid relying on pypi deployments FROM alpine AS optimum-neuron RUN mkdir -p /optimum-neuron ADD https://github.com/huggingface/optimum-neuron/archive/refs/tags/v0.2.2.tar.gz /optimum-neuron/sources.tar.gz RUN tar -C /optimum-neuron -xf /optimum-neuron/sources.tar.gz --strip-components=1 # Build cargo components (adapted from TGI original Dockerfile) # Note: we cannot use the cargo-chef base image as it uses python 3.11 FROM ubuntu:22.04 AS chef RUN apt-get update -y \ && apt-get install -y --no-install-recommends \ curl ca-certificates build-essential \ && rm -rf /var/lib/apt/lists/* \ && apt-get clean RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain 1.85.1 --profile minimal -y ENV PATH="/root/.cargo/bin:${PATH}" RUN cargo install cargo-chef --locked WORKDIR /usr/src FROM chef AS planner COPY backends/neuron/Cargo.toml Cargo.toml COPY Cargo.lock Cargo.lock COPY rust-toolchain.toml rust-toolchain.toml COPY proto proto COPY router router COPY backends backends COPY launcher launcher RUN cargo chef prepare --recipe-path recipe.json FROM chef AS builder RUN apt-get update -y \ && apt-get install -y --no-install-recommends \ unzip python3-dev libssl-dev pkg-config \ && rm -rf /var/lib/apt/lists/* \ && apt-get clean RUN PROTOC_ZIP=protoc-21.12-linux-x86_64.zip && \ curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v21.12/$PROTOC_ZIP && \ unzip -o $PROTOC_ZIP -d /usr/local bin/protoc && \ unzip -o $PROTOC_ZIP -d /usr/local 'include/*' && \ rm -f $PROTOC_ZIP COPY backends/neuron/Cargo.toml Cargo.toml COPY --from=planner /usr/src/recipe.json recipe.json RUN cargo chef cook --release --recipe-path recipe.json COPY Cargo.lock Cargo.lock COPY rust-toolchain.toml rust-toolchain.toml COPY proto proto COPY router router COPY backends backends COPY launcher launcher RUN cargo build --release # Python base image FROM ubuntu:22.04 AS base RUN apt-get update -y \ && apt-get install -y --no-install-recommends \ python3-pip \ python3-setuptools \ python-is-python3 \ && rm -rf /var/lib/apt/lists/* \ && apt-get clean RUN pip3 --no-cache-dir install --upgrade pip # Python server build image FROM base AS pyserver RUN apt-get update -y \ && apt-get install -y --no-install-recommends \ make \ python3-venv \ && rm -rf /var/lib/apt/lists/* \ && apt-get clean RUN install -d /pyserver WORKDIR /pyserver COPY backends/neuron/server server COPY proto proto RUN pip3 install -r server/build-requirements.txt RUN VERBOSE=1 BUILDDIR=/pyserver/build PROTODIR=/pyserver/proto make -C server package # Neuron base image (used for deployment) FROM base AS neuron # Install system prerequisites RUN apt-get update -y \ && apt-get install -y --no-install-recommends \ gnupg2 \ wget \ python3-dev \ libexpat1 \ && rm -rf /var/lib/apt/lists/* \ && apt-get clean RUN echo "deb https://apt.repos.neuron.amazonaws.com jammy main" > /etc/apt/sources.list.d/neuron.list RUN wget -qO - https://apt.repos.neuron.amazonaws.com/GPG-PUB-KEY-AMAZON-AWS-NEURON.PUB | apt-key add - # Install neuronx packages RUN apt-get update -y \ && apt-get install -y --no-install-recommends \ aws-neuronx-dkms=2.20.28.0 \ aws-neuronx-collectives=2.24.59.0-838c7fc8b \ aws-neuronx-runtime-lib=2.24.53.0-f239092cc \ aws-neuronx-tools=2.22.61.0 \ libxml2 \ && rm -rf /var/lib/apt/lists/* \ && apt-get clean ENV PATH="/opt/bin/:/opt/aws/neuron/bin:${PATH}" # Install manually torch CPU version to avoid pulling CUDA RUN pip3 install \ torch==2.5.1 \ torchvision==0.20.1 \ --index-url https://download.pytorch.org/whl/cpu RUN pip3 install \ neuronx-cc==2.17.194.0 \ torch-neuronx==2.5.1.2.6.0 \ neuronx-distributed==0.11.0 \ libneuronxla==2.2.1630.0 \ --extra-index-url=https://pip.repos.neuron.amazonaws.com # Install HuggingFace packages RUN pip3 install \ hf_transfer huggingface_hub # Install optimum-neuron COPY --from=optimum-neuron /optimum-neuron optimum-neuron RUN pip3 install ./optimum-neuron # TGI base env ENV HUGGINGFACE_HUB_CACHE=/tmp \ HF_HUB_ENABLE_HF_TRANSFER=1 \ PORT=80 # Disable color logs as they are not supported by CloudWatch ENV LOGURU_COLORIZE=NO ENV LOG_COLORIZE=0 # Install router COPY --from=builder /usr/src/target/release/text-generation-router-v2 /usr/local/bin/text-generation-router # Install launcher COPY --from=builder /usr/src/target/release/text-generation-launcher /usr/local/bin/text-generation-launcher # Install python server COPY --from=pyserver /pyserver/build/dist dist RUN pip install dist/text_generation_server*.tar.gz # Final image FROM neuron COPY backends/neuron/tgi_entry_point.py /tgi_entry_point.py COPY backends/neuron/tgi-entrypoint.sh /tgi-entrypoint.sh RUN chmod +x /tgi-entrypoint.sh ENTRYPOINT ["/tgi-entrypoint.sh"]
text-generation-inference/Dockerfile.neuron/0
{ "file_path": "text-generation-inference/Dockerfile.neuron", "repo_id": "text-generation-inference", "token_count": 2030 }
283
//! Text Generation gRPC client library pub mod v2; pub mod v3; use async_trait::async_trait; use base64::{engine::general_purpose::STANDARD, Engine}; use thiserror::Error; use tonic::transport; use tonic::Status; pub use v3::{Chunk, Image, Input, InputChunk}; #[async_trait] pub trait Health { /// Check if a generate server is healthy by asking it to allocate a tensor on device async fn device_health(&self) -> Result<()>; /// Check if a generate server is healthy by doing a forward pass. /// EXPENSIVE async fn model_health(&self) -> Result<()>; } #[derive(Debug)] pub struct ShardInfo { pub requires_padding: bool, pub dtype: String, pub device_type: String, pub window_size: Option<u32>, pub speculate: u32, } #[derive(Error, Debug, Clone)] pub enum ClientError { #[error("Could not connect to Text Generation server: {0}")] Connection(String), #[error("Server error: {0}")] Generation(String), #[error("Sharded results are empty")] EmptyResults, } impl From<Status> for ClientError { fn from(err: Status) -> Self { let err = Self::Generation(err.message().to_string()); tracing::error!("{err}"); err } } impl From<transport::Error> for ClientError { fn from(err: transport::Error) -> Self { let err = Self::Connection(err.to_string()); tracing::error!("{err}"); err } } // Small convenience re-wrapping of `Chunk`. impl From<Chunk> for InputChunk { fn from(chunk: Chunk) -> Self { InputChunk { chunk: Some(chunk) } } } /// Convert input chunks to a stringly-typed input for backwards /// compat for backends that haven't implemented chunked inputs. pub trait ChunksToString { /// Convert chunks to string. fn chunks_to_string(&self) -> String; } impl ChunksToString for Vec<InputChunk> { fn chunks_to_string(&self) -> String { let mut output = String::new(); self.iter().for_each(|c| match &c.chunk { Some(Chunk::Text(text)) => output.push_str(text), Some(Chunk::Image(Image { data, mimetype })) => { let encoded = STANDARD.encode(data); output.push_str(&format!("![](data:{};base64,{})", mimetype, encoded)) } // We don't create empty chunks, so this should be unreachable. None => unreachable!("Chunks should never be empty"), }); output } } static WARMUP_IMAGE_BASE64 :&str = "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAABg2lDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV/TSotUROxQxCFDdbKLijjWKhShQqgVWnUwufQLmrQkKS6OgmvBwY/FqoOLs64OroIg+AHi7OCk6CIl/i8ptIjx4Lgf7+497t4BQqvKNDOQADTdMjKppJjLr4rBVwQQwhAERGVm1uckKQ3P8XUPH1/v4jzL+9yfY0AtmAzwicQJVjcs4g3imU2rznmfOMLKskp8Tjxh0AWJH7muuPzGueSwwDMjRjYzTxwhFks9rPQwKxsa8TRxTNV0yhdyLquctzhr1Qbr3JO/MFzQV5a5TnMUKSxiCRJEKGiggiosxGnVSTGRof2kh3/E8UvkUshVASPHAmrQIDt+8D/43a1ZnJp0k8JJoO/Ftj/GgOAu0G7a9vexbbdPAP8zcKV3/bUWMPtJerOrxY6AwW3g4rqrKXvA5Q4QfarLhuxIfppCsQi8n9E35YHhW6B/ze2ts4/TByBLXaVvgINDYLxE2ese7w719vbvmU5/PycecohsjayNAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH6AQIEQMnlTSSjwAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAASSURBVDjLY2AYBaNgFIyCoQsABMQAAeRw1DoAAAAASUVORK5CYII="; pub type Result<T> = std::result::Result<T, ClientError>;
text-generation-inference/backends/client/src/lib.rs/0
{ "file_path": "text-generation-inference/backends/client/src/lib.rs", "repo_id": "text-generation-inference", "token_count": 1545 }
284
# Copyright (C) 2024 Habana Labs, Ltd. an Intel Company. import torch import grpc from google.rpc import status_pb2, code_pb2 from grpc_status import rpc_status from grpc_interceptor.server import AsyncServerInterceptor from loguru import logger from typing import Callable, Any import traceback import os class ExceptionInterceptor(AsyncServerInterceptor): async def intercept( self, method: Callable, request_or_iterator: Any, context: grpc.ServicerContext, method_name: str, ) -> Any: try: response = method(request_or_iterator, context) return await response except Exception as err: trace = " " + traceback.format_exc() if os.environ.get("DUMP_STACK") else "" method_name = method_name.split("/")[-1] logger.exception(f"Method {method_name} encountered an error.") # Runtime Error cannot be recovered from if isinstance(err, RuntimeError): exit(1) if torch.cuda.is_available(): torch.cuda.empty_cache() from .utils.debug import dbg_trace dbg_trace("EXCEPTION", traceback.format_exc()) await context.abort_with_status( rpc_status.to_status( status_pb2.Status(code=code_pb2.INTERNAL, message=str(err) + trace) ) )
text-generation-inference/backends/gaudi/server/text_generation_server/interceptor.py/0
{ "file_path": "text-generation-inference/backends/gaudi/server/text_generation_server/interceptor.py", "repo_id": "text-generation-inference", "token_count": 627 }
285
# ruff: noqa: F821 # the above line disables the `undefined-name` rule for the model type variables import torch import os from loguru import logger from transformers.configuration_utils import PretrainedConfig from huggingface_hub import hf_hub_download, HfApi from typing import Optional from pathlib import Path from typing import List, Dict import enum # Needed to properly setup habana_frameworks from text_generation_server.utils.speculate import get_speculate, set_speculate from text_generation_server.models.model import Model from text_generation_server.models.custom_modeling.flash_phi_moe_modeling import ( PhiMoEConfig, ) from text_generation_server.utils.adapter import ( AdapterParameters, build_layer_weight_lookup, load_and_merge_adapters, AdapterInfo, ) from text_generation_server.adapters.lora import LoraWeights from text_generation_server.utils.log import log_master __all__ = [ "Model", "CausalLM", "Seq2SeqLM", "get_model_with_lora_adapters", ] VLM_BATCH_TYPES = set() FLASH_ATTENTION = True try: from text_generation_server.models.flash_causal_lm import FlashCausalLM from text_generation_server.models.flash_vlm_causal_lm import FlashVlmCausalLM from text_generation_server.models.mllama_causal_lm import FlashMllamaCausalLM from text_generation_server.models.custom_modeling.flash_deepseek_v2_modeling import ( FlashDeepseekV2ForCausalLM, DeepseekV2Config, ) from text_generation_server.models.custom_modeling.flash_deepseek_v3_modeling import ( FlashDeepseekV3ForCausalLM, DeepseekV3Config, ) from text_generation_server.models.custom_modeling.flash_llama_modeling import ( FlashLlamaForCausalLM, ) from text_generation_server.models.custom_modeling.flash_llama4_modeling import ( Llama4ForConditionalGeneration, ) from text_generation_server.models.custom_modeling.flash_cohere_modeling import ( FlashCohereForCausalLM, ) from text_generation_server.models.custom_modeling.flash_gemma_modeling import ( FlashGemmaForCausalLM, ) from text_generation_server.models.custom_modeling.flash_gemma2_modeling import ( FlashGemma2ForCausalLM, ) from text_generation_server.models.custom_modeling.flash_gemma3_modeling import ( Gemma3ForConditionalGeneration, FlashGemma3ForCausalLM, ) from text_generation_server.models.custom_modeling.flash_dbrx_modeling import ( FlashDbrxForCausalLM, DbrxConfig, ) from text_generation_server.models.custom_modeling.flash_rw_modeling import ( RWConfig, FlashRWForCausalLM, ) from text_generation_server.models.custom_modeling.flash_neox_modeling import ( FlashGPTNeoXForCausalLM, ) from text_generation_server.models.custom_modeling.flash_pali_gemma_modeling import ( PaliGemmaForConditionalGeneration, ) from text_generation_server.models.custom_modeling.flash_phi_modeling import ( FlashPhiForCausalLM, ) from text_generation_server.models.mllama_causal_lm import FlashMllamaCausalLMBatch from text_generation_server.models.custom_modeling.flash_mllama import ( FlashMllamaForConditionalGeneration, ) from text_generation_server.models.custom_modeling.flash_llava_next import ( FlashLlavaNextForConditionalGeneration, ) from text_generation_server.models.custom_modeling.flash_santacoder_modeling import ( FlashSantacoderForCausalLM, ) from text_generation_server.models.custom_modeling.flash_starcoder2_modeling import ( FlashStarcoder2ForCausalLM, ) from text_generation_server.models.custom_modeling.flash_qwen2_modeling import ( Qwen2ForCausalLM, ) from text_generation_server.models.custom_modeling.flash_qwen3_modeling import ( Qwen3ForCausalLM, ) from text_generation_server.models.custom_modeling.flash_qwen3_moe_modeling import ( Qwen3MoeForCausalLM, ) from text_generation_server.models.custom_modeling.flash_mistral_modeling import ( FlashMistralForCausalLM, ) from text_generation_server.models.custom_modeling.flash_mixtral_modeling import ( FlashMixtralForCausalLM, ) from text_generation_server.models.custom_modeling.flash_gpt2_modeling import ( FlashGPT2ForCausalLM, ) from text_generation_server.models.custom_modeling.flash_gptj_modeling import ( FlashGPTJForCausalLM, ) from text_generation_server.models.custom_modeling.idefics2 import ( Idefics2ForConditionalGeneration, ) from text_generation_server.models.custom_modeling.idefics3 import ( Idefics3ForConditionalGeneration, ) from text_generation_server.models.custom_modeling.qwen2_vl import ( Qwen2VLForConditionalGeneration, ) from text_generation_server.models.custom_modeling.qwen2_5_vl import ( Qwen2_5VLForConditionalGeneration, Qwen2_5_VLConfig, Qwen2_5_VLProcessor, ) from text_generation_server.layers.attention import SUPPORTS_WINDOWING except ImportError as e: log_master(logger.warning, f"Could not import Flash Attention enabled models: {e}") SUPPORTS_WINDOWING = False FLASH_ATTENTION = False VLM_BATCH_TYPES = set() if FLASH_ATTENTION: __all__.append(FlashCausalLM) from text_generation_server.models.flash_vlm_causal_lm import ( FlashVlmCausalLMBatch, ) VLM_BATCH_TYPES = { FlashVlmCausalLMBatch, FlashMllamaCausalLMBatch, } __all__.append(VLM_BATCH_TYPES) class ModelType(enum.Enum): DEEPSEEK_V2 = { "type": "deepseek_v2", "name": "Deepseek V2", "url": "https://huggingface.co/deepseek-ai/DeepSeek-V2", } DEEPSEEK_V3 = { "type": "deepseek_v3", "name": "Deepseek V3", "url": "https://huggingface.co/deepseek-ai/DeepSeek-V3", } IDEFICS2 = { "type": "idefics2", "name": "Idefics 2", "url": "https://huggingface.co/HuggingFaceM4/idefics2-8b", "multimodal": True, } IDEFICS3 = { "type": "idefics3", "name": "Idefics 3", "url": "https://huggingface.co/HuggingFaceM4/Idefics3-8B-Llama3", "multimodal": True, } LLAVA_NEXT = { "type": "llava_next", "name": "Llava Next (1.6)", "url": "https://huggingface.co/llava-hf/llava-v1.6-vicuna-13b-hf", "multimodal": True, } LLAMA = { "type": "llama", "name": "Llama", "url": "https://huggingface.co/collections/meta-llama/llama-31-669fc079a0c406a149a5738f", } LLAMA4 = { "type": "llama4", "name": "Llama4", "url": "https://huggingface.co/collections/meta-llama/llama-31-669fc079a0c406a149a5738f", } PHI3 = { "type": "phi3", "name": "Phi 3", "url": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct", } GRANITE = { "type": "granite", "name": "Granite", "url": "https://huggingface.co/ibm-granite/granite-3.0-8b-instruct", } GEMMA = { "type": "gemma", "name": "Gemma", "url": "https://huggingface.co/google/gemma-7b", } PALIGEMMA = { "type": "paligemma", "name": "PaliGemma", "url": "https://huggingface.co/google/paligemma-3b-pt-224", } GEMMA2 = { "type": "gemma2", "name": "Gemma2", "url": "https://huggingface.co/collections/google/gemma-2-release-667d6600fd5220e7b967f315", } GEMMA3 = { "type": "gemma3", "name": "Gemma3", "url": "https://huggingface.co/collections/google/gemma-3-release-67c6c6f89c4f76621268bb6d", } GEMMA3_TEXT = { "type": "gemma3_text", "name": "Gemma3 Text", "url": "https://huggingface.co/collections/google/gemma-3-release-67c6c6f89c4f76621268bb6d", } COHERE = { "type": "cohere", "name": "Cohere", "url": "https://huggingface.co/CohereForAI/c4ai-command-r-plus", } DBRX = { "type": "dbrx", "name": "Dbrx", "url": "https://huggingface.co/databricks/dbrx-instruct", } MAMBA = { "type": "mamba", "name": "Mamba", "url": "https://huggingface.co/state-spaces/mamba-2.8b-slimpj", } MISTRAL = { "type": "mistral", "name": "Mistral", "url": "https://huggingface.co/mistralai/Mistral-Nemo-Instruct-2407", } MIXTRAL = { "type": "mixtral", "name": "Mixtral", "url": "https://huggingface.co/mistralai/Mixtral-8x22B-Instruct-v0.1", } GPT_BIGCODE = { "type": "gpt_bigcode", "name": "Gpt Bigcode", "url": "https://huggingface.co/bigcode/gpt_bigcode-santacoder", } PHI = { "type": "phi", "name": "Phi", "url": "https://huggingface.co/microsoft/phi-1_5", } PHI_MOE = { "type": "phimoe", "name": "PhiMoe", "url": "https://huggingface.co/microsoft/Phi-3.5-MoE-instruct", } BAICHUAN = { "type": "baichuan", "name": "Baichuan", "url": "https://huggingface.co/baichuan-inc/Baichuan2-7B-Chat", } FALCON = { "type": "falcon", "name": "Falcon", "url": "https://huggingface.co/tiiuae/falcon-7b-instruct", } STARCODER2 = { "type": "starcoder2", "name": "StarCoder 2", "url": "https://huggingface.co/bigcode/starcoder2-15b-instruct-v0.1", } QWEN2 = { "type": "qwen2", "name": "Qwen 2", "url": "https://huggingface.co/collections/Qwen/qwen2-6659360b33528ced941e557f", } QWEN2_VL = { "type": "qwen2_vl", "name": "Qwen 2 VL", "url": "https://huggingface.co/collections/Qwen/qwen2-vl-66cee7455501d7126940800d", } QWEN2_5_VL = { "type": "qwen2_5_vl", "name": "Qwen 2.5 VL", "url": "https://huggingface.co/collections/Qwen/qwen25-66e81a666513e518adb90d9e", } QWEN3 = { "type": "qwen3", "name": "Qwen 3", "url": "https://huggingface.co/collections/Qwen/qwen3-67dd247413f0e2e4f653967f", } QWEN3_MOE = { "type": "qwen3_moe", "name": "Qwen 3 Moe", "url": "https://huggingface.co/collections/Qwen/qwen3-67dd247413f0e2e4f653967f", } GALACTICA = { "type": "galactica", "name": "Galactica", "url": "https://huggingface.co/facebook/galactica-120b", } SANTACODER = { "type": "santacoder", "name": "SantaCoder", "url": "https://huggingface.co/bigcode/santacoder", } GPT2 = { "type": "gpt2", "name": "Gpt2", "url": "https://huggingface.co/openai-community/gpt2", } GPT_NEOX = { "type": "gpt_neox", "name": "Gpt Neox", "url": "https://huggingface.co/EleutherAI/gpt-neox-20b", } GPTJ = { "type": "gptj", "name": "Gptj", "url": "https://huggingface.co/EleutherAI/gpt-j-6b", } MLLAMA = { "type": "mllama", "name": "Mllama", "url": "https://huggingface.co/meta-llama/Llama-3.2-11B-Vision-Instruct", "multimodal": True, } __GLOBALS = locals() for data in ModelType: __GLOBALS[data.name] = data.value["type"] SDP_ON_BF16 = int(os.environ.get("SDP_ON_BF16", 0)) # Disable gradients torch.set_grad_enabled(False) def get_model( model_id: str, lora_adapter_ids: Optional[List[str]], revision: Optional[str], sharded: bool, quantize: Optional[str], speculate: Optional[int], dtype: Optional[torch.dtype], kv_cache_dtype: Optional[str], trust_remote_code: bool, max_input_tokens: int, ) -> Model: global FLASH_ATTENTION if speculate is not None: set_speculate(speculate) else: set_speculate(0) config_dict, _ = PretrainedConfig.get_config_dict( model_id, revision=revision, trust_remote_code=trust_remote_code ) model_type = config_dict.get("model_type", None) speculator = None if "medusa_num_heads" in config_dict: medusa_model_id = model_id medusa_revision = revision model_id = config_dict["base_model_name_or_path"] revision = "main" speculate_medusa = config_dict["medusa_num_heads"] if speculate is not None: if speculate > speculate_medusa: raise RuntimeError( f"Speculate is set to `{speculate}` but this medusa models only has `{speculate_medusa}` heads, please make them match" ) else: set_speculate(speculate) else: set_speculate(speculate_medusa) config_dict, _ = PretrainedConfig.get_config_dict( model_id, revision=revision, trust_remote_code=trust_remote_code ) # Reload model type from parent. model_type = config_dict.get("model_type", None) is_local = Path(medusa_model_id).exists() if not is_local: medusa_config = hf_hub_download( medusa_model_id, revision=medusa_revision, filename="config.json" ) hf_hub_download( medusa_model_id, revision=medusa_revision, filename="medusa_lm_head.safetensors", ) speculator = { "path": Path(medusa_config).parent, "model_paths": ["medusa_lm_head.safetensors"], } else: speculator = { "path": Path(medusa_model_id), "model_paths": ["medusa_lm_head.safetensors"], } method = "medusa" elif model_type == "mlp_speculator": mlp_model_id = model_id mlp_revision = revision model_id = config_dict["base_model_name_or_path"] revision = "main" speculate_mlp = config_dict["n_predict"] if speculate is not None: if speculate > speculate_mlp: raise RuntimeError( f"Speculate is set to `{speculate}` but this mlp_speculator models only has `{speculate_mlp}` heads, please make them match" ) else: set_speculate(speculate) else: set_speculate(speculate_mlp) config_dict, _ = PretrainedConfig.get_config_dict( model_id, revision=revision, trust_remote_code=trust_remote_code ) # Reload model type from parent. model_type = config_dict.get("model_type", None) is_local = Path(mlp_model_id).exists() extension = ".safetensors" if not is_local: mlp_speculator_config = hf_hub_download( mlp_model_id, revision=mlp_revision, filename="config.json" ) api = HfApi() info = api.model_info(mlp_model_id, revision=mlp_revision) filenames = [ s.rfilename for s in info.siblings if s.rfilename.endswith(extension) and len(s.rfilename.split("/")) == 1 and "arguments" not in s.rfilename and "args" not in s.rfilename and "training" not in s.rfilename ] for filename in filenames: hf_hub_download( mlp_model_id, revision=mlp_revision, filename=filename, ) speculator_dir_path = Path(mlp_speculator_config).parent # if these are downloaded, they get converted to safetensors filenames.extend( [p for p in os.listdir(speculator_dir_path) if p.endswith(extension)] ) speculator = { "path": Path(mlp_speculator_config).parent, "model_paths": filenames, } else: speculator = Path(mlp_model_id) filenames = [p for p in os.listdir(speculator) if p.endswith(extension)] speculator = {"path": speculator, "model_paths": filenames} method = "mlp_speculator" else: method = "n-gram" speculate = get_speculate() if speculate > 0: logger.info(f"Using speculation {method} with {speculate} input ids.") model_type = config_dict["model_type"] if kv_cache_dtype == "fp8_e4m3fn": kv_cache_dtype = torch.float8_e4m3fn elif kv_cache_dtype == "fp8_e5m2": kv_cache_dtype = torch.float8_e5m2 else: kv_cache_dtype = dtype if FLASH_ATTENTION: if model_type == DEEPSEEK_V2: head_size = max( config_dict.get("qk_nope_dim", 128) + config_dict.get("qk_rope_dim", 64), config_dict.get("v_head_dim", 128), ) return FlashCausalLM( model_id=model_id, model_class=FlashDeepseekV2ForCausalLM, revision=revision, quantize=quantize, speculator=speculator, default_dtype=torch.bfloat16, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, config_class=DeepseekV2Config, head_size=head_size, ) elif model_type == DEEPSEEK_V3: head_size = max( config_dict.get("qk_nope_dim", 128) + config_dict.get("qk_rope_dim", 64), config_dict.get("v_head_dim", 128), ) return FlashCausalLM( model_id=model_id, model_class=FlashDeepseekV3ForCausalLM, revision=revision, quantize=quantize, speculator=speculator, default_dtype=torch.bfloat16, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, config_class=DeepseekV3Config, head_size=head_size, ) elif ( model_type == GPT_BIGCODE or model_type == GPT2 and model_id.startswith("bigcode/") ): return FlashCausalLM( model_id=model_id, model_class=FlashSantacoderForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, aliases={"transformer.wte.weight": ["lm_head.weight"]}, num_kv_heads=1, ) elif model_type == GPT2: return FlashCausalLM( model_id=model_id, model_class=FlashGPT2ForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == GPTJ: return FlashCausalLM( model_id=model_id, model_class=FlashGPTJForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == GPT_NEOX: from text_generation_server.models.custom_modeling.flash_neox_modeling import ( GPTNeoXConfig, ) return FlashCausalLM( model_id=model_id, model_class=FlashGPTNeoXForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, config_class=GPTNeoXConfig, ) elif model_type == PHI: return FlashCausalLM( model_id=model_id, model_class=FlashPhiForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == PHI_MOE: return FlashCausalLM( model_id=model_id, model_class=FlashLlamaForCausalLM, config_class=PhiMoEConfig, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == LLAMA or model_type == PHI3 or model_type == GRANITE: return FlashCausalLM( model_id=model_id, model_class=FlashLlamaForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == LLAMA4: print(f"Llama4 model detected: {model_id}") return FlashVlmCausalLM( model_id=model_id, model_class=Llama4ForConditionalGeneration, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, default_dtype=torch.bfloat16, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, support_chunking=False, ) elif model_type == BAICHUAN: return FlashCausalLM( model_id=model_id, model_class=FlashLlamaForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == GEMMA: return FlashCausalLM( model_id=model_id, model_class=FlashGemmaForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, # Works better for these models default_dtype=torch.bfloat16, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == GEMMA2: return FlashCausalLM( model_id=model_id, model_class=FlashGemma2ForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, # Works better for these models default_dtype=torch.bfloat16, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == GEMMA3: return FlashVlmCausalLM( model_id=model_id, model_class=Gemma3ForConditionalGeneration, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, default_dtype=torch.bfloat16, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, support_chunking=False, ) elif model_type == GEMMA3_TEXT: return FlashCausalLM( model_id=model_id, model_class=FlashGemma3ForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, # Works better for these models default_dtype=torch.bfloat16, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == COHERE: return FlashCausalLM( model_id=model_id, model_class=FlashCohereForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == DBRX: return FlashCausalLM( model_id=model_id, model_class=FlashDbrxForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, # Dbrx works better in bfloat16. default_dtype=torch.bfloat16, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, config_class=DbrxConfig, ) elif ( model_type in ["RefinedWeb", "RefinedWebModel", FALCON] and not sharded and not config_dict.get("alibi", False) ): return FlashCausalLM( model_id=model_id, model_class=FlashRWForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, aliases={ "lm_head.weight": ["transformer.word_embeddings.weight"], "transformer.word_embeddings.weight": ["lm_head.weight"], }, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, config_class=RWConfig, ) elif model_type == MISTRAL: return FlashCausalLM( model_id=model_id, model_class=FlashMistralForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == MIXTRAL: return FlashCausalLM( model_id=model_id, model_class=FlashMixtralForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == STARCODER2: return FlashCausalLM( model_id=model_id, model_class=FlashStarcoder2ForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == QWEN2: return FlashCausalLM( model_id=model_id, model_class=Qwen2ForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == QWEN2_VL: return FlashVlmCausalLM( model_id=model_id, model_class=Qwen2VLForConditionalGeneration, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, default_dtype=torch.bfloat16, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, # TODO: Fix bug in rust image_text_replacement implementation support_chunking=False, ) elif model_type == QWEN2_5_VL: return FlashVlmCausalLM( model_id=model_id, model_class=Qwen2_5VLForConditionalGeneration, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, default_dtype=torch.bfloat16, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, config_class=Qwen2_5_VLConfig, processor_class=Qwen2_5_VLProcessor, # TODO: Fix bug in rust image_text_replacement implementation support_chunking=False, ) elif model_type == QWEN3: return FlashCausalLM( model_id=model_id, model_class=Qwen3ForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == QWEN3_MOE: return FlashCausalLM( model_id=model_id, model_class=Qwen3MoeForCausalLM, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == MLLAMA: return FlashMllamaCausalLM( model_id=model_id, model_class=FlashMllamaForConditionalGeneration, batch_class=FlashMllamaCausalLMBatch, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, default_dtype=torch.bfloat16, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, support_chunking=False, ) elif model_type == IDEFICS2: return FlashVlmCausalLM( model_id=model_id, model_class=Idefics2ForConditionalGeneration, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, # XXX: Extremely important to cap resolution in order to limit # VRAM usage. processor_kwargs={"size": {"longest_edge": 448, "shortest_edge": 378}}, ) elif model_type == IDEFICS3: return FlashVlmCausalLM( model_id=model_id, model_class=Idefics3ForConditionalGeneration, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, default_dtype=torch.bfloat16, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, # XXX: Extremely important to cap resolution in order to limit # VRAM usage. processor_kwargs={"size": {"longest_edge": 1456}}, ) elif model_type == PALIGEMMA: return FlashVlmCausalLM( model_id=model_id, model_class=PaliGemmaForConditionalGeneration, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, # Works better for these models default_dtype=torch.bfloat16, trust_remote_code=trust_remote_code, lora_adapter_ids=lora_adapter_ids, ) elif model_type == LLAVA_NEXT: return FlashVlmCausalLM( model_class=FlashLlavaNextForConditionalGeneration, model_id=model_id, revision=revision, quantize=quantize, speculator=speculator, dtype=dtype, kv_cache_dtype=kv_cache_dtype, trust_remote_code=trust_remote_code, ) raise ValueError(f"Unsupported model type {model_type}") # get_model_with_lora_adapters wraps the internal get_model function and adds support for loading adapters # this provides a post model loading hook to load adapters into the model after the model has been loaded def get_model_with_lora_adapters( model_id: str, lora_adapters: Optional[List[AdapterInfo]], revision: Optional[str], sharded: bool, quantize: Optional[str], speculate: Optional[int], dtype: Optional[torch.dtype], kv_cache_dtype: Optional[str], trust_remote_code: bool, max_input_tokens: int, adapter_to_index: Dict[str, int], ): lora_adapter_ids = [adapter.id for adapter in lora_adapters] model = get_model( model_id, lora_adapter_ids, revision, sharded, quantize, speculate, dtype, kv_cache_dtype, trust_remote_code, max_input_tokens, ) if len(lora_adapters) > 0: target_to_layer = build_layer_weight_lookup(model.model) for index, adapter in enumerate(lora_adapters): # The AdapterParameters object allows for merging multiple adapters into a single adapter. # At the moment, we only support loading a single adapter into the model, but we keep the # AdapterParameters object for easier extension in the future. adapter_parameters = AdapterParameters( adapter_info=[adapter], # when merging multiple adapters we can weight them differently # if this is not set, all adapters will be weighted equally # see: text_generation_server.utils.merges.strategies for impl weights=None, merge_strategy=0, density=1.0, majority_sign_method=0, ) adapter_index = index + 1 adapter_to_index[adapter.id] = adapter_index logger.info( f"Loading adapter weights into model: {','.join([adapter.id for adapter in adapter_parameters.adapter_info])}" ) weight_names = tuple([v[0] for v in target_to_layer.values()]) ( module_map, adapter_config, adapter_weight_names, adapter_tokenizer, ) = load_and_merge_adapters( model.model_id, adapter_parameters, adapter_index, weight_names, False, ) unused_weight_names = adapter_weight_names.copy() adapter_layers = [ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", "qkv_proj", ] for layer_name in adapter_layers: nlayers = ( 1 if layer_name == "lm_head" else len(model.model.model.layers) ) adapter_weights = LoraWeights.prepare_weights( config=adapter_config, module_map=module_map, layer_type=layer_name, unused_weight_names=unused_weight_names, nlayers=nlayers, dtype=model.dtype, world_size=model.world_size, process_group=model.process_group, target_to_layer=target_to_layer, ) if adapter_weights is None: continue model.layer_to_adapter_weights[layer_name].add_adapter( adapter_index, adapter_weights ) if len(unused_weight_names) > 0: logger.warning( f"{','.join([a.id for a in lora_adapters])} unused adapter weights: {unused_weight_names}" ) if adapter_tokenizer is not None: model.tokenizers.add_tokenizer(adapter_index, adapter_tokenizer) model.loaded_adapters.add(adapter_index) return model
text-generation-inference/backends/gaudi/server/text_generation_server/models/__init__.py/0
{ "file_path": "text-generation-inference/backends/gaudi/server/text_generation_server/models/__init__.py", "repo_id": "text-generation-inference", "token_count": 20885 }
286
# coding=utf-8 # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch import torch.distributed from torch import nn from transformers.activations import ACT2FN from transformers.configuration_utils import PretrainedConfig from typing import Optional, List, Tuple from text_generation_server.layers.attention.kv_cache import get_kv_scales from text_generation_server.layers.attention import ( paged_attention, attention, set_block_mapping, Seqlen, HPUPagedAttentionMetadata, ) from text_generation_server.layers import ( TensorParallelRowLinear, TensorParallelColumnLinear, TensorParallelEmbedding, SpeculativeHead, TensorParallelMultiAdapterLinear, TensorParallelAdapterRowLinear, ) from text_generation_server.layers.rotary import PositionRotaryEmbedding from text_generation_server.layers.layernorm import ( FastRMSNorm, ) import habana_frameworks.torch as htorch class MistralConfig(PretrainedConfig): model_type = "mistral" def __init__( self, vocab_size=32000, hidden_size=4096, intermediate_size=14336, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=8, hidden_act="silu", max_position_embeddings=4096 * 32, initializer_range=0.02, rms_norm_eps=1e-6, use_cache=True, pad_token_id=None, bos_token_id=1, eos_token_id=2, pretraining_tp=1, tie_word_embeddings=False, rope_theta=10000.0, sliding_window=None, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.sliding_window = sliding_window # for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.pretraining_tp = pretraining_tp self.use_cache = use_cache self.rope_theta = rope_theta super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, ) class MistralAttention(torch.nn.Module): def __init__(self, prefix: str, config, weights, layer_id, rotary_emb): super().__init__() self.max_past = ( config.sliding_window if config.sliding_window is not None else -1 ) self.num_heads = config.num_attention_heads self.hidden_size = config.hidden_size if getattr(config, "head_dim", None) is not None: self.head_size = config.head_dim else: self.head_size = self.hidden_size // self.num_heads self.rotary_emb = rotary_emb self.softmax_scale = self.head_size**-0.5 if self.num_heads % weights.process_group.size() != 0: raise ValueError( f"`num_heads` must be divisible by `num_shards` (got `num_heads`: {self.num_heads} " f"and `num_shards`: {weights.process_group.size()}" ) self.num_heads = self.num_heads // weights.process_group.size() self.num_key_value_heads = ( config.num_key_value_heads // weights.process_group.size() ) query_key_value = TensorParallelColumnLinear.load_multi( config, prefixes=[f"{prefix}.q_proj", f"{prefix}.k_proj", f"{prefix}.v_proj"], dim=0, weights=weights, bias=False, ) self.query_key_value = TensorParallelMultiAdapterLinear.load( query_key_value, layer_id, ["q_proj", "k_proj", "v_proj"], sizes=[ self.head_size * config.num_attention_heads, self.head_size * config.num_key_value_heads, self.head_size * config.num_key_value_heads, ], process_group=weights.process_group, ) self.kv_scales = get_kv_scales(weights, f"{prefix}") o_proj = TensorParallelRowLinear.load( config, prefix=f"{prefix}.o_proj", weights=weights, bias=False, ) self.o_proj = TensorParallelAdapterRowLinear.load( o_proj, layer_id, "o_proj", process_group=weights.process_group, ) self.num_groups = self.num_heads // self.num_key_value_heads self.kv_head_mapping = torch.arange( 0, self.num_key_value_heads, dtype=torch.int32, device=weights.device ).repeat_interleave(self.num_groups) def forward( self, hidden_states, cos, sin, cu_seqlen_prefill, kv_cache, slots, seqlen, adapter_data, hpu_attention_meta, ): qkv = self.query_key_value(hidden_states, adapter_data) query, kv = qkv.split( [ self.head_size * self.num_heads, 2 * self.head_size * self.num_key_value_heads, ], dim=1, ) query = query.view(-1, self.num_heads, self.head_size) kv = kv.view(-1, 2, self.num_key_value_heads, self.head_size) self.rotary_emb(query, torch.select(kv, dim=1, index=0), cos, sin) kv_cache.store( key=kv[:, 0], value=kv[:, 1], slots=slots, kv_scales=self.kv_scales, ) # Prefill if cu_seqlen_prefill is not None: # sdpa attn_output = attention( query=query, key=kv[:, 0], value=kv[:, 1], kv_cache=kv_cache, kv_scales=self.kv_scales, seqlen=seqlen, softmax_scale=self.softmax_scale, window_size_left=self.max_past, ) # Decode else: attn_output = paged_attention( query, kv_cache, self.kv_head_mapping, self.softmax_scale, seqlen, kv_scales=self.kv_scales, hpu_attention_meta=hpu_attention_meta, window_size_left=self.max_past, ) return self.o_proj( attn_output.view(-1, self.num_heads * self.head_size), adapter_data ) class MistralMLP(nn.Module): def __init__(self, prefix: str, config, weights, layer_id): super().__init__() self.hidden_act = config.hidden_act self.act = ( ACT2FN[self.hidden_act] if "gelu" not in self.hidden_act else lambda x: torch.nn.functional.gelu( x, approximate=( "tanh" if self.hidden_act in ["gelu_fast", "gelu_pytorch_tanh"] else "none" ), ) ) # Fuse gate and up proj gate_up_proj = TensorParallelColumnLinear.load_multi( config, prefixes=[f"{prefix}.gate_proj", f"{prefix}.up_proj"], weights=weights, dim=0, bias=False, ) self.gate_up_proj = TensorParallelMultiAdapterLinear.load( gate_up_proj, layer_id, ["gate_proj", "up_proj"], sizes=[ config.intermediate_size, config.intermediate_size, ], process_group=weights.process_group, ) down_proj = TensorParallelRowLinear.load( config, prefix=f"{prefix}.down_proj", weights=weights, bias=False, ) self.down_proj = TensorParallelAdapterRowLinear.load( down_proj, layer_id, "down_proj", process_group=weights.process_group, ) self.intermediate_size = ( config.intermediate_size // weights.process_group.size() ) # TODO: This is a hotfix to be removed & properly refactored. self.quantize = config.quantize def forward(self, hidden_states, adapter_data): gate_up_states = self.gate_up_proj(hidden_states, adapter_data) gate_up_states = gate_up_states.view(-1, 2, self.intermediate_size) return self.down_proj( self.act(gate_up_states[:, 0]) * gate_up_states[:, 1], adapter_data ) class MistralLayer(nn.Module): def __init__(self, prefix: str, config, weights, layer_id, rotary_emb): super().__init__() self.self_attn = MistralAttention( prefix=f"{prefix}.self_attn", config=config, weights=weights, layer_id=layer_id, rotary_emb=rotary_emb, ) self.mlp = MistralMLP( prefix=f"{prefix}.mlp", config=config, weights=weights, layer_id=layer_id ) self.input_layernorm = FastRMSNorm.load( prefix=f"{prefix}.input_layernorm", weights=weights, eps=config.rms_norm_eps ) self.post_attention_layernorm = FastRMSNorm.load( prefix=f"{prefix}.post_attention_layernorm", weights=weights, eps=config.rms_norm_eps, ) def forward( self, hidden_states, residual, cos, sin, cu_seqlen_prefill, kv_cache, slots, seqlen, adapter_data, hpu_attention_meta, ): normed_hidden_states, res = self.input_layernorm(hidden_states, residual) # Self Attention attn_output = self.self_attn( normed_hidden_states, cos, sin, cu_seqlen_prefill, kv_cache, slots, seqlen, adapter_data, hpu_attention_meta, ) # faster post attention rms norm normed_attn_res_output, attn_res = self.post_attention_layernorm( attn_output, res ) mlp_output = self.mlp(normed_attn_res_output, adapter_data) return mlp_output, attn_res class MistralModel(torch.nn.Module): def __init__(self, prefix: str, config, weights): super().__init__() process_group = weights.process_group self.tp_rank = process_group.rank() self.tp_world_size = process_group.size() if getattr(config, "head_dim", None) is not None: head_dim = config.head_dim else: head_dim = config.hidden_size // config.num_attention_heads rotary_emb = PositionRotaryEmbedding.static( config=config, dim=head_dim, base=config.rope_theta, device=weights.device, ) self.layers = nn.ModuleList( [ MistralLayer( prefix=f"{prefix}.layers.{layer_id}", config=config, weights=weights, layer_id=layer_id, rotary_emb=rotary_emb, ) for layer_id in range(config.num_hidden_layers) ] ) self.norm = FastRMSNorm.load( prefix=f"{prefix}.norm", weights=weights, eps=config.rms_norm_eps ) self.gradient_checkpointing = False self.head_size = self.layers[0].self_attn.head_size self.num_heads = self.layers[0].self_attn.num_heads self.num_key_value_heads = self.layers[0].self_attn.num_key_value_heads def forward( self, inputs_embeds: torch.Tensor, position_ids: torch.Tensor, cu_seqlen_prefill: Optional[torch.Tensor], kv_cache: List[Tuple[torch.Tensor, torch.Tensor]], slots: torch.Tensor, seqlen: Seqlen, hpu_attention_meta: Optional[HPUPagedAttentionMetadata], adapter_data: Optional[torch.Tensor] = None, ): if hpu_attention_meta is not None: hpu_attention_meta = set_block_mapping( hpu_attention_meta, inputs_embeds.shape[0] ) hidden_states = inputs_embeds # Get rotary cos and sin for this forward # Avoid to index in each layer cos, sin = self.layers[0].self_attn.rotary_emb.get_cos_sin(position_ids) residual = None lazy_mode = htorch.utils.internal.is_lazy() if lazy_mode: htorch.core.mark_step() for i, layer in enumerate(self.layers): hidden_states, residual = layer( hidden_states, residual, cos, sin, cu_seqlen_prefill, kv_cache[i], slots, seqlen, adapter_data, hpu_attention_meta, ) if lazy_mode: htorch.core.mark_step() hidden_states, _ = self.norm(hidden_states, residual) return hidden_states class FlashMistralForCausalLM(torch.nn.Module): def __init__(self, prefix: str, config, weights, name=None): if name is None: name = "model" super().__init__() self.embed_tokens = TensorParallelEmbedding( prefix=( f"{name}.embed_tokens" if not prefix else f"{prefix}.{name}.embed_tokens" ), weights=weights, ) self.model = MistralModel( prefix=name if not prefix else f"{prefix}.{name}", config=config, weights=weights, ) self.lm_head = SpeculativeHead.load( config, # TODO dirty hack for idefics2. prefix=( "lm_head" if not prefix or name != "model" else f"{prefix}.lm_head" ), weights=weights, ) self.max_past = config.sliding_window self.max_past_tensor = ( torch.tensor(config.sliding_window, device=weights.device) if self.max_past is not None else None ) def forward( self, input_ids: torch.Tensor, position_ids: torch.Tensor, cu_seqlen_prefill: Optional[torch.Tensor], kv_cache: List[Tuple[torch.Tensor, torch.Tensor]], slots: torch.Tensor, seqlen: Seqlen, hpu_attention_meta: Optional[HPUPagedAttentionMetadata], lm_head_indices: Optional[torch.Tensor] = None, adapter_data: Optional[torch.Tensor] = None, ) -> torch.Tensor: inputs_embeds = self.embed_tokens(input_ids) hidden_states = self.model( inputs_embeds, position_ids, cu_seqlen_prefill, kv_cache, slots, seqlen, hpu_attention_meta, adapter_data, ) if lm_head_indices is not None: hidden_states = hidden_states[lm_head_indices] logits = self.lm_head(hidden_states) return logits
text-generation-inference/backends/gaudi/server/text_generation_server/models/custom_modeling/flash_mistral_modeling.py/0
{ "file_path": "text-generation-inference/backends/gaudi/server/text_generation_server/models/custom_modeling/flash_mistral_modeling.py", "repo_id": "text-generation-inference", "token_count": 8324 }
287
# coding=utf-8 # Copyright 2025 the HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PyTorch Qwen2.5 VL model.""" from typing import Optional, Tuple, List import torch import torch.utils.checkpoint from torch import nn from habana_frameworks.torch.hpex.kernels import FusedSDPA from vllm_hpu_extension.utils import ModuleFusedSDPA import numpy as np from transformers.activations import ACT2FN from transformers.configuration_utils import PretrainedConfig import torch.nn.functional as F from text_generation_server.layers.layernorm import FastRMSNorm from text_generation_server.layers import ( TensorParallelColumnLinear, TensorParallelRowLinear, TensorParallelEmbedding, SpeculativeHead, ) from text_generation_server.layers.attention import ( Seqlen, HPUPagedAttentionMetadata, ) from text_generation_server.models.custom_modeling.flash_qwen2_modeling import ( Qwen2Model, ) from habana_frameworks.torch.hpex.kernels import ( RotaryPosEmbeddingMode, apply_rotary_pos_emb, ) import habana_frameworks.torch as htorch # Copied from: https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen2_5_vl/processing_qwen2_5_vl.py from typing import Union from transformers.feature_extraction_utils import BatchFeature from transformers.image_utils import ImageInput from transformers.video_utils import VideoInput from transformers.processing_utils import ( ProcessingKwargs, ProcessorMixin, Unpack, VideosKwargs, ) from transformers.tokenization_utils_base import PreTokenizedInput, TextInput class Qwen2_5_VLVideosProcessorKwargs(VideosKwargs, total=False): fps: Union[List[float], float] class Qwen2_5_VLProcessorKwargs(ProcessingKwargs, total=False): videos_kwargs: Qwen2_5_VLVideosProcessorKwargs _defaults = { "text_kwargs": { "padding": False, }, "videos_kwargs": {"fps": 2.0}, } class Qwen2_5_VLProcessor(ProcessorMixin): r""" Constructs a Qwen2.5-VL processor which wraps a Qwen2.5-VL image processor and a Qwen2 tokenizer into a single processor. [`Qwen2_5_VLProcessor`] offers all the functionalities of [`Qwen2VLImageProcessor`] and [`Qwen2TokenizerFast`]. See the [`~Qwen2_5_VLProcessor.__call__`] and [`~Qwen2_5_VLProcessor.decode`] for more information. Args: image_processor ([`Qwen2VLImageProcessor`], *optional*): The image processor is a required input. tokenizer ([`Qwen2TokenizerFast`], *optional*): The tokenizer is a required input. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages in a chat into a tokenizable string. """ attributes = ["image_processor", "tokenizer"] valid_kwargs = ["chat_template"] image_processor_class = "AutoImageProcessor" tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast") def __init__( self, image_processor=None, tokenizer=None, chat_template=None, **kwargs ): self.image_token = ( "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token ) self.video_token = ( "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token ) super().__init__(image_processor, tokenizer, chat_template=chat_template) def __call__( self, images: ImageInput = None, text: Union[ TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput] ] = None, videos: VideoInput = None, **kwargs: Unpack[Qwen2_5_VLProcessorKwargs], ) -> BatchFeature: """ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to Qwen2VLImageProcessor's [`~Qwen2VLImageProcessor.__call__`] if `vision_infos` is not `None`. Args: images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`): The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. Both channels-first and channels-last formats are supported. text (`str`, `List[str]`, `List[List[str]]`): The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`): The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are: - `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. - `'jax'`: Return JAX `jnp.ndarray` objects. Returns: [`BatchFeature`]: A [`BatchFeature`] with the following fields: - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not `None`). - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`. - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`. - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`. - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`. - **second_per_grid_ts** -- List of video seconds per time grid. Returned when `videos` is not `None`. """ output_kwargs = self._merge_kwargs( Qwen2_5_VLProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs, ) if images is not None: image_inputs = self.image_processor( images=images, videos=None, **output_kwargs["images_kwargs"] ) image_grid_thw = image_inputs["image_grid_thw"] else: image_inputs = {} image_grid_thw = None if videos is not None: videos_inputs = self.image_processor( images=None, videos=videos, **output_kwargs["images_kwargs"] ) video_grid_thw = videos_inputs["video_grid_thw"] fps = output_kwargs["videos_kwargs"].pop("fps", 2.0) if isinstance(fps, (int, float)): second_per_grid_ts = [ self.image_processor.temporal_patch_size / fps ] * len(video_grid_thw) elif hasattr(fps, "__len__") and len(fps) == len(video_grid_thw): second_per_grid_ts = [ self.image_processor.temporal_patch_size / tmp for tmp in fps ] else: raise ValueError( f"The length of fps ({len(fps) if hasattr(fps, '__len__') else fps}) must be equal to the length of video_grid_thw ({len(video_grid_thw)}) or fps should be a single number." ) videos_inputs.update({"second_per_grid_ts": second_per_grid_ts}) else: videos_inputs = {} video_grid_thw = None if not isinstance(text, list): text = [text] if image_grid_thw is not None: merge_length = self.image_processor.merge_size**2 index = 0 for i in range(len(text)): while self.image_token in text[i]: text[i] = text[i].replace( self.image_token, "<|placeholder|>" * (image_grid_thw[index].prod() // merge_length), 1, ) index += 1 text[i] = text[i].replace("<|placeholder|>", self.image_token) if video_grid_thw is not None: merge_length = self.image_processor.merge_size**2 index = 0 for i in range(len(text)): while self.video_token in text[i]: text[i] = text[i].replace( self.video_token, "<|placeholder|>" * (video_grid_thw[index].prod() // merge_length), 1, ) index += 1 text[i] = text[i].replace("<|placeholder|>", self.video_token) text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"]) return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}) def batch_decode(self, *args, **kwargs): """ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.batch_decode(*args, **kwargs) def decode(self, *args, **kwargs): """ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.decode(*args, **kwargs) def post_process_image_text_to_text(self, generated_outputs): """ Post-process the output of the model to decode the text. Args: generated_outputs (`torch.Tensor` or `np.ndarray`): The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)` or `(sequence_length,)`. Returns: `List[str]`: The decoded text. """ return self.tokenizer.batch_decode( generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, ) @property def model_input_names(self): tokenizer_input_names = self.tokenizer.model_input_names image_processor_input_names = self.image_processor.model_input_names names_from_processor = list( dict.fromkeys(tokenizer_input_names + image_processor_input_names) ) return names_from_processor + ["second_per_grid_ts"] # Copied from: https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py class Qwen2_5_VLVisionConfig(PretrainedConfig): model_type = "qwen2_5_vl" base_config_key = "vision_config" def __init__( self, depth=32, hidden_size=3584, hidden_act="silu", intermediate_size=3420, num_heads=16, in_channels=3, patch_size=14, spatial_merge_size=2, spatial_patch_size=14, temporal_patch_size=2, tokens_per_second=4, window_size=112, out_hidden_size=3584, fullatt_block_indexes=[7, 15, 23, 31], **kwargs, ): super().__init__(**kwargs) self.depth = depth self.hidden_size = hidden_size self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.num_heads = num_heads self.in_channels = in_channels self.patch_size = patch_size self.spatial_patch_size = spatial_patch_size self.spatial_merge_size = spatial_merge_size self.temporal_patch_size = temporal_patch_size self.tokens_per_second = tokens_per_second self.window_size = window_size self.fullatt_block_indexes = fullatt_block_indexes self.out_hidden_size = out_hidden_size class Qwen2_5_VLConfig(PretrainedConfig): def __init__( self, vocab_size=152064, hidden_size=8192, intermediate_size=29568, num_hidden_layers=80, num_attention_heads=64, num_key_value_heads=8, hidden_act="silu", max_position_embeddings=32768, initializer_range=0.02, rms_norm_eps=1e-05, use_cache=True, tie_word_embeddings=False, rope_theta=1000000.0, use_sliding_window=False, sliding_window=4096, max_window_layers=80, attention_dropout=0.0, vision_config=None, rope_scaling=None, **kwargs, ): if vision_config is not None: self.vision_config = Qwen2_5_VLVisionConfig(**vision_config) self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.use_sliding_window = use_sliding_window self.sliding_window = sliding_window self.max_window_layers = max_window_layers # for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.attention_dropout = attention_dropout self.rope_scaling = rope_scaling # Validate the correctness of rotary position embeddings parameters # BC: if there is a 'type' field, move it to 'rope_type'. # and change type from 'mrope' to 'default' because `mrope` does defeault RoPE calculations # one can set it to "linear"/"dynamic" etc. to have scaled RoPE # TODO: @raushan update config in the hub if self.rope_scaling is not None and "type" in self.rope_scaling: if self.rope_scaling["type"] == "mrope": self.rope_scaling["type"] = "default" self.rope_scaling["rope_type"] = self.rope_scaling["type"] super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs) class Qwen2_5VLAttention(nn.Module): def __init__(self, *, prefix, config, weights): super().__init__() self.embed_dim = config.hidden_size // weights.process_group.size() self.head_dim = config.hidden_size // config.num_heads self.num_heads = config.num_heads // weights.process_group.size() self.qkv = TensorParallelColumnLinear.load_qkv( config, prefix=f"{prefix}.qkv", weights=weights, bias=False, num_heads=self.num_heads, num_key_value_heads=self.num_heads, ) self.qkv.linear.bias = weights.get_sharded(f"{prefix}.qkv.bias", dim=0) self.proj = TensorParallelRowLinear.load( config, prefix=f"{prefix}.proj", weights=weights, bias=True, ) self.softmax_scale = 1.0 / np.sqrt(self.embed_dim // self.num_heads) def forward( self, hidden_state: torch.Tensor, cu_seqlens: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, max_seqlen: int, ) -> torch.Tensor: # apply the qkv linear layer to the hidden state qkv = self.qkv(hidden_state) query, key, value = qkv.split( [self.embed_dim, self.embed_dim, self.embed_dim], dim=1 ) # reshape the query, key, and value tensors _shape = ( hidden_state.shape[0], self.num_heads, self.embed_dim // self.num_heads, ) query = query.view(*_shape) key = key.view(*_shape) value = value.view(*_shape) # apply rotary positional embeddings rope_mode = RotaryPosEmbeddingMode.BLOCKWISE rotary_dim = cos.shape[-1] query_rot = query[..., :rotary_dim] query_pass = query[..., rotary_dim:] query_rot = apply_rotary_pos_emb(query_rot, cos, sin, None, 0, rope_mode) query.copy_(torch.cat((query_rot, query_pass), dim=-1).reshape(query.shape)) key_rot = key[..., :rotary_dim] key_pass = key[..., rotary_dim:] key_rot = apply_rotary_pos_emb(key_rot, cos, sin, None, 0, rope_mode) key.copy_(torch.cat((key_rot, key_pass), dim=-1).reshape(key.shape)) # execute sdpa causal = False query = query.transpose(0, 1) key = key.transpose(0, 1) value = value.transpose(0, 1) fsdpa_op = ModuleFusedSDPA(FusedSDPA) attention_mask = torch.zeros( [1, max_seqlen, max_seqlen], device=query.device, dtype=torch.bool ) for i in range(1, len(cu_seqlens)): attention_mask[ :, cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i] ] = True attn_output = fsdpa_op( query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=causal, scale=None, softmax_mode="None", recompute_mode=None, valid_sequence_lengths=None, ) attn_output = attn_output.transpose(0, 1) # reshape output to original dimensions attn_output = attn_output.reshape(hidden_state.shape[0], -1) attn_output = self.proj(attn_output) return attn_output class Qwen2_5VLVisionMLP(nn.Module): def __init__(self, *, prefix, config, weights): super().__init__() self.activation_fn = ACT2FN[config.hidden_act] self.intermediate_size = ( config.intermediate_size // weights.process_group.size() ) self.up = TensorParallelColumnLinear.load( prefix=f"{prefix}.up_proj", weights=weights, config=config, bias=True ) self.gate = TensorParallelColumnLinear.load( prefix=f"{prefix}.gate_proj", weights=weights, config=config, bias=True ) self.down = TensorParallelRowLinear.load( prefix=f"{prefix}.down_proj", weights=weights, config=config, bias=True ) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: gate_states = self.gate(hidden_states) up_states = self.up(hidden_states) activated_states = self.activation_fn(gate_states) * up_states down_states = self.down(activated_states) return down_states class Qwen2_5VLVisionBlock(nn.Module): def __init__(self, prefix, config, weights): super().__init__() self.attn = Qwen2_5VLAttention( prefix=f"{prefix}.attn", config=config, weights=weights, ) self.norm1 = FastRMSNorm.load( prefix=f"{prefix}.norm1", weights=weights, eps=1e-6, ) self.norm2 = FastRMSNorm.load( prefix=f"{prefix}.norm2", weights=weights, eps=1e-6, ) self.mlp = Qwen2_5VLVisionMLP( prefix=f"{prefix}.mlp", config=config, weights=weights, ) def forward(self, hidden_states, cu_seqlens, cos, sin, max_seqlen) -> torch.Tensor: norm1_out, _ = self.norm1(hidden_states) attn_out = self.attn(norm1_out, cu_seqlens, cos, sin, max_seqlen) hidden_states = hidden_states + attn_out norm2_out, _ = self.norm2(hidden_states) mlp_out = self.mlp(norm2_out) hidden_states = hidden_states + mlp_out return hidden_states class Qwen2_5VLPatchMerger(nn.Module): def __init__(self, *, prefix, config, weights): super().__init__() self.hidden_size = config.hidden_size * (config.spatial_merge_size**2) self.patch_merger_ln_q = FastRMSNorm.load( prefix=f"{prefix}.ln_q", weights=weights, eps=1e-6, ) self.fc1 = TensorParallelColumnLinear.load( prefix=f"{prefix}.mlp.0", weights=weights, config=config, bias=True ) self.fc2 = TensorParallelRowLinear.load( prefix=f"{prefix}.mlp.2", weights=weights, config=config, bias=True ) def forward(self, hidden_states) -> torch.Tensor: hidden_states, _ = self.patch_merger_ln_q(hidden_states) hidden_states = hidden_states.view(-1, self.hidden_size) hidden_states = self.fc1(hidden_states) hidden_states = F.gelu(hidden_states) hidden_states = self.fc2(hidden_states) return hidden_states class Qwen2_5VisionModel(nn.Module): def __init__(self, *, prefix, config, weights): super().__init__() self.spatial_merge_size = config.spatial_merge_size kernel_size = [config.temporal_patch_size, config.patch_size, config.patch_size] self.patch_embedding = nn.Conv3d( in_channels=config.in_channels, out_channels=config.hidden_size, kernel_size=kernel_size, stride=kernel_size, bias=False, ) self.patch_embedding.weight = nn.Parameter( weights.get_tensor(f"{prefix}.patch_embed.proj.weight"), requires_grad=False ) head_dim = config.hidden_size // config.num_heads theta = 10000.0 dim = head_dim // 2 inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) self.blocks = nn.ModuleList( [ Qwen2_5VLVisionBlock( prefix=f"{prefix}.blocks.{i}", config=config, weights=weights, ) for i in range(config.depth) ] ) self.merger = Qwen2_5VLPatchMerger( prefix=f"{prefix}.merger", config=config, weights=weights, ) self.temporal_patch_size = config.temporal_patch_size self.spatial_patch_size = config.spatial_patch_size self.in_channels = config.in_channels self.embed_dim = config.hidden_size self.window_size = config.window_size self.patch_size = config.patch_size self.spatial_merge_unit = config.spatial_merge_size * config.spatial_merge_size self.fullatt_block_indexes = config.fullatt_block_indexes def apply_class_embedding(self, hidden_state: torch.Tensor) -> torch.Tensor: batch_size, _, hidden_size = hidden_state.shape class_embedding = self.class_embedding.expand(batch_size, 1, hidden_size) hidden_state = torch.cat([class_embedding, hidden_state], dim=1) return hidden_state def get_window_index(self, grid_thw): window_index: list = [] cu_window_seqlens: list = [0] window_index_id = 0 vit_merger_window_size = ( self.window_size // self.spatial_merge_size // self.patch_size ) for grid_t, grid_h, grid_w in grid_thw: llm_grid_h, llm_grid_w = ( grid_h // self.spatial_merge_size, grid_w // self.spatial_merge_size, ) index = torch.arange(grid_t * llm_grid_h * llm_grid_w).reshape( grid_t, llm_grid_h, llm_grid_w ) pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size index_padded = F.pad(index, (0, pad_w, 0, pad_h), "constant", -100) index_padded = index_padded.reshape( grid_t, num_windows_h, vit_merger_window_size, num_windows_w, vit_merger_window_size, ) index_padded = index_padded.permute(0, 1, 3, 2, 4).reshape( grid_t, num_windows_h * num_windows_w, vit_merger_window_size, vit_merger_window_size, ) seqlens = (index_padded != -100).sum([2, 3]).reshape(-1) index_padded = index_padded.reshape(-1) index_new = index_padded[index_padded != -100] window_index.append(index_new + window_index_id) cu_seqlens_tmp = ( seqlens.cumsum(0) * self.spatial_merge_unit + cu_window_seqlens[-1] ) cu_window_seqlens.extend(cu_seqlens_tmp.tolist()) window_index_id += (grid_t * llm_grid_h * llm_grid_w).item() window_index = torch.cat(window_index, dim=0) return window_index, cu_window_seqlens def forward( self, pixel_values: torch.Tensor, grid_thw: Optional[torch.LongTensor] = None, ) -> torch.Tensor: # reshape the input tensor for processing shape = ( -1, self.in_channels, self.temporal_patch_size, self.spatial_patch_size, self.spatial_patch_size, ) pixel_values = pixel_values.view(shape).to(self.patch_embedding.weight.dtype) hidden_states = self.patch_embedding(pixel_values).view(-1, self.embed_dim) # TODO: revisit to see if we can avoid some of these reshapes # find the position ids for the input tensor based on the grid_thw pos_ids = [] for t, h, w in grid_thw: hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w) hpos_ids = hpos_ids.reshape( h // self.spatial_merge_size, self.spatial_merge_size, w // self.spatial_merge_size, self.spatial_merge_size, ) hpos_ids = hpos_ids.permute(0, 2, 1, 3) hpos_ids = hpos_ids.flatten() wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1) wpos_ids = wpos_ids.reshape( h // self.spatial_merge_size, self.spatial_merge_size, w // self.spatial_merge_size, self.spatial_merge_size, ) wpos_ids = wpos_ids.permute(0, 2, 1, 3) wpos_ids = wpos_ids.flatten() pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1)) pos_ids = torch.cat(pos_ids, dim=0) max_grid_size = grid_thw[:, 1:].max() # apply the positional embeddings to the position ids seq = torch.arange( max_grid_size, device=self.inv_freq.device, dtype=self.inv_freq.dtype ) rotary_pos_emb_full = torch.outer(seq, self.inv_freq) rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1) window_index, cu_window_seqlens = self.get_window_index(grid_thw) seq_len = hidden_states.shape[0] patch_shape = (seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) og_shape = (seq_len, -1) hidden_states = hidden_states.view(patch_shape)[window_index, :, :].view( og_shape ) rotary_pos_emb = rotary_pos_emb.view(patch_shape)[window_index, :, :].view( og_shape ) rotary_pos_emb = rotary_pos_emb.to(device=hidden_states.device) cos = rotary_pos_emb.cos() sin = rotary_pos_emb.sin() cos = torch.cat((cos, cos), dim=-1).unsqueeze(1) sin = torch.cat((sin, sin), dim=-1).unsqueeze(1) cu_window_seqlens = torch.tensor( cu_window_seqlens, device="cpu", dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32, ) cu_window_seqlens = torch.unique_consecutive(cu_window_seqlens).to( hidden_states.device ) # create a cu_seqlens tensor to be used in the attention mask cu_seqlens = torch.repeat_interleave( grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0] ).cumsum(dim=0, dtype=torch.int32) cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0) max_seqlen = torch.max(cu_seqlens[1:] - cu_seqlens[:-1]) # iterately apply the blocks to the hidden states lazy_mode = htorch.utils.internal.is_lazy() if lazy_mode: htorch.core.mark_step() for layer_num, block in enumerate(self.blocks): # NOTE: qwen2_5_vl.py has a concept of full attention blocks # that are applied at specific layers. if layer_num in self.fullatt_block_indexes: cu_seqlens_now = cu_seqlens else: cu_seqlens_now = cu_window_seqlens hidden_states = block(hidden_states, cu_seqlens_now, cos, sin, max_seqlen) if lazy_mode: htorch.core.mark_step() # apply the final patch merger to the hidden states hidden_states = self.merger(hidden_states) reverse_indices = torch.argsort(window_index) hidden_states = hidden_states[reverse_indices, :] return hidden_states class Qwen2_5VLForConditionalGeneration(nn.Module): def __init__(self, prefix, config, weights): super().__init__() self.config = config config.vision_config.quantize = None config.vision_config.speculator = config.speculator # set rope_scaling.type == "mrope" since AutoConfig.from_pretrained incorrectly # returns rope_scaling.type == "default" for Qwen2_5-VL model at the moment if ( hasattr(config, "rope_scaling") and config.rope_scaling is not None and config.rope_scaling.get("type", None) == "default" ): config.rope_scaling.update({"rope_type": "mrope"}) self.hidden_size = config.hidden_size self.vision_start_token_id = config.vision_start_token_id self.vision_end_token_id = config.vision_end_token_id self.image_token_id = config.image_token_id self.video_token_id = config.video_token_id self.spatial_merge_size = config.vision_config.spatial_merge_size self.embed_tokens = TensorParallelEmbedding( prefix="model.embed_tokens", weights=weights ) self.visual = Qwen2_5VisionModel( prefix="visual", config=config.vision_config, weights=weights ) self.text_model = Qwen2Model(prefix=None, config=config, weights=weights) if config.tie_word_embeddings: suffix = "model.embed_tokens" else: suffix = "lm_head" self.lm_head = SpeculativeHead.load( config, prefix=suffix if not prefix else f"{prefix}.{suffix}", weights=weights, ) self.device = weights.device # based on https://github.com/huggingface/transformers/blob/e284c7e954abe12c34b50461c17f8115a0afe115/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py#L1391 # modified to first find segments then initialize position ids for each segment # Steps: # locate all vision and text segments # calculate `vision_segment_lengths` for each vision segment to be use as offset # calculate `text_segment_lengths` for each text segment to be used as offset # create position ids for each vision segment based on the image grid # create position ids for each text segment # combine all the position ids # the final segment is the difference between the last vision segment and the end of the input # combine all the position ids and reshape to (3, input_ids_len) then swap dimensions to (input_ids_len, 3) def get_position_ids( self, input_ids: torch.Tensor, image_grid_thw: Optional[torch.Tensor] = None, ) -> torch.Tensor: if image_grid_thw is None: return ( torch.arange(input_ids.shape[0], device=input_ids.device) .unsqueeze(1) .repeat(1, 3) ) spatial_merge_size = self.spatial_merge_size vision_start_token_id = self.vision_start_token_id vision_end_token_id = self.vision_end_token_id device = input_ids.device dtype = input_ids.dtype input_ids_len = input_ids.shape[0] vision_starts = torch.where(input_ids == vision_start_token_id)[0] vision_ends = torch.where(input_ids == vision_end_token_id)[0] vision_segments = torch.stack((vision_starts, vision_ends), dim=1) prev_vision_end = torch.cat( [torch.zeros(1, device=vision_ends.device, dtype=dtype), vision_ends[:-1]] ) text_lengths_between_vision = vision_segments[:, 0] - prev_vision_end + 1 vision_widths_max = torch.cat( [ torch.zeros(1, device=image_grid_thw.device, dtype=dtype), image_grid_thw[:-1, 2] // spatial_merge_size, ] ) vision_segment_lengths = vision_widths_max + text_lengths_between_vision vision_segment_lengths = vision_segment_lengths.cumsum(dim=0) text_segment_lengths = vision_segment_lengths - text_lengths_between_vision # create position ids for each vision segment based on the image grid llm_pos_ids_list = [] for i, _ in enumerate(vision_segments): t, h, w = ( image_grid_thw[i][0], image_grid_thw[i][1] // spatial_merge_size, image_grid_thw[i][2] // spatial_merge_size, ) t_indices = torch.arange(t, device=device).repeat_interleave(h * w) h_indices = torch.arange(h, device=device).repeat_interleave(w).repeat(t) w_indices = torch.arange(w, device=device).repeat(t * h) image_position_ids = torch.stack([t_indices, h_indices, w_indices], dim=0) # offset by the position of the last vision segment im = image_position_ids + vision_segment_lengths[i] llm_pos_ids_list.append(im) # create position ids for each text segment text_ranges = [ torch.arange(seq_len, device=device).view(1, -1).expand(3, -1) + text_segment_lengths[i] for i, seq_len in enumerate(text_lengths_between_vision) ] full_llm_pos_ids_list = [ item for sublist in zip(text_ranges, llm_pos_ids_list) for item in sublist ] max_s = full_llm_pos_ids_list[-1].max() + 1 final_text_len = input_ids_len - vision_ends[-1] if final_text_len > 0: m = torch.arange(final_text_len, device=device).view(1, -1).expand(3, -1) full_llm_pos_ids_list.append(m + max_s) position_ids = ( torch.cat(full_llm_pos_ids_list, dim=1).reshape(3, -1).transpose(0, 1) ) return position_ids def get_vision_embeds( self, pixel_values: torch.FloatTensor, pixel_attention_mask: Optional[torch.FloatTensor] = None, image_sizes: Optional[torch.Tensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, ): image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw).squeeze(0) return image_embeds def get_inputs_embeds( self, input_ids: torch.Tensor, vision_embeds: torch.Tensor = None, ): inputs_embeds = self.embed_tokens(input_ids) # apply the visual model to the pixel values if they are provided if vision_embeds is not None: mask = torch.where(input_ids == self.image_token_id) inputs_embeds[mask] = vision_embeds return inputs_embeds def forward( self, inputs_embeds: torch.Tensor, position_ids: torch.Tensor, cu_seqlen_prefill: Optional[torch.Tensor], kv_cache: List[Tuple[torch.Tensor, torch.Tensor]], slots: torch.Tensor, seqlen: Seqlen, hpu_attention_meta: Optional[HPUPagedAttentionMetadata], lm_head_indices: Optional[torch.Tensor], attention_mask: Optional[torch.BoolTensor] = None, adapter_data: Optional[torch.Tensor] = None, image_indices=None, ): hidden_states = self.text_model( inputs_embeds=inputs_embeds, position_ids=position_ids, cu_seqlen_prefill=cu_seqlen_prefill, kv_cache=kv_cache, slots=slots, seqlen=seqlen, hpu_attention_meta=hpu_attention_meta, ) if lm_head_indices is not None: hidden_states = hidden_states[lm_head_indices] logits, speculative_logits = self.lm_head(hidden_states) return logits, speculative_logits
text-generation-inference/backends/gaudi/server/text_generation_server/models/custom_modeling/qwen2_5_vl.py/0
{ "file_path": "text-generation-inference/backends/gaudi/server/text_generation_server/models/custom_modeling/qwen2_5_vl.py", "repo_id": "text-generation-inference", "token_count": 18100 }
288
from typing import Iterable from loguru import logger from text_generation_server.pb import generate_pb2 def concat_text_chunks(chunks: Iterable[generate_pb2.InputChunk]) -> str: """ Concatenate text in text chunks. Non-text chunks are dropped. """ text = None for chunk in chunks: chunk_type = chunk.WhichOneof("chunk") if chunk_type == "text": if text is None: text = chunk.text else: raise NotImplementedError("Request contained more than one text chunk") else: # We cannot reject this, e.g. warmup sends an image chunk. logger.debug(f"Encountered non-text chunk type {chunk_type}") if text is None: raise NotImplementedError("Request without a text chunk") return text
text-generation-inference/backends/gaudi/server/text_generation_server/utils/chunks.py/0
{ "file_path": "text-generation-inference/backends/gaudi/server/text_generation_server/utils/chunks.py", "repo_id": "text-generation-inference", "token_count": 332 }
289
SPECULATE = None def get_speculate() -> int: global SPECULATE return SPECULATE def set_speculate(speculate: int): global SPECULATE SPECULATE = speculate
text-generation-inference/backends/gaudi/server/text_generation_server/utils/speculate.py/0
{ "file_path": "text-generation-inference/backends/gaudi/server/text_generation_server/utils/speculate.py", "repo_id": "text-generation-inference", "token_count": 66 }
290
[workspace] members = [ "backends/v2", "backends/grpc-metadata", "launcher", "router" ] default-members = [ "backends/v2", "backends/grpc-metadata", "launcher", "router" ] resolver = "2" [workspace.package] version = "3.0.0" edition = "2021" authors = ["Olivier Dehaene"] homepage = "https://github.com/huggingface/text-generation-inference" [workspace.dependencies] base64 = "0.22.0" tokenizers = { version = "0.20.0", features = ["http"] } hf-hub = { version = "0.4.2", features = ["tokio"] } metrics = { version = "0.23.0" } metrics-exporter-prometheus = { version = "0.15.1", features = [] } minijinja = { version = "2.2.0", features = ["json"] } minijinja-contrib = { version = "2.0.2", features = ["pycompat"] } pyo3 = { version = "0.22.2", features = ["auto-initialize"] } [profile.release] incremental = true [profile.release-binary] inherits = "release" debug = 1 incremental = true panic = "abort" [profile.release-opt] inherits = "release" debug = 0 incremental = false lto = "fat" opt-level = 3 codegen-units = 1
text-generation-inference/backends/neuron/Cargo.toml/0
{ "file_path": "text-generation-inference/backends/neuron/Cargo.toml", "repo_id": "text-generation-inference", "token_count": 416 }
291
[pytest] asyncio_mode = auto
text-generation-inference/backends/neuron/tests/pytest.ini/0
{ "file_path": "text-generation-inference/backends/neuron/tests/pytest.ini", "repo_id": "text-generation-inference", "token_count": 13 }
292
fetchcontent_declare( json # DOWNLOAD_EXTRACT_TIMESTAMP URL https://github.com/nlohmann/json/archive/refs/tags/v3.11.3.tar.gz ) fetchcontent_makeavailable(json)
text-generation-inference/backends/trtllm/cmake/json.cmake/0
{ "file_path": "text-generation-inference/backends/trtllm/cmake/json.cmake", "repo_id": "text-generation-inference", "token_count": 87 }
293
// // Created by mfuntowicz on 11/16/24. // #include <catch2/catch_all.hpp> #include "../csrc/hardware.hpp" using namespace huggingface::tgi::hardware::cuda; TEST_CASE("is_at_least_<arch>") { const static auto VOLTA_CAPABILITIES = compute_capabilities_t(7, 0); REQUIRE(VOLTA_CAPABILITIES.is_at_least_volta()); REQUIRE_FALSE(VOLTA_CAPABILITIES.is_at_least_turing()); REQUIRE_FALSE(VOLTA_CAPABILITIES.is_at_least_ampere()); REQUIRE_FALSE(VOLTA_CAPABILITIES.is_at_least_ada_lovelace()); REQUIRE_FALSE(VOLTA_CAPABILITIES.is_at_least_hopper()); const static auto TURING_CAPABILITIES = compute_capabilities_t(7, 5); REQUIRE(TURING_CAPABILITIES.is_at_least_volta()); REQUIRE(TURING_CAPABILITIES.is_at_least_turing()); REQUIRE_FALSE(TURING_CAPABILITIES.is_at_least_ampere()); REQUIRE_FALSE(TURING_CAPABILITIES.is_at_least_ada_lovelace()); REQUIRE_FALSE(TURING_CAPABILITIES.is_at_least_hopper()); const static auto AMPERE_CAPABILITIES = compute_capabilities_t(8, 0); REQUIRE(AMPERE_CAPABILITIES.is_at_least_volta()); REQUIRE(AMPERE_CAPABILITIES.is_at_least_turing()); REQUIRE(AMPERE_CAPABILITIES.is_at_least_ampere()); REQUIRE_FALSE(AMPERE_CAPABILITIES.is_at_least_ada_lovelace()); REQUIRE_FALSE(AMPERE_CAPABILITIES.is_at_least_hopper()); const static auto ADA_LOVELACE_CAPABILITIES = compute_capabilities_t(8, 9); REQUIRE(ADA_LOVELACE_CAPABILITIES.is_at_least_volta()); REQUIRE(ADA_LOVELACE_CAPABILITIES.is_at_least_turing()); REQUIRE(ADA_LOVELACE_CAPABILITIES.is_at_least_ampere()); REQUIRE(ADA_LOVELACE_CAPABILITIES.is_at_least_ada_lovelace()); REQUIRE_FALSE(ADA_LOVELACE_CAPABILITIES.is_at_least_hopper()); const static auto HOPPER_CAPABILITIES = compute_capabilities_t(9, 0); REQUIRE(HOPPER_CAPABILITIES.is_at_least_volta()); REQUIRE(HOPPER_CAPABILITIES.is_at_least_turing()); REQUIRE(HOPPER_CAPABILITIES.is_at_least_ampere()); REQUIRE(HOPPER_CAPABILITIES.is_at_least_ada_lovelace()); REQUIRE(HOPPER_CAPABILITIES.is_at_least_hopper()); } TEST_CASE("is_at_least") { const static auto VOLTA_CAPABILITIES = compute_capabilities_t(7, 0); REQUIRE(VOLTA_CAPABILITIES.is_at_least(VOLTA)); REQUIRE_FALSE(VOLTA_CAPABILITIES.is_at_least(TURING)); REQUIRE_FALSE(VOLTA_CAPABILITIES.is_at_least(AMPERE)); REQUIRE_FALSE(VOLTA_CAPABILITIES.is_at_least(ADA_LOVELACE)); REQUIRE_FALSE(VOLTA_CAPABILITIES.is_at_least(HOPPER)); const static auto TURING_CAPABILITIES = compute_capabilities_t(7, 5); REQUIRE(TURING_CAPABILITIES.is_at_least(VOLTA)); REQUIRE(TURING_CAPABILITIES.is_at_least(TURING)); REQUIRE_FALSE(TURING_CAPABILITIES.is_at_least(AMPERE)); REQUIRE_FALSE(TURING_CAPABILITIES.is_at_least(ADA_LOVELACE)); REQUIRE_FALSE(TURING_CAPABILITIES.is_at_least(HOPPER)); const static auto AMPERE_CAPABILITIES = compute_capabilities_t(8, 0); REQUIRE(AMPERE_CAPABILITIES.is_at_least(VOLTA)); REQUIRE(AMPERE_CAPABILITIES.is_at_least(TURING)); REQUIRE(AMPERE_CAPABILITIES.is_at_least(AMPERE)); REQUIRE_FALSE(AMPERE_CAPABILITIES.is_at_least(ADA_LOVELACE)); REQUIRE_FALSE(AMPERE_CAPABILITIES.is_at_least(HOPPER)); const static auto ADA_LOVELACE_CAPABILITIES = compute_capabilities_t(8, 9); REQUIRE(ADA_LOVELACE_CAPABILITIES.is_at_least(VOLTA)); REQUIRE(ADA_LOVELACE_CAPABILITIES.is_at_least(TURING)); REQUIRE(ADA_LOVELACE_CAPABILITIES.is_at_least(AMPERE)); REQUIRE(ADA_LOVELACE_CAPABILITIES.is_at_least(ADA_LOVELACE)); REQUIRE_FALSE(ADA_LOVELACE_CAPABILITIES.is_at_least(HOPPER)); const static auto HOPPER_CAPABILITIES = compute_capabilities_t (9, 0); REQUIRE(HOPPER_CAPABILITIES.is_at_least(VOLTA)); REQUIRE(HOPPER_CAPABILITIES.is_at_least(TURING)); REQUIRE(HOPPER_CAPABILITIES.is_at_least(AMPERE)); REQUIRE(HOPPER_CAPABILITIES.is_at_least(ADA_LOVELACE)); REQUIRE(HOPPER_CAPABILITIES.is_at_least(HOPPER)); }
text-generation-inference/backends/trtllm/tests/test_hardware.cpp/0
{ "file_path": "text-generation-inference/backends/trtllm/tests/test_hardware.cpp", "repo_id": "text-generation-inference", "token_count": 1738 }
294
//! Text Generation gRPC client library use async_trait::async_trait; use thiserror::Error; use tonic::transport; use tonic::Status; #[allow(clippy::derive_partial_eq_without_eq)] mod pb; mod grpc_client; mod sharded_client; pub use grpc_client::Client; pub use pb::generate::v3::{ input_chunk::Chunk, Batch, CachedBatch, FinishReason, GeneratedText, Generation, GrammarType, HealthResponse, Image, InfoResponse, Input, InputChunk, NextTokenChooserParameters, Request, StoppingCriteriaParameters, }; pub use sharded_client::ShardedClient; #[async_trait] pub trait Health { /// Check if a generate server is healthy by asking it to allocate a tensor on device async fn device_health(&self) -> Result<()>; /// Check if a generate server is healthy by doing a forward pass. /// EXPENSIVE async fn model_health(&self) -> Result<()>; } #[derive(Error, Debug, Clone)] pub enum ClientError { #[error("Could not connect to Text Generation server: {0}")] Connection(String), #[error("Server error: {0}")] Generation(String), #[error("Sharded results are empty")] EmptyResults, } impl From<Status> for ClientError { fn from(err: Status) -> Self { let err = Self::Generation(err.message().to_string()); tracing::error!("{err}"); err } } impl From<transport::Error> for ClientError { fn from(err: transport::Error) -> Self { let err = Self::Connection(err.to_string()); tracing::error!("{err}"); err } } // Small convenience re-wrapping of `Chunk`. impl From<Chunk> for InputChunk { fn from(chunk: Chunk) -> Self { InputChunk { chunk: Some(chunk) } } } static WARMUP_IMAGE_BASE64 :&str = "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAABg2lDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV/TSotUROxQxCFDdbKLijjWKhShQqgVWnUwufQLmrQkKS6OgmvBwY/FqoOLs64OroIg+AHi7OCk6CIl/i8ptIjx4Lgf7+497t4BQqvKNDOQADTdMjKppJjLr4rBVwQQwhAERGVm1uckKQ3P8XUPH1/v4jzL+9yfY0AtmAzwicQJVjcs4g3imU2rznmfOMLKskp8Tjxh0AWJH7muuPzGueSwwDMjRjYzTxwhFks9rPQwKxsa8TRxTNV0yhdyLquctzhr1Qbr3JO/MFzQV5a5TnMUKSxiCRJEKGiggiosxGnVSTGRof2kh3/E8UvkUshVASPHAmrQIDt+8D/43a1ZnJp0k8JJoO/Ftj/GgOAu0G7a9vexbbdPAP8zcKV3/bUWMPtJerOrxY6AwW3g4rqrKXvA5Q4QfarLhuxIfppCsQi8n9E35YHhW6B/ze2ts4/TByBLXaVvgINDYLxE2ese7w719vbvmU5/PycecohsjayNAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH6AQIEQMnlTSSjwAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAASSURBVDjLY2AYBaNgFIyCoQsABMQAAeRw1DoAAAAASUVORK5CYII="; pub type Result<T> = std::result::Result<T, ClientError>;
text-generation-inference/backends/v3/src/client/mod.rs/0
{ "file_path": "text-generation-inference/backends/v3/src/client/mod.rs", "repo_id": "text-generation-inference", "token_count": 1210 }
295
unit-tests: python -m pytest --cov=text_generation tests install: pip install pip --upgrade pip install -e .
text-generation-inference/clients/python/Makefile/0
{ "file_path": "text-generation-inference/clients/python/Makefile", "repo_id": "text-generation-inference", "token_count": 41 }
296
<html> <head> <!-- Load the latest Swagger UI code and style from npm using unpkg.com --> <script src="https://unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@3/swagger-ui.css"/> <title>Text Generation Inference API</title> </head> <body> <div id="swagger-ui"></div> <!-- Div to hold the UI component --> <script> window.onload = function () { // Begin Swagger UI call region const ui = SwaggerUIBundle({ url: "openapi.json", //Location of Open API spec in the repo dom_id: '#swagger-ui', deepLinking: true, supportedSubmitMethods: [], presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], }) window.ui = ui } </script> </body> </html>
text-generation-inference/docs/index.html/0
{ "file_path": "text-generation-inference/docs/index.html", "repo_id": "text-generation-inference", "token_count": 653 }
297
# Guidance Text Generation Inference (TGI) now supports [JSON and regex grammars](#grammar-and-constraints) and [tools and functions](#tools-and-functions) to help developers guide LLM responses to fit their needs. These feature are available starting from version `1.4.3`. They are accessible via the [`huggingface_hub`](https://pypi.org/project/huggingface-hub/) library. The tool support is compatible with OpenAI's client libraries. The following guide will walk you through the new features and how to use them! _note: guidance is supported as grammar in the `/generate` endpoint and as tools in the `v1/chat/completions` endpoint._ ## How it works TGI leverages the [outlines](https://github.com/outlines-dev/outlines) library to efficiently parse and compile the grammatical structures and tools specified by users. This integration transforms the defined grammars into an intermediate representation that acts as a framework to guide and constrain content generation, ensuring that outputs adhere to the specified grammatical rules. If you are interested in the technical details on how outlines is used in TGI, you can check out the [conceptual guidance documentation](../conceptual/guidance). ## Table of Contents 📚 ### Grammar and Constraints - [The Grammar Parameter](#the-grammar-parameter): Shape your AI's responses with precision. - [Constrain with Pydantic](#constrain-with-pydantic): Define a grammar using Pydantic models. - [JSON Schema Integration](#json-schema-integration): Fine-grained control over your requests via JSON schema. - [Using the client](#using-the-client): Use TGI's client libraries to shape the AI's responses. ### Tools and Functions - [The Tools Parameter](#the-tools-parameter): Enhance the AI's capabilities with predefined functions. - [Via the client](#text-generation-inference-client): Use TGI's client libraries to interact with the Messages API and Tool functions. - [OpenAI integration](#openai-integration): Use OpenAI's client libraries to interact with TGI's Messages API and Tool functions. ## Grammar and Constraints 🛣️ ### The Grammar Parameter In TGI `1.4.3`, we've introduced the grammar parameter, which allows you to specify the format of the response you want from the LLM. Using curl, you can make a request to TGI's Messages API with the grammar parameter. This is the most primitive way to interact with the API and using [Pydantic](#constrain-with-pydantic) is recommended for ease of use and readability. ```json curl localhost:3000/generate \ -X POST \ -H 'Content-Type: application/json' \ -d '{ "inputs": "I saw a puppy a cat and a raccoon during my bike ride in the park", "parameters": { "repetition_penalty": 1.3, "grammar": { "type": "json", "value": { "properties": { "location": { "type": "string" }, "activity": { "type": "string" }, "animals_seen": { "type": "integer", "minimum": 1, "maximum": 5 }, "animals": { "type": "array", "items": { "type": "string" } } }, "required": ["location", "activity", "animals_seen", "animals"] } } } }' // {"generated_text":"{ \n\n\"activity\": \"biking\",\n\"animals\": [\"puppy\",\"cat\",\"raccoon\"],\n\"animals_seen\": 3,\n\"location\": \"park\"\n}"} ``` ### Hugging Face Hub Python Library The Hugging Face Hub Python library provides a client that makes it easy to interact with the Messages API. Here's an example of how to use the client to send a request with a grammar parameter. ```python from huggingface_hub import InferenceClient client = InferenceClient("http://localhost:3000") schema = { "properties": { "location": {"title": "Location", "type": "string"}, "activity": {"title": "Activity", "type": "string"}, "animals_seen": { "maximum": 5, "minimum": 1, "title": "Animals Seen", "type": "integer", }, "animals": {"items": {"type": "string"}, "title": "Animals", "type": "array"}, }, "required": ["location", "activity", "animals_seen", "animals"], "title": "Animals", "type": "object", } user_input = "I saw a puppy a cat and a raccoon during my bike ride in the park" resp = client.text_generation( f"convert to JSON: 'f{user_input}'. please use the following schema: {schema}", max_new_tokens=100, seed=42, grammar={"type": "json", "value": schema}, ) print(resp) # { "activity": "bike ride", "animals": ["puppy", "cat", "raccoon"], "animals_seen": 3, "location": "park" } ``` A grammar can be defined using Pydantic models, JSON schemas, or regular expressions. The LLM will then generate a response that conforms to the specified grammar. > Note: A grammar must compile to an intermediate representation to constrain the output. Grammar compilation is a computationally expensive and may take a few seconds to complete on the first request. Subsequent requests will use the cached grammar and will be much faster. ### Constrain with Pydantic Using Pydantic models we can define a similar grammar as the previous example in a shorter and more readable way. ```python from huggingface_hub import InferenceClient from pydantic import BaseModel, conint from typing import List class Animals(BaseModel): location: str activity: str animals_seen: conint(ge=1, le=5) # Constrained integer type animals: List[str] client = InferenceClient("http://localhost:3000") user_input = "I saw a puppy a cat and a raccoon during my bike ride in the park" resp = client.text_generation( f"convert to JSON: 'f{user_input}'. please use the following schema: {Animals.model_json_schema()}", max_new_tokens=100, seed=42, grammar={"type": "json", "value": Animals.model_json_schema()}, ) print(resp) # { "activity": "bike ride", "animals": ["puppy", "cat", "raccoon"], "animals_seen": 3, "location": "park" } ``` defining a grammar as regular expressions ```python from huggingface_hub import InferenceClient client = InferenceClient("http://localhost:3000") section_regex = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" regexp = f"HELLO\.{section_regex}\.WORLD\.{section_regex}" # This is a more realistic example of an ip address regex # regexp = f"{section_regex}\.{section_regex}\.{section_regex}\.{section_regex}" resp = client.text_generation( f"Whats Googles DNS? Please use the following regex: {regexp}", seed=42, grammar={ "type": "regex", "value": regexp, }, ) print(resp) # HELLO.255.WORLD.255 ``` ## Tools and Functions 🛠️ ### The Tools Parameter In addition to the grammar parameter, we've also introduced a set of tools and functions to help you get the most out of the Messages API. Tools are a set of user defined functions that can be used in tandem with the chat functionality to enhance the LLM's capabilities. Functions, similar to grammar are defined as JSON schema and can be passed as part of the parameters to the Messages API. ```json curl localhost:3000/v1/chat/completions \ -X POST \ -H 'Content-Type: application/json' \ -d '{ "model": "tgi", "messages": [ { "role": "user", "content": "What is the weather like in New York?" } ], "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature unit to use. Infer this from the users location." } }, "required": ["location", "format"] } } } ], "tool_choice": "get_current_weather" }' // {"id":"","object":"text_completion","created":1709051640,"model":"HuggingFaceH4/zephyr-7b-beta","system_fingerprint":"1.4.3-native","choices":[{"index":0,"message":{"role":"assistant","tool_calls":{"id":0,"type":"function","function":{"description":null,"name":"tools","parameters":{"format":"celsius","location":"New York"}}}},"logprobs":null,"finish_reason":"eos_token"}],"usage":{"prompt_tokens":157,"completion_tokens":19,"total_tokens":176}} ``` ### Chat Completion with Tools Grammars are supported in the `/generate` endpoint, while tools are supported in the `/chat/completions` endpoint. Here's an example of how to use the client to send a request with a tool parameter. ```python from huggingface_hub import InferenceClient client = InferenceClient("http://localhost:3000") tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature unit to use. Infer this from the users location.", }, }, "required": ["location", "format"], }, }, }, { "type": "function", "function": { "name": "get_n_day_weather_forecast", "description": "Get an N-day weather forecast", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature unit to use. Infer this from the users location.", }, "num_days": { "type": "integer", "description": "The number of days to forecast", }, }, "required": ["location", "format", "num_days"], }, }, }, ] chat = client.chat_completion( messages=[ { "role": "system", "content": "You're a helpful assistant! Answer the users question best you can.", }, { "role": "user", "content": "What is the weather like in Brooklyn, New York?", }, ], tools=tools, seed=42, max_tokens=100, ) print(chat.choices[0].message.tool_calls) # [ChatCompletionOutputToolCall(function=ChatCompletionOutputFunctionDefinition(arguments={'format': 'fahrenheit', 'location': 'Brooklyn, New York', 'num_days': 7}, name='get_n_day_weather_forecast', description=None), id=0, type='function')] ``` ### OpenAI integration TGI exposes an OpenAI-compatible API, which means you can use OpenAI's client libraries to interact with TGI's Messages API and Tool functions. ```python from openai import OpenAI # Initialize the client, pointing it to one of the available models client = OpenAI( base_url="http://localhost:3000/v1", api_key="_", ) # NOTE: tools defined above and removed for brevity chat_completion = client.chat.completions.create( model="tgi", messages=[ { "role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.", }, { "role": "user", "content": "What's the weather like the next 3 days in San Francisco, CA?", }, ], tools=tools, tool_choice="auto", # tool selected by model max_tokens=500, ) called = chat_completion.choices[0].message.tool_calls print(called) # { # "id": 0, # "type": "function", # "function": { # "description": None, # "name": "tools", # "parameters": { # "format": "celsius", # "location": "San Francisco, CA", # "num_days": 3, # }, # }, # } ``` ### Tool Choice Configuration When configuring how the model interacts with tools during a chat completion, there are several options for determining if or how a tool should be called. These options are controlled by the `tool_choice` parameter, which specifies the behavior of the model in relation to tool usage. The following modes are supported: 1. **`auto`**: - The model decides whether to call a tool or generate a response message based on the user's input. - If tools are provided, this is the default mode. - Example usage: ```python tool_choice="auto" ``` 2. **`none`**: - The model will never call any tools and will only generate a response message. - If no tools are provided, this is the default mode. - Example usage: ```python tool_choice="none" ``` 3. **`required`**: - The model must call one or more tools and will not generate a response message on its own. - Example usage: ```python tool_choice="required" ``` 4. **Specific Tool Call by Function Name**: - You can force the model to call a specific tool either by specifying the tool function directly or by using an object definition. - Two ways to do this: 1. Provide the function name as a string: ```python tool_choice="get_current_weather" ``` 2. Use the function object format: ```python tool_choice={ "type": "function", "function": { "name": "get_current_weather" } } ``` These options allow flexibility when integrating tools with the chat completions endpoint. You can configure the model to either rely on tools automatically or force it to follow a predefined behavior, based on the needs of the task at hand. --- | **Tool Choice Option** | **Description** | **When to Use** | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | `auto` | The model decides whether to call a tool or generate a message. This is the default if tools are provided. | Use when you want the model to decide when a tool is necessary. | | `none` | The model generates a message without calling any tools. This is the default if no tools are provided. | Use when you do not want the model to call any tools. | | `required` | The model must call one or more tools and will not generate a message on its own. | Use when a tool call is mandatory, and you do not want a regular message generated. | | Specific Tool Call (`name` or object) | Force the model to call a specific tool either by specifying its name (`tool_choice="get_current_weather"`) or using an object. | Use when you want to restrict the model to calling a particular tool for the response. |
text-generation-inference/docs/source/basic_tutorials/using_guidance.md/0
{ "file_path": "text-generation-inference/docs/source/basic_tutorials/using_guidance.md", "repo_id": "text-generation-inference", "token_count": 6738 }
298
# Using TGI with Intel Gaudi You can use TGI on Intel Gaudi using the [TGI gaudi backend](https://huggingface.co/docs/text-generation-inference/backends/gaudi).
text-generation-inference/docs/source/installation_gaudi.md/0
{ "file_path": "text-generation-inference/docs/source/installation_gaudi.md", "repo_id": "text-generation-inference", "token_count": 53 }
299
import copy import logging import sys from tempfile import TemporaryDirectory import huggingface_hub import pytest import docker import hashlib import os import tempfile from docker.errors import NotFound TEST_ORGANIZATION = "optimum-internal-testing" TEST_CACHE_REPO_ID = f"{TEST_ORGANIZATION}/neuron-testing-cache" HF_TOKEN = huggingface_hub.get_token() logging.basicConfig( level=logging.INFO, format="[%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s", stream=sys.stdout, ) logger = logging.getLogger(__file__) # All model configurations below will be added to the neuron_model_config fixture MODEL_CONFIGURATIONS = { "llama": { "model_id": "unsloth/Llama-3.2-1B-Instruct", "export_kwargs": { "batch_size": 4, "sequence_length": 2048, "num_cores": 2, "auto_cast_type": "fp16", }, }, "qwen2": { "model_id": "Qwen/Qwen2.5-0.5B", "export_kwargs": { "batch_size": 4, "sequence_length": 4096, "num_cores": 2, "auto_cast_type": "fp16", }, }, "qwen3": { "model_id": "Qwen/Qwen3-1.7B", "export_kwargs": { "batch_size": 4, "sequence_length": 4096, "num_cores": 2, "auto_cast_type": "bf16", }, }, "granite": { "model_id": "ibm-granite/granite-3.1-2b-instruct", "export_kwargs": { "batch_size": 4, "sequence_length": 4096, "num_cores": 2, "auto_cast_type": "bf16", }, }, "phi3": { "model_id": "microsoft/Phi-3-mini-4k-instruct", "export_kwargs": { "batch_size": 4, "sequence_length": 4096, "num_cores": 2, "auto_cast_type": "bf16", }, }, } def get_neuron_backend_hash(): import subprocess res = subprocess.run( ["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True ) root_dir = res.stdout.split("\n")[0] def get_sha(path): res = subprocess.run( ["git", "ls-tree", "HEAD", f"{root_dir}/{path}"], capture_output=True, text=True, ) # Output of the command is in the form '040000 tree|blob <SHA>\t<path>\n' sha = res.stdout.split("\t")[0].split(" ")[-1] return sha.encode() # We hash both the neuron backends directory and Dockerfile and create a smaller hash out of that m = hashlib.sha256() m.update(get_sha("backends/neuron")) m.update(get_sha("Dockerfile.neuron")) return m.hexdigest()[:10] def get_neuron_model_name(config_name: str): return f"neuron-tgi-testing-{config_name}-{get_neuron_backend_hash()}" def get_tgi_docker_image(): docker_image = os.getenv("DOCKER_IMAGE", None) if docker_image is None: client = docker.from_env() images = client.images.list(filters={"reference": "text-generation-inference"}) if not images: raise ValueError( "No text-generation-inference image found on this host to run tests." ) docker_image = images[0].tags[0] return docker_image def maybe_export_model(config_name, model_config): """Export a neuron model for the specified test configuration. If the neuron model has not already been compiled and pushed to the hub, it is exported by a custom image built on the fly from the base TGI image. This makes sure the exported model and image are aligned and avoids introducing neuron specific imports in the test suite. Args: config_name (`str`): Used to identify test configurations model_config (`str`): The model configuration for export (includes the original model id) """ neuron_model_name = get_neuron_model_name(config_name) neuron_model_id = f"{TEST_ORGANIZATION}/{neuron_model_name}" hub = huggingface_hub.HfApi() if hub.repo_exists(neuron_model_id): logger.info( f"Skipping model export for config {config_name} as {neuron_model_id} already exists" ) return neuron_model_id client = docker.from_env() env = {"LOG_LEVEL": "info", "CUSTOM_CACHE_REPO": TEST_CACHE_REPO_ID} if HF_TOKEN is not None: env["HUGGING_FACE_HUB_TOKEN"] = HF_TOKEN env["HF_TOKEN"] = HF_TOKEN # Create a sub-image to export the model to workaround docker dind issues preventing # to share a volume from the container running tests model_id = model_config["model_id"] export_kwargs = model_config["export_kwargs"] base_image = get_tgi_docker_image() export_image = f"neuron-tgi-tests-{config_name}-export-img" logger.info(f"Building temporary image {export_image} from {base_image}") with tempfile.TemporaryDirectory() as context_dir: # Create entrypoint model_path = "/data/neuron_model" export_command = ( f"optimum-cli export neuron -m {model_id} --task text-generation" ) for kwarg, value in export_kwargs.items(): export_command += f" --{kwarg} {str(value)}" export_command += f" {model_path}" entrypoint_content = f"""#!/bin/sh {export_command} huggingface-cli repo create --organization {TEST_ORGANIZATION} {neuron_model_name} huggingface-cli upload {TEST_ORGANIZATION}/{neuron_model_name} {model_path} --exclude *.bin *.safetensors optimum-cli neuron cache synchronize --repo_id {TEST_CACHE_REPO_ID} """ with open(os.path.join(context_dir, "entrypoint.sh"), "wb") as f: f.write(entrypoint_content.encode("utf-8")) f.flush() # Create Dockerfile docker_content = f""" FROM {base_image} COPY entrypoint.sh /export-entrypoint.sh RUN chmod +x /export-entrypoint.sh ENTRYPOINT ["/export-entrypoint.sh"] """ with open(os.path.join(context_dir, "Dockerfile"), "wb") as f: f.write(docker_content.encode("utf-8")) f.flush() image, logs = client.images.build( path=context_dir, dockerfile=f.name, tag=export_image ) logger.info("Successfully built image %s", image.id) logger.debug("Build logs %s", logs) try: client.containers.run( export_image, environment=env, auto_remove=True, detach=False, devices=["/dev/neuron0"], shm_size="1G", ) logger.info(f"Successfully exported model for config {config_name}") except Exception as e: logger.exception(f"An exception occurred while running container: {e}.") pass finally: # Cleanup the export image logger.info("Cleaning image %s", image.id) try: image.remove(force=True) except NotFound: pass except Exception as e: logger.error("Error while removing image %s, skipping", image.id) logger.exception(e) return neuron_model_id def maybe_export_models(): for config_name, model_config in MODEL_CONFIGURATIONS.items(): maybe_export_model(config_name, model_config) @pytest.fixture(scope="session", params=MODEL_CONFIGURATIONS.keys()) def neuron_model_config(request): """Expose a pre-trained neuron model The fixture first makes sure the following model artifacts are present on the hub: - exported neuron model under optimum-internal-testing/neuron-testing-<name>-<version>, - cached artifacts under optimum-internal-testing/neuron-testing-cache. If not, it will export the model and push it to the hub. It then fetches the model locally and return a dictionary containing: - a configuration name, - the original model id, - the export parameters, - the neuron model id, - the neuron model local path. For each exposed model, the local directory is maintained for the duration of the test session and cleaned up afterwards. The hub model artifacts are never cleaned up and persist accross sessions. They must be cleaned up manually when the optimum-neuron version changes. """ config_name = request.param model_config = copy.deepcopy(MODEL_CONFIGURATIONS[request.param]) # Export the model first (only if needed) neuron_model_id = maybe_export_model(config_name, model_config) with TemporaryDirectory() as neuron_model_path: logger.info(f"Fetching {neuron_model_id} from the HuggingFace hub") hub = huggingface_hub.HfApi() hub.snapshot_download( neuron_model_id, etag_timeout=30, local_dir=neuron_model_path ) # Add dynamic parameters to the model configuration model_config["neuron_model_path"] = neuron_model_path model_config["neuron_model_id"] = neuron_model_id # Also add model configuration name to allow tests to adapt their expectations model_config["name"] = config_name # Yield instead of returning to keep a reference to the temporary directory. # It will go out of scope and be released only once all tests needing the fixture # have been completed. logger.info(f"{config_name} ready for testing ...") yield model_config logger.info(f"Done with {config_name}") @pytest.fixture(scope="module") def neuron_model_path(neuron_model_config): yield neuron_model_config["neuron_model_path"] if __name__ == "__main__": maybe_export_models()
text-generation-inference/integration-tests/fixtures/neuron/export_models.py/0
{ "file_path": "text-generation-inference/integration-tests/fixtures/neuron/export_models.py", "repo_id": "text-generation-inference", "token_count": 4075 }
300
[ { "choices": [ { "delta": { "content": "OK", "function_call": null, "refusal": null, "role": "assistant", "tool_calls": null }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741265133, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": "!", "function_call": null, "refusal": null, "role": "assistant", "tool_calls": null }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741265133, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": "", "function_call": null, "refusal": null, "role": "assistant", "tool_calls": null }, "finish_reason": "stop", "index": 0, "logprobs": null } ], "created": 1741265133, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [], "created": 1741265133, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": "3.1.2-dev0-native", "usage": { "completion_tokens": 3, "completion_tokens_details": null, "prompt_tokens": 39, "prompt_tokens_details": null, "total_tokens": 42 } } ]
text-generation-inference/integration-tests/models/__snapshots__/test_completion_prompts/test_chat_openai_usage.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_completion_prompts/test_chat_openai_usage.json", "repo_id": "text-generation-inference", "token_count": 1068 }
301
{ "details": { "best_of_sequences": null, "finish_reason": "length", "generated_tokens": 10, "prefill": [], "seed": null, "tokens": [ { "id": 198, "logprob": -0.68603516, "special": false, "text": "\n" }, { "id": 198, "logprob": -0.005393982, "special": false, "text": "\n" }, { "id": 29744, "logprob": -0.31079102, "special": false, "text": "Deep" }, { "id": 4673, "logprob": -0.08300781, "special": false, "text": " learning" }, { "id": 318, "logprob": -0.58984375, "special": false, "text": " is" }, { "id": 257, "logprob": -0.953125, "special": false, "text": " a" }, { "id": 649, "logprob": -2.0957031, "special": false, "text": " new" }, { "id": 2214, "logprob": -1.8095703, "special": false, "text": " field" }, { "id": 286, "logprob": -1.0673828, "special": false, "text": " of" }, { "id": 2267, "logprob": -0.9375, "special": false, "text": " research" } ], "top_tokens": null }, "generated_text": "\n\nDeep learning is a new field of research" }
text-generation-inference/integration-tests/models/__snapshots__/test_flash_gpt2/test_flash_gpt2.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_flash_gpt2/test_flash_gpt2.json", "repo_id": "text-generation-inference", "token_count": 866 }
302
{ "choices": [ { "delta": { "content": "", "role": "assistant", "tool_calls": null }, "finish_reason": "stop", "index": 0, "logprobs": null } ], "created": 1738343559, "id": "", "model": "Qwen/Qwen2.5-VL-3B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.0.2-dev0-native", "usage": null }
text-generation-inference/integration-tests/models/__snapshots__/test_flash_qwen2_5_vl/test_flash_qwen2_5_vl_simple_streaming.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_flash_qwen2_5_vl/test_flash_qwen2_5_vl_simple_streaming.json", "repo_id": "text-generation-inference", "token_count": 203 }
303
{ "details": { "finish_reason": "length", "generated_tokens": 10, "prefill": [], "seed": null, "tokens": [ { "id": 100, "logprob": -0.9824219, "special": false, "text": "_" }, { "id": 5879, "logprob": -0.3017578, "special": false, "text": "world" }, { "id": 2284, "logprob": -0.68652344, "special": false, "text": "():" }, { "id": 303, "logprob": -0.27734375, "special": false, "text": "\n " }, { "id": 1489, "logprob": -0.4482422, "special": false, "text": " print" }, { "id": 459, "logprob": -0.54248047, "special": false, "text": "(\"" }, { "id": 8302, "logprob": -0.4296875, "special": false, "text": "Hello" }, { "id": 10914, "logprob": -0.8544922, "special": false, "text": " World" }, { "id": 16013, "logprob": -0.7573242, "special": false, "text": "!\")" }, { "id": 222, "logprob": -0.81347656, "special": false, "text": "\n" } ] }, "generated_text": "_world():\n print(\"Hello World!\")\n" }
text-generation-inference/integration-tests/models/__snapshots__/test_flash_starcoder2_lora/test_flash_starcoder2_with_hugcode_adapter.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_flash_starcoder2_lora/test_flash_starcoder2_with_hugcode_adapter.json", "repo_id": "text-generation-inference", "token_count": 852 }
304
{ "choices": [ { "finish_reason": "stop", "index": 0, "logprobs": null, "message": { "content": "{\"firstName\":\"David\",\"lastName\":\"(Not provided)\",\"hobby\":\", nature\",\"numCats\":2}", "role": "assistant" } } ], "created": 1746053368, "id": "", "model": "google/gemma-3-4b-it", "object": "chat.completion", "system_fingerprint": "3.3.4-dev0-native", "usage": { "completion_tokens": 35, "prompt_tokens": 32, "total_tokens": 67 } }
text-generation-inference/integration-tests/models/__snapshots__/test_json_schema_constrain/test_json_schema_basic.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_json_schema_constrain/test_json_schema_basic.json", "repo_id": "text-generation-inference", "token_count": 254 }
305
[ { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": "{", "name": "get_current_weather" }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": " \"", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": "location", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": "\":", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": " \"", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": "Bro", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": "oklyn", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": ",", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": " NY", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": "\",", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": " \"", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": "format", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": "\":", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": " \"", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": "f", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": "ahrenheit", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null }, { "choices": [ { "delta": { "content": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": "\"}", "name": null }, "id": "0", "index": 0, "type": "function" } ] }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1741688515, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "chat.completion.chunk", "system_fingerprint": "3.1.2-dev0-native", "usage": null } ]
text-generation-inference/integration-tests/models/__snapshots__/test_tools_llama/test_flash_llama_grammar_tools_choice_stream.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_tools_llama/test_flash_llama_grammar_tools_choice_stream.json", "repo_id": "text-generation-inference", "token_count": 7033 }
306
import pytest @pytest.fixture(scope="module") def flash_falcon_handle(launcher): with launcher("tiiuae/falcon-7b", trust_remote_code=True) as handle: yield handle @pytest.fixture(scope="module") async def flash_falcon(flash_falcon_handle): await flash_falcon_handle.health(300) return flash_falcon_handle.client @pytest.mark.release @pytest.mark.asyncio @pytest.mark.private async def test_flash_falcon(flash_falcon, response_snapshot): response = await flash_falcon.generate( "Girafatron is obsessed with giraffes, the most glorious animal on the face of this Earth. Giraftron believes all other animals are irrelevant when compared to the glorious majesty of the giraffe.\nDaniel: Hello, Girafatron!\nGirafatron:", max_new_tokens=10, decoder_input_details=True, ) assert response.details.generated_tokens == 10 assert response == response_snapshot @pytest.mark.release @pytest.mark.asyncio @pytest.mark.private async def test_flash_falcon_all_params(flash_falcon, response_snapshot): response = await flash_falcon.generate( "Girafatron is obsessed with giraffes, the most glorious animal on the face of this Earth. Giraftron believes all other animals are irrelevant when compared to the glorious majesty of the giraffe.\nDaniel: Hello, Girafatron!\nGirafatron:", max_new_tokens=10, repetition_penalty=1.2, return_full_text=True, stop_sequences=["test"], temperature=0.5, top_p=0.9, top_k=10, truncate=5, typical_p=0.9, watermark=True, decoder_input_details=True, seed=0, ) assert response.details.generated_tokens == 10 assert response == response_snapshot @pytest.mark.release @pytest.mark.asyncio @pytest.mark.private async def test_flash_falcon_load(flash_falcon, generate_load, response_snapshot): responses = await generate_load( flash_falcon, "Girafatron is obsessed with giraffes, the most glorious animal on the face of this Earth. Giraftron believes all other animals are irrelevant when compared to the glorious majesty of the giraffe.\nDaniel: Hello, Girafatron!\nGirafatron:", max_new_tokens=10, n=4, ) assert len(responses) == 4 assert all([r.generated_text == responses[0].generated_text for r in responses]) assert responses == response_snapshot
text-generation-inference/integration-tests/models/test_flash_falcon.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_flash_falcon.py", "repo_id": "text-generation-inference", "token_count": 908 }
307
import pytest @pytest.fixture(scope="module") def flash_medusa_handle(launcher): with launcher( "FasterDecoding/medusa-vicuna-7b-v1.3", num_shard=2, revision="refs/pr/1" ) as handle: yield handle @pytest.fixture(scope="module") async def flash_medusa(flash_medusa_handle): await flash_medusa_handle.health(300) return flash_medusa_handle.client @pytest.mark.asyncio async def test_flash_medusa_simple(flash_medusa, response_snapshot): response = await flash_medusa.generate( "What is Deep Learning?", max_new_tokens=10, decoder_input_details=True ) assert response.details.generated_tokens == 10 assert response == response_snapshot @pytest.mark.asyncio async def test_flash_medusa_all_params(flash_medusa, response_snapshot): response = await flash_medusa.generate( "What is Deep Learning?", max_new_tokens=10, repetition_penalty=1.2, return_full_text=True, stop_sequences=["test"], temperature=0.5, top_p=0.9, top_k=10, truncate=5, typical_p=0.9, watermark=True, decoder_input_details=True, seed=0, ) assert response.details.generated_tokens == 10 assert response == response_snapshot @pytest.mark.asyncio async def test_flash_medusa_load(flash_medusa, generate_load, response_snapshot): responses = await generate_load( flash_medusa, "What is Deep Learning?", max_new_tokens=10, n=4 ) assert len(responses) == 4 assert all( [r.generated_text == responses[0].generated_text for r in responses] ), f"{[r.generated_text for r in responses]}" assert ( responses[0].generated_text == "\nDeep learning is a subset of machine learning" ) assert responses == response_snapshot
text-generation-inference/integration-tests/models/test_flash_medusa.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_flash_medusa.py", "repo_id": "text-generation-inference", "token_count": 749 }
308
import pytest @pytest.fixture(scope="module") def flash_starcoder2_handle(launcher): with launcher("bigcode/starcoder2-3b", num_shard=2) as handle: yield handle @pytest.fixture(scope="module") async def flash_starcoder2(flash_starcoder2_handle): await flash_starcoder2_handle.health(300) return flash_starcoder2_handle.client @pytest.mark.release @pytest.mark.asyncio @pytest.mark.private async def test_flash_starcoder2(flash_starcoder2, response_snapshot): response = await flash_starcoder2.generate( "def print_hello", max_new_tokens=10, decoder_input_details=True ) assert response.details.generated_tokens == 10 assert response == response_snapshot @pytest.mark.release @pytest.mark.asyncio @pytest.mark.private async def test_flash_starcoder2_default_params(flash_starcoder2, response_snapshot): response = await flash_starcoder2.generate( "def print_hello", max_new_tokens=60, temperature=0.2, top_p=0.95, decoder_input_details=True, seed=0, ) assert response.details.generated_tokens == 60 assert response == response_snapshot @pytest.mark.release @pytest.mark.asyncio @pytest.mark.private async def test_flash_starcoder2_load( flash_starcoder2, generate_load, response_snapshot ): responses = await generate_load( flash_starcoder2, "def print_hello", max_new_tokens=10, n=4 ) assert len(responses) == 4 assert all([r.generated_text == responses[0].generated_text for r in responses]) assert responses == response_snapshot
text-generation-inference/integration-tests/models/test_flash_starcoder2.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_flash_starcoder2.py", "repo_id": "text-generation-inference", "token_count": 625 }
309
import pytest @pytest.fixture(scope="module") def neox_sharded_handle(launcher): with launcher( "OpenAssistant/oasst-sft-1-pythia-12b", num_shard=2, use_flash_attention=False ) as handle: yield handle @pytest.fixture(scope="module") async def neox_sharded(neox_sharded_handle): await neox_sharded_handle.health(300) return neox_sharded_handle.client @pytest.mark.release @pytest.mark.skip @pytest.mark.asyncio async def test_neox(neox_sharded, response_snapshot): response = await neox_sharded.generate( "<|prompter|>What is a meme, and what's the history behind this word?<|endoftext|><|assistant|>", max_new_tokens=10, decoder_input_details=True, ) assert response.details.generated_tokens == 10 assert response == response_snapshot @pytest.mark.release @pytest.mark.skip @pytest.mark.asyncio async def test_neox_load(neox_sharded, generate_load, response_snapshot): responses = await generate_load( neox_sharded, "<|prompter|>What is a meme, and what's the history behind this word?<|endoftext|><|assistant|>", max_new_tokens=10, n=4, ) assert len(responses) == 4 assert all([r.generated_text == responses[0].generated_text for r in responses]) assert responses == response_snapshot
text-generation-inference/integration-tests/models/test_neox_sharded.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_neox_sharded.py", "repo_id": "text-generation-inference", "token_count": 523 }
310
pub fn get_cuda_capability() -> Option<(usize, usize)> { use pyo3::prelude::*; let py_get_capability = |py: Python| -> PyResult<(isize, isize)> { let torch = py.import_bound("torch.cuda")?; let get_device_capability = torch.getattr("get_device_capability")?; get_device_capability.call0()?.extract() }; match pyo3::Python::with_gil(py_get_capability) { Ok((major, minor)) if major < 0 || minor < 0 => { tracing::warn!("Ignoring negative GPU compute capabilities: {major}.{minor}"); None } Ok((major, minor)) => Some((major as usize, minor as usize)), Err(err) => { tracing::warn!("Cannot determine GPU compute capability: {}", err); None } } }
text-generation-inference/launcher/src/gpu.rs/0
{ "file_path": "text-generation-inference/launcher/src/gpu.rs", "repo_id": "text-generation-inference", "token_count": 350 }
311
final: prev: { # You can use this overlay to temporarily override packages for # development. For permanent overrides, it's better to do this in # our package flake: # # https://github.com/huggingface/text-generation-inference-nix # # Note that overriding packages that are in the transitive closure # of many other packages (e.g. transformers) will require a large # rebuild. pythonPackagesExtensions = prev.pythonPackagesExtensions ++ [ ( python-self: python-super: with python-self; { # Python package override example: #transformers = python-super.transformers.overrideAttrs ( # _: _: { # src = final.fetchFromGitHub { # owner = "huggingface"; # repo = "transformers"; # rev = "v4.51.0"; # hash = "sha256-dnVpc6fm1SYGcx7FegpwVVxUY6XRlsxLs5WOxYv11y8="; # }; # } #); #huggingface-hub = python-super.huggingface-hub.overrideAttrs ( # _: _: { # src = final.fetchFromGitHub { # owner = "huggingface"; # repo = "huggingface_hub"; # rev = "v0.30.0"; # hash = "sha256-sz+n1uoWrSQPqJFiG/qCT6b4r08kD9MsoPZXbfWNB2o="; # }; # } #); } ) ]; # Non-python package override example: # # ripgrep = prev.ripgrep.overrideAttrs ( # _: _: { # src = final.fetchFromGitHub { # owner = "BurntSushi"; # repo = "ripgrep"; # rev = "79cbe89deb1151e703f4d91b19af9cdcc128b765"; # hash = "sha256-JPTM2KNmGMb+/jOfK3X7OM1wnN+3TU35SJOIcqmp3mg="; # }; # }); }
text-generation-inference/nix/overlay.nix/0
{ "file_path": "text-generation-inference/nix/overlay.nix", "repo_id": "text-generation-inference", "token_count": 818 }
312
use crate::chat::{ChatChoice, ChatEvent, ChatState}; /// HTTP Server logic use crate::config::Config; use crate::infer::{Backend, Infer, InferError, InferResponse, InferStreamResponse}; #[cfg(feature = "kserve")] use crate::kserve::{ kerve_server_metadata, kserve_health_live, kserve_health_ready, kserve_model_infer, kserve_model_metadata, kserve_model_metadata_ready, }; use crate::logging::trace_context_middleware; use crate::sagemaker::{ sagemaker_compatibility, SagemakerRequest, SagemakerResponse, SagemakerStreamResponse, __path_sagemaker_compatibility, }; use crate::validation::ValidationError; use crate::vertex::vertex_compatibility; use crate::{ usage_stats, BestOfSequence, Details, ErrorResponse, FinishReason, FunctionName, GenerateParameters, GenerateRequest, GenerateResponse, GrammarType, HubModelInfo, HubProcessorConfig, HubTokenizerConfig, Info, Message, MessageChunk, MessageContent, OutputMessage, PrefillToken, SimpleToken, StreamDetails, StreamOptions, StreamResponse, TextMessage, Token, TokenizeResponse, Tokenizer, ToolCallDelta, ToolCallMessage, Url, Usage, Validation, }; use crate::{ ChatCompletion, ChatCompletionChoice, ChatCompletionChunk, ChatCompletionComplete, ChatCompletionDelta, ChatCompletionLogprob, ChatCompletionLogprobs, ChatCompletionTopLogprob, ChatRequest, Chunk, CompatGenerateRequest, Completion, CompletionComplete, CompletionFinal, CompletionRequest, CompletionType, DeltaToolCall, Function, Prompt, Tool, }; use crate::{ChatTokenizeResponse, JsonSchemaConfig}; use crate::{FunctionDefinition, HubPreprocessorConfig, ToolCall, ToolChoice}; use crate::{MessageBody, ModelInfo, ModelsInfo}; use async_stream::__private::AsyncStream; use axum::extract::{DefaultBodyLimit, Extension}; use axum::http::{HeaderMap, HeaderValue, Method, StatusCode}; use axum::response::sse::{Event, KeepAlive, Sse}; use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::{http, Json, Router}; use axum_tracing_opentelemetry::middleware::OtelAxumLayer; use futures::stream::StreamExt; use futures::stream::{FuturesOrdered, FuturesUnordered}; use futures::Stream; use futures::TryStreamExt; use hf_hub::api::tokio::{Api, ApiBuilder, ApiRepo}; use hf_hub::{Cache, Repo, RepoType}; use http::header::AUTHORIZATION; use metrics_exporter_prometheus::{Matcher, PrometheusBuilder, PrometheusHandle}; use pyo3::prelude::*; use pyo3::types::IntoPyDict; use std::convert::Infallible; use std::fs::File; use std::io::BufReader; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::Duration; use thiserror::Error; use tokio::select; use tokio::signal; use tokio::sync::oneshot; use tokio::time::Instant; use tower_http::cors::{AllowOrigin, CorsLayer}; use tracing::{info_span, instrument, Instrument}; use tracing_opentelemetry::OpenTelemetrySpanExt; use utoipa::OpenApi; use utoipa_swagger_ui::SwaggerUi; fn encoding_to_tokens(encoding: &tokenizers::Encoding, input: &str) -> Vec<SimpleToken> { let offsets = encoding.get_offsets(); let input_ids = encoding.get_ids(); if offsets.len() == input_ids.len() { input_ids .iter() .zip(offsets) .map(|(&id, &(start, stop))| { let text: Vec<u8> = input.bytes().skip(start).take(stop - start).collect(); let text: String = String::from_utf8_lossy(&text).to_string(); SimpleToken { id, text, start, stop, } }) .collect() } else { encoding .get_ids() .iter() .map(|&id| SimpleToken { id, text: "".to_string(), start: 0, stop: 0, }) .collect() } } /// Generate tokens if `stream == false` or a stream of token if `stream == true` #[utoipa::path( post, tag = "Text Generation Inference", path = "/", request_body = CompatGenerateRequest, responses( (status = 200, description = "Generated Text", content( ("application/json" = Vec<GenerateResponse>), ("text/event-stream" = StreamResponse), )), (status = 424, description = "Generation Error", body = ErrorResponse, example = json ! ({"error": "Request failed during generation"})), (status = 429, description = "Model is overloaded", body = ErrorResponse, example = json ! ({"error": "Model is overloaded"})), (status = 422, description = "Input validation error", body = ErrorResponse, example = json ! ({"error": "Input validation error"})), (status = 500, description = "Incomplete generation", body = ErrorResponse, example = json ! ({"error": "Incomplete generation"})), ) )] #[instrument(skip(infer, req))] pub(crate) async fn compat_generate( Extension(default_return_full_text): Extension<bool>, infer: Extension<Infer>, compute_type: Extension<ComputeType>, context: Extension<Option<opentelemetry::Context>>, Json(mut req): Json<CompatGenerateRequest>, ) -> Result<Response, (StatusCode, Json<ErrorResponse>)> { // default return_full_text given the pipeline_tag if req.parameters.return_full_text.is_none() { req.parameters.return_full_text = Some(default_return_full_text) } // switch on stream if req.stream { Ok( generate_stream(infer, compute_type, context, Json(req.into())) .await .into_response(), ) } else { let (headers, Json(generation)) = generate(infer, compute_type, context, Json(req.into())).await?; // wrap generation inside a Vec to match api-inference Ok((headers, Json(vec![generation])).into_response()) } } /// Text Generation Inference endpoint info #[utoipa::path( get, tag = "Text Generation Inference", path = "/info", responses((status = 200, description = "Served model info", body = Info)) )] #[instrument] async fn get_model_info(info: Extension<Info>) -> Json<Info> { Json(info.0) } #[utoipa::path( get, tag = "Text Generation Inference", path = "/v1/models", responses( (status = 200, description = "Served model info", body = ModelInfo), (status = 404, description = "Model not found", body = ErrorResponse), ) )] #[instrument(skip(info))] /// Get model info async fn openai_get_model_info(info: Extension<Info>) -> Json<ModelsInfo> { Json(ModelsInfo { data: vec![ModelInfo { id: info.0.model_id.clone(), object: "model".to_string(), created: 0, // TODO: determine how to get this owned_by: info.0.model_id.clone(), }], ..Default::default() }) } /// Template and tokenize ChatRequest #[utoipa::path( post, tag = "Text Generation Inference", path = "/chat_tokenize", request_body = ChatRequest, responses( (status = 200, description = "Templated and tokenized ChatRequest", body = ChatTokenizeResponse), (status = 404, description = "Failed to tokenize ChatRequest", body = ErrorResponse), ) )] async fn get_chat_tokenize( Extension(infer): Extension<Infer>, Json(chat): Json<ChatRequest>, ) -> Result<(HeaderMap, Json<ChatTokenizeResponse>), (StatusCode, Json<ErrorResponse>)> { metrics::counter!("tgi_request_count").increment(1); let generate_request: GenerateRequest = chat.try_into_generate(&infer)?.0; let input = generate_request.inputs.clone(); let encoding = infer.tokenize(generate_request).await?; let tokens = encoding_to_tokens(&encoding, &input); let resp = ChatTokenizeResponse { tokenize_response: TokenizeResponse(tokens), templated_text: input, }; Ok((HeaderMap::new(), Json(resp))) } #[utoipa::path( get, tag = "Text Generation Inference", path = "/health", responses( (status = 200, description = "Everything is working fine"), (status = 503, description = "Text generation inference is down", body = ErrorResponse, example = json ! ({"error": "unhealthy", "error_type": "healthcheck"})), ) )] #[instrument(skip(infer))] /// Health check method async fn health(infer: Extension<Infer>) -> Result<(), (StatusCode, Json<ErrorResponse>)> { match infer.health().await { true => Ok(()), false => Err(( StatusCode::SERVICE_UNAVAILABLE, Json(ErrorResponse { error: "unhealthy".to_string(), error_type: "healthcheck".to_string(), }), )), } } /// Generate tokens #[utoipa::path( post, tag = "Text Generation Inference", path = "/generate", request_body = GenerateRequest, responses( (status = 200, description = "Generated Text", body = GenerateResponse), (status = 424, description = "Generation Error", body = ErrorResponse, example = json ! ({"error": "Request failed during generation"})), (status = 429, description = "Model is overloaded", body = ErrorResponse, example = json ! ({"error": "Model is overloaded"})), (status = 422, description = "Input validation error", body = ErrorResponse, example = json ! ({"error": "Input validation error"})), (status = 500, description = "Incomplete generation", body = ErrorResponse, example = json ! ({"error": "Incomplete generation"})), ) )] #[instrument( skip_all, fields( parameters = ? req.parameters, total_time, validation_time, queue_time, inference_time, time_per_token, seed, ) )] async fn generate( infer: Extension<Infer>, Extension(ComputeType(compute_type)): Extension<ComputeType>, Extension(context): Extension<Option<opentelemetry::Context>>, Json(req): Json<GenerateRequest>, ) -> Result<(HeaderMap, Json<GenerateResponse>), (StatusCode, Json<ErrorResponse>)> { let span = tracing::Span::current(); if let Some(context) = context { span.set_parent(context); } let (headers, _, response) = generate_internal(infer, ComputeType(compute_type), Json(req), span).await?; Ok((headers, response)) } pub(crate) async fn generate_internal( infer: Extension<Infer>, ComputeType(compute_type): ComputeType, Json(req): Json<GenerateRequest>, span: tracing::Span, ) -> Result<(HeaderMap, u32, Json<GenerateResponse>), (StatusCode, Json<ErrorResponse>)> { let start_time = Instant::now(); metrics::counter!("tgi_request_count").increment(1); // Do not long ultra long inputs, like image payloads. tracing::debug!( "Input: {}", &req.inputs.chars().take(1000).collect::<String>() ); let compute_characters = req.inputs.chars().count(); let mut add_prompt = None; if req.parameters.return_full_text.unwrap_or(false) { add_prompt = Some(req.inputs.clone()); } let details: bool = req.parameters.details || req.parameters.decoder_input_details; // Inference let (response, best_of_responses) = match req.parameters.best_of { Some(best_of) if best_of > 1 => { let (response, best_of_responses) = infer.generate_best_of(req, best_of).await?; (response, Some(best_of_responses)) } _ => (infer.generate(req).await?, None), }; // Token details let input_length = response._input_length; let details = match details { true => { // convert best_of_responses let best_of_sequences = best_of_responses.map(|responses: Vec<InferResponse>| { responses .into_iter() .map(|response: InferResponse| { // Add prompt if return_full_text let mut output_text = response.generated_text.text; if let Some(prompt) = &add_prompt { output_text = prompt.clone() + &output_text; } BestOfSequence { generated_text: output_text, finish_reason: response.generated_text.finish_reason, generated_tokens: response.generated_text.generated_tokens, prefill: response.prefill, tokens: response.tokens, top_tokens: response.top_tokens, seed: response.generated_text.seed, } }) .collect() }); Some(Details { finish_reason: response.generated_text.finish_reason, generated_tokens: response.generated_text.generated_tokens, prefill: response.prefill, tokens: response.tokens, seed: response.generated_text.seed, best_of_sequences, top_tokens: response.top_tokens, }) } false => None, }; // Timings let total_time = start_time.elapsed(); let validation_time = response.queued - start_time; let queue_time = response.start - response.queued; let inference_time = Instant::now() - response.start; let time_per_token = inference_time / response.generated_text.generated_tokens; // Tracing metadata span.record("total_time", format!("{total_time:?}")); span.record("validation_time", format!("{validation_time:?}")); span.record("queue_time", format!("{queue_time:?}")); span.record("inference_time", format!("{inference_time:?}")); span.record("time_per_token", format!("{time_per_token:?}")); span.record("seed", format!("{:?}", response.generated_text.seed)); // Headers let mut headers = HeaderMap::new(); headers.insert("x-compute-type", compute_type.parse().unwrap()); headers.insert( "x-compute-time", total_time.as_secs_f64().to_string().parse().unwrap(), ); headers.insert( "x-compute-characters", compute_characters.to_string().parse().unwrap(), ); headers.insert( "x-total-time", total_time.as_millis().to_string().parse().unwrap(), ); headers.insert( "x-validation-time", validation_time.as_millis().to_string().parse().unwrap(), ); headers.insert( "x-queue-time", queue_time.as_millis().to_string().parse().unwrap(), ); headers.insert( "x-inference-time", inference_time.as_millis().to_string().parse().unwrap(), ); headers.insert( "x-time-per-token", time_per_token.as_millis().to_string().parse().unwrap(), ); headers.insert("x-prompt-tokens", input_length.into()); headers.insert( "x-generated-tokens", response.generated_text.generated_tokens.into(), ); // Metrics metrics::counter!("tgi_request_success").increment(1); metrics::histogram!("tgi_request_duration").record(total_time.as_secs_f64()); metrics::histogram!("tgi_request_validation_duration").record(validation_time.as_secs_f64()); metrics::histogram!("tgi_request_queue_duration").record(queue_time.as_secs_f64()); metrics::histogram!("tgi_request_inference_duration").record(inference_time.as_secs_f64()); metrics::histogram!("tgi_request_mean_time_per_token_duration") .record(time_per_token.as_secs_f64()); metrics::histogram!("tgi_request_generated_tokens") .record(response.generated_text.generated_tokens as f64); // Send response let mut output_text = response.generated_text.text; if let Some(prompt) = add_prompt { output_text = prompt + &output_text; } tracing::debug!("Output: {}", output_text); tracing::info!("Success"); let response = GenerateResponse { generated_text: output_text, details, }; Ok((headers, input_length, Json(response))) } /// Generate a stream of token using Server-Sent Events #[utoipa::path( post, tag = "Text Generation Inference", path = "/generate_stream", request_body = GenerateRequest, responses( (status = 200, description = "Generated Text", body = StreamResponse, content_type = "text/event-stream"), (status = 424, description = "Generation Error", body = ErrorResponse, example = json ! ({"error": "Request failed during generation"}), content_type = "text/event-stream"), (status = 429, description = "Model is overloaded", body = ErrorResponse, example = json ! ({"error": "Model is overloaded"}), content_type = "text/event-stream"), (status = 422, description = "Input validation error", body = ErrorResponse, example = json ! ({"error": "Input validation error"}), content_type = "text/event-stream"), (status = 500, description = "Incomplete generation", body = ErrorResponse, example = json ! ({"error": "Incomplete generation"}), content_type = "text/event-stream"), ) )] #[instrument( skip_all, fields( parameters = ? req.parameters, total_time, validation_time, queue_time, inference_time, time_per_token, seed, ) )] async fn generate_stream( Extension(infer): Extension<Infer>, Extension(compute_type): Extension<ComputeType>, Extension(context): Extension<Option<opentelemetry::Context>>, Json(req): Json<GenerateRequest>, ) -> ( HeaderMap, Sse<impl Stream<Item = Result<Event, Infallible>>>, ) { let span = tracing::Span::current(); if let Some(context) = context { span.set_parent(context); } let (headers, response_stream) = generate_stream_internal(infer, compute_type, Json(req), span).await; let response_stream = async_stream::stream! { let mut response_stream = Box::pin(response_stream); while let Some(raw_event) = response_stream.next().await { yield Ok(raw_event.map_or_else(Event::from, |token| { Event::default() .json_data(token) .unwrap_or_else(|e| InferError::StreamSerializationError(e.to_string()).into()) })); } }; let sse = Sse::new(response_stream).keep_alive(KeepAlive::default()); (headers, sse) } async fn generate_stream_internal( infer: Infer, ComputeType(compute_type): ComputeType, Json(req): Json<GenerateRequest>, span: tracing::Span, ) -> ( HeaderMap, impl Stream<Item = Result<StreamResponse, InferError>>, ) { let start_time = Instant::now(); metrics::counter!("tgi_request_count").increment(1); tracing::debug!("Input: {}", req.inputs); let compute_characters = req.inputs.chars().count(); let mut headers = HeaderMap::new(); headers.insert("x-compute-type", compute_type.parse().unwrap()); headers.insert( "x-compute-characters", compute_characters.to_string().parse().unwrap(), ); headers.insert("X-Accel-Buffering", "no".parse().unwrap()); let stream = async_stream::stream! { // Inference let mut end_reached = false; let mut error = false; let mut add_prompt = None; if req.parameters.return_full_text.unwrap_or(false) { add_prompt = Some(req.inputs.clone()); } let details = req.parameters.details; let best_of = req.parameters.best_of.unwrap_or(1); if best_of != 1 { let err = InferError::from(ValidationError::BestOfStream); metrics::counter!("tgi_request_failure", "err" => "validation").increment(1); tracing::error!("{err}"); yield Err(err); } else if req.parameters.decoder_input_details { let err = InferError::from(ValidationError::PrefillDetailsStream); metrics::counter!("tgi_request_failure", "err" => "validation").increment(1); tracing::error!("{err}"); yield Err(err); } else { match infer.generate_stream(req).instrument(info_span!(parent: &span, "async_stream")).await { // Keep permit as long as generate_stream lives Ok((_permit, input_length, response_stream)) => { let mut index = 0; let mut response_stream = Box::pin(response_stream); // Server-Sent Event stream while let Some(response) = response_stream.next().await { index += 1; match response { Ok(response) => { match response { // Prefill is ignored InferStreamResponse::Prefill(_) => {} // Yield event for every new token InferStreamResponse::Intermediate{ token, top_tokens, } => { tracing::debug!(parent: &span, "Token: {:?}", token); // StreamResponse let stream_token = StreamResponse { index, token, top_tokens, generated_text: None, details: None, }; yield Ok(stream_token); } // Yield event for last token and compute timings InferStreamResponse::End { token, generated_text, start, queued, top_tokens, } => { // Token details let details = match details { true => Some(StreamDetails { finish_reason: generated_text.finish_reason, generated_tokens: generated_text.generated_tokens, seed: generated_text.seed, input_length, }), false => None, }; // Timings let total_time = start_time.elapsed(); let validation_time = queued - start_time; let queue_time = start - queued; let inference_time = Instant::now() - start; let time_per_token = inference_time / generated_text.generated_tokens; // Tracing metadata span.record("total_time", format!("{total_time:?}")); span.record("validation_time", format!("{validation_time:?}")); span.record("queue_time", format!("{queue_time:?}")); span.record("inference_time", format!("{inference_time:?}")); span.record("time_per_token", format!("{time_per_token:?}")); span.record("seed", format!("{:?}", generated_text.seed)); // Metrics metrics::counter!("tgi_request_success").increment(1); metrics::histogram!("tgi_request_duration").record(total_time.as_secs_f64()); metrics::histogram!("tgi_request_validation_duration").record(validation_time.as_secs_f64()); metrics::histogram!("tgi_request_queue_duration").record(queue_time.as_secs_f64()); metrics::histogram!("tgi_request_inference_duration").record(inference_time.as_secs_f64()); metrics::histogram!("tgi_request_mean_time_per_token_duration").record(time_per_token.as_secs_f64()); metrics::histogram!("tgi_request_generated_tokens").record(generated_text.generated_tokens as f64); // StreamResponse end_reached = true; let mut output_text = generated_text.text; if let Some(prompt) = add_prompt { output_text = prompt + &output_text; } tracing::debug!(parent: &span, "Output: {}", output_text); tracing::info!(parent: &span, "Success"); let stream_token = StreamResponse { index, token, top_tokens, generated_text: Some(output_text), details }; yield Ok(stream_token); break; } } } // yield error Err(err) => { error = true; yield Err(err); break; } } } }, // yield error Err(err) => { error = true; yield Err(err); } } // Check if generation reached the end // Skip if we already sent an error if !end_reached && !error { let err = InferError::IncompleteGenerationStream; metrics::counter!("tgi_request_failure", "err" => "incomplete").increment(1); tracing::error!("{err}"); yield Err(err); } } }; (headers, stream) } /// Generate tokens #[utoipa::path( post, tag = "Text Generation Inference", path = "/v1/completions", request_body = CompletionRequest, responses( (status = 200, description = "Generated Chat Completion", content( ("application/json" = CompletionFinal), ("text/event-stream" = Chunk), )), (status = 424, description = "Generation Error", body = ErrorResponse, example = json ! ({"error": "Request failed during generation"})), (status = 429, description = "Model is overloaded", body = ErrorResponse, example = json ! ({"error": "Model is overloaded"})), (status = 422, description = "Input validation error", body = ErrorResponse, example = json ! ({"error": "Input validation error"})), (status = 500, description = "Incomplete generation", body = ErrorResponse, example = json ! ({"error": "Incomplete generation"})), ) )] #[instrument( skip_all, fields( // parameters = ? req.parameters, total_time, validation_time, queue_time, inference_time, time_per_token, seed, ) )] pub(crate) async fn completions( Extension(infer): Extension<Infer>, Extension(compute_type): Extension<ComputeType>, Extension(info): Extension<Info>, Extension(context): Extension<Option<opentelemetry::Context>>, Json(req): Json<CompletionRequest>, ) -> Result<Response, (StatusCode, Json<ErrorResponse>)> { let span = tracing::Span::current(); if let Some(context) = context { span.set_parent(context); } metrics::counter!("tgi_request_count").increment(1); let CompletionRequest { model, max_tokens, seed, stop, stream, temperature, .. } = req; let max_new_tokens = max_tokens; let stop = stop.unwrap_or_default(); // enable greedy only when temperature is 0 let (do_sample, temperature) = match temperature { Some(0.0) => (false, None), other => (true, other), }; // if suffix is present throw an error if req.suffix.is_some() { metrics::counter!("tgi_request_failure", "err" => "validation").increment(1); return Err(( StatusCode::UNPROCESSABLE_ENTITY, Json(ErrorResponse { error: "Suffix is not supported and can be achieved by preprocessing the prompt." .to_string(), error_type: "suffix not supported".to_string(), }), )); } if req.prompt.0.len() > info.max_client_batch_size { metrics::counter!("tgi_request_failure", "err" => "validation").increment(1); return Err(( StatusCode::UNPROCESSABLE_ENTITY, Json(ErrorResponse { error: format!( "Number of prompts exceeds the maximum allowed batch size of {}", info.max_client_batch_size ), error_type: "batch size exceeded".to_string(), }), )); } let generate_requests: Vec<GenerateRequest> = req .prompt .0 .iter() .map(|prompt| GenerateRequest { inputs: prompt.to_string(), add_special_tokens: true, parameters: GenerateParameters { best_of: None, temperature, repetition_penalty: req.repetition_penalty, frequency_penalty: req.frequency_penalty, top_k: None, top_p: req.top_p, typical_p: None, do_sample, max_new_tokens, return_full_text: None, stop: stop.clone(), truncate: None, watermark: false, details: true, decoder_input_details: !stream, seed, top_n_tokens: None, grammar: None, adapter_id: model.as_ref().filter(|m| *m != "tgi").map(String::from), }, }) .collect(); let mut x_compute_type = None; let mut x_compute_characters = 0u32; let mut x_accel_buffering = None; if stream { let mut response_streams = FuturesOrdered::new(); for (index, generate_request) in generate_requests.into_iter().enumerate() { let model_id = info.model_id.clone(); let system_fingerprint = format!("{}-{}", info.version, info.docker_label.unwrap_or("native")); let infer_clone = infer.clone(); let compute_type_clone = compute_type.clone(); let span_clone = span.clone(); // Create a future for each generate_stream_internal call. let generate_future = async move { let (header_tx, header_rx) = oneshot::channel(); let (sse_tx, sse_rx) = tokio::sync::mpsc::unbounded_channel(); tokio::spawn(async move { let (headers, response_stream) = generate_stream_internal( infer_clone.clone(), compute_type_clone.clone(), Json(generate_request), span_clone.clone(), ) .await; let response_stream = async_stream::stream! { let mut response_stream = Box::pin(response_stream); while let Some(stream_token) = response_stream.next().await { match stream_token { Ok(stream_token) => { let event = Event::default(); let current_time = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_else(|_| std::time::Duration::from_secs(0)) .as_secs(); let message = match stream_token.details { Some(details) => { let completion_tokens = details.generated_tokens; let prompt_tokens = details.input_length; let total_tokens = prompt_tokens + completion_tokens; Completion::Final(CompletionFinal { id: String::new(), created: current_time, model: model_id.clone(), system_fingerprint: system_fingerprint.clone(), choices: vec![CompletionComplete { finish_reason: details.finish_reason.to_string(), index: index as u32, logprobs: None, text: stream_token.token.text, }], usage: Usage { prompt_tokens, completion_tokens, total_tokens, }, }) } None => Completion::Chunk(Chunk { id: String::new(), created: current_time, choices: vec![CompletionComplete { finish_reason: String::new(), index: index as u32, logprobs: None, text: stream_token.token.text, }], model: model_id.clone(), system_fingerprint: system_fingerprint.clone(), }), }; let event = event .json_data(message) .unwrap_or_else(|_e| Event::default()); yield Ok(event); } Err(err) => yield Ok(err.into_openai_event()), } } }; // send and dont wait for response let _ = header_tx.send(headers); // pin an emit messages to the sse_tx let mut sse = Box::pin(response_stream); while let Some(event) = sse.next().await { if sse_tx.send(event).is_err() { tracing::error!("Failed to send event. Receiver dropped."); break; } } }); (header_rx, sse_rx) }; response_streams.push_back(generate_future); } let mut all_rxs = vec![]; while let Some((header_rx, sse_rx)) = response_streams.next().await { all_rxs.push(sse_rx); // get the headers from the first response of each stream let headers = header_rx.await.map_err(|e| { tracing::error!("Failed to get headers: {:?}", e); ( StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Failed to get headers".to_string(), error_type: "headers".to_string(), }), ) })?; if x_compute_type.is_none() { x_compute_type = headers .get("x-compute-type") .and_then(|v| v.to_str().ok()) .map(|v| v.to_string()); x_accel_buffering = headers .get("x-accel-buffering") .and_then(|v| v.to_str().ok()) .map(|v| v.to_string()); } x_compute_characters += headers .get("x-compute-characters") .and_then(|v| v.to_str().ok()) .and_then(|v| v.parse().ok()) .unwrap_or(0); } let mut headers = HeaderMap::new(); if let Some(x_compute_type) = x_compute_type { headers.insert("x-compute-type", x_compute_type.parse().unwrap()); } headers.insert("x-compute-characters", x_compute_characters.into()); if let Some(x_accel_buffering) = x_accel_buffering { headers.insert("x-accel-buffering", x_accel_buffering.parse().unwrap()); } // now sink the sse streams into a single stream and remove the ones that are done let stream: AsyncStream<Result<Event, Infallible>, _> = async_stream::stream! { loop { let mut i = 0; while i < all_rxs.len() { let rx = &mut all_rxs[i]; select! { Some(event) = rx.recv() => { yield event; } else => { all_rxs.remove(i); continue; // skip the increment to handle the next element at the same index } } i += 1; // only increment when no element was removed } if all_rxs.is_empty() { break; } } }; let stream = stream.chain(futures::stream::once(async { Ok(Event::default().data("[DONE]")) })); let sse = Sse::new(stream).keep_alive(KeepAlive::default()); Ok((headers, sse).into_response()) } else { let current_time = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_else(|_| std::time::Duration::from_secs(0)) .as_secs(); let responses = FuturesUnordered::new(); for (index, generate_request) in generate_requests.into_iter().enumerate() { let infer_clone = infer.clone(); let compute_type_clone = compute_type.clone(); let span_clone = span.clone(); let response_future = async move { let result = generate_internal( Extension(infer_clone), compute_type_clone, Json(generate_request), span_clone, ) .await; result.map(|(headers, input_length, generation)| { (index, headers, input_length, generation) }) }; responses.push(response_future); } let generate_responses = responses.try_collect::<Vec<_>>().await?; let mut prompt_tokens = 0u32; let mut completion_tokens = 0u32; let mut total_tokens = 0u32; let mut x_compute_time = 0u32; let mut x_total_time = 0u32; let mut x_validation_time = 0u32; let mut x_queue_time = 0u32; let mut x_inference_time = 0u32; let mut x_time_per_token = 0u32; let mut x_prompt_tokens = 0u32; let mut x_generated_tokens = 0u32; let choices = generate_responses .into_iter() .map(|(index, headers, input_length, Json(generation))| { let details = generation.details.ok_or(( // this should never happen but handle if details are missing unexpectedly StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "No details in generation".to_string(), error_type: "no details".to_string(), }), ))?; if x_compute_type.is_none() { x_compute_type = headers .get("x-compute-type") .and_then(|v| v.to_str().ok()) .map(|v| v.to_string()); } // accumulate headers and usage from each response x_compute_time += headers .get("x-compute-time") .and_then(|v| v.to_str().ok()?.parse().ok()) .unwrap_or(0); x_compute_characters += headers .get("x-compute-characters") .and_then(|v| v.to_str().ok()?.parse().ok()) .unwrap_or(0); x_total_time += headers .get("x-total-time") .and_then(|v| v.to_str().ok()?.parse().ok()) .unwrap_or(0); x_validation_time += headers .get("x-validation-time") .and_then(|v| v.to_str().ok()?.parse().ok()) .unwrap_or(0); x_queue_time += headers .get("x-queue-time") .and_then(|v| v.to_str().ok()?.parse().ok()) .unwrap_or(0); x_inference_time += headers .get("x-inference-time") .and_then(|v| v.to_str().ok()?.parse().ok()) .unwrap_or(0); x_time_per_token += headers .get("x-time-per-token") .and_then(|v| v.to_str().ok()?.parse().ok()) .unwrap_or(0); x_prompt_tokens += headers .get("x-prompt-tokens") .and_then(|v| v.to_str().ok()?.parse().ok()) .unwrap_or(0); x_generated_tokens += headers .get("x-generated-tokens") .and_then(|v| v.to_str().ok()?.parse().ok()) .unwrap_or(0); prompt_tokens += input_length; completion_tokens += details.generated_tokens; total_tokens += input_length + details.generated_tokens; Ok(CompletionComplete { finish_reason: details.finish_reason.format(true), index: index as u32, logprobs: None, text: generation.generated_text, }) }) .collect::<Result<Vec<_>, _>>() .map_err(|(status, Json(err))| (status, Json(err)))?; let response = Completion::Final(CompletionFinal { id: "".to_string(), created: current_time, model: info.model_id.clone(), system_fingerprint: format!( "{}-{}", info.version, info.docker_label.unwrap_or("native") ), choices, usage: Usage { prompt_tokens, completion_tokens, total_tokens, }, }); // headers similar to `generate` but aggregated let mut headers = HeaderMap::new(); if let Some(x_compute_type) = x_compute_type { headers.insert("x-compute-type", x_compute_type.parse().unwrap()); } headers.insert("x-compute-characters", x_compute_characters.into()); headers.insert("x-total-time", x_total_time.into()); headers.insert("x-validation-time", x_validation_time.into()); headers.insert("x-queue-time", x_queue_time.into()); headers.insert("x-inference-time", x_inference_time.into()); headers.insert("x-time-per-token", x_time_per_token.into()); headers.insert("x-prompt-tokens", x_prompt_tokens.into()); headers.insert("x-generated-tokens", x_generated_tokens.into()); if let Some(x_accel_buffering) = x_accel_buffering { headers.insert("x-accel-buffering", x_accel_buffering.parse().unwrap()); } Ok((headers, Json(response)).into_response()) } } /// Generate tokens #[utoipa::path( post, tag = "Text Generation Inference", path = "/v1/chat/completions", request_body = ChatRequest, responses( (status = 200, description = "Generated Chat Completion", content( ("application/json" = ChatCompletion), ("text/event-stream" = ChatCompletionChunk), )), (status = 424, description = "Generation Error", body = ErrorResponse, example = json ! ({"error": "Request failed during generation"})), (status = 429, description = "Model is overloaded", body = ErrorResponse, example = json ! ({"error": "Model is overloaded"})), (status = 422, description = "Input validation error", body = ErrorResponse, example = json ! ({"error": "Input validation error"})), (status = 500, description = "Incomplete generation", body = ErrorResponse, example = json ! ({"error": "Incomplete generation"})), ) )] #[instrument( skip_all, fields( parameters, total_time, validation_time, queue_time, inference_time, time_per_token, seed, ) )] pub(crate) async fn chat_completions( Extension(infer): Extension<Infer>, Extension(compute_type): Extension<ComputeType>, Extension(info): Extension<Info>, Extension(context): Extension<Option<opentelemetry::Context>>, Json(mut chat): Json<ChatRequest>, ) -> Result<Response, (StatusCode, Json<ErrorResponse>)> { let span = tracing::Span::current(); if let Some(context) = context { span.set_parent(context); } metrics::counter!("tgi_request_count").increment(1); let ChatRequest { model, stream, stream_options, logprobs, .. } = chat.clone(); tracing::debug!("Got chat_template {:?}", infer.chat_template); let id = chat.next_tool_call_id(); let (generate_request, using_tools): (GenerateRequest, bool) = chat.clone().try_into_generate(&infer)?; span.record("parameters", format!("{:?}", generate_request.parameters)); let logprobs = logprobs.unwrap_or_default(); // extract model id from request if specified let model_id = match model.as_deref() { Some("tgi") | None => info.model_id.clone(), Some(m_id) => m_id.to_string(), }; let system_fingerprint = format!("{}-{}", info.version, info.docker_label.unwrap_or("native")); // switch on stream if stream { let (headers, response_stream) = generate_stream_internal( infer.clone(), compute_type.clone(), Json(generate_request), span.clone(), ) .await; let response_stream = async_stream::stream! { let mut response_stream = Box::pin(response_stream); let mut state = ChatState::new(using_tools, stream_options.clone(), system_fingerprint.clone(), model_id.clone(), logprobs, id.clone()); while let Some(result) = response_stream.next().await { match result{ Ok(stream_token) => { let events = state.push(stream_token); match events{ ChatEvent::NoTool => { chat.tools = None; chat.response_format = None; let (generate_request, using_tools): (GenerateRequest, bool) = chat.clone().try_into_generate(&infer).unwrap(); assert!(!using_tools); let (_headers, response_stream2) = generate_stream_internal(infer.clone(), compute_type.clone(), Json(generate_request), span.clone()).await; state = ChatState::new(using_tools, stream_options.clone(), system_fingerprint.clone(), model_id.clone(), logprobs, id.clone()); response_stream = Box::pin(response_stream2); } ChatEvent::Events(events) => { for chat_complete in events{ yield Ok(Event::default().json_data(chat_complete).unwrap_or_else(|e| { tracing::error!("Failed to serialize ChatCompletionChunk: {:?}", e); Event::default() })); } } } } Err(err) => yield Ok(err.into_openai_event()) } } yield Ok::<Event, Infallible>(Event::default().data("[DONE]")); }; let sse = Sse::new(response_stream).keep_alive(KeepAlive::default()); Ok((headers, sse).into_response()) } else { let (mut headers, mut input_length, Json(generation)) = generate_internal( Extension(infer.clone()), compute_type.clone(), Json(generate_request), span.clone(), ) .await?; let current_time = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_else(|_| std::time::Duration::from_secs(0)) .as_secs(); let (tool_calls, output) = if using_tools { match crate::chat::parse_output(&generation.generated_text)? { ChatChoice::NoTool => { chat.tools = None; chat.response_format = None; let (generate_request, using_tools): (GenerateRequest, bool) = chat.clone().try_into_generate(&infer)?; assert!(!using_tools); let (headers_final, input_length_final, Json(generation)) = generate_internal( Extension(infer), compute_type, Json(generate_request), span, ) .await?; headers = headers_final; input_length = input_length_final; (None, Some(generation.generated_text)) } ChatChoice::ToolCalls(tool_calls) => (Some(tool_calls), None), } } else { (None, Some(generation.generated_text)) }; // build the complete response object with the full text let response = CompletionType::ChatCompletion(ChatCompletion::new( model_id, system_fingerprint, output, current_time, generation.details.unwrap(), logprobs, tool_calls, input_length, )); // wrap generation inside a Vec to match api-inference Ok((headers, Json(response)).into_response()) } } /// Tokenize inputs #[utoipa::path( post, tag = "Text Generation Inference", path = "/tokenize", request_body = GenerateRequest, responses( (status = 200, description = "Tokenized ids", body = TokenizeResponse), (status = 404, description = "No tokenizer found", body = ErrorResponse, example = json ! ({"error": "No fast tokenizer available"})), ) )] #[instrument(skip_all)] async fn tokenize( Extension(infer): Extension<Infer>, Json(req): Json<GenerateRequest>, ) -> Result<Json<TokenizeResponse>, (StatusCode, Json<ErrorResponse>)> { let input = req.inputs.clone(); let encoding = infer.tokenize(req).await?; let tokens = encoding_to_tokens(&encoding, &input); Ok(Json(TokenizeResponse(tokens))) } /// Prometheus metrics scrape endpoint #[utoipa::path( get, tag = "Text Generation Inference", path = "/metrics", responses((status = 200, description = "Prometheus Metrics", body = String)) )] async fn metrics(prom_handle: Extension<PrometheusHandle>) -> String { prom_handle.render() } #[derive(Clone, Debug)] pub(crate) struct ComputeType(String); // OpenAPI documentation #[derive(OpenApi)] #[openapi( paths( health, get_model_info, compat_generate, generate, generate_stream, chat_completions, completions, tokenize, metrics, openai_get_model_info, sagemaker_compatibility, get_chat_tokenize, ), components( schemas( Info, CompatGenerateRequest, SagemakerRequest, GenerateRequest, GrammarType, JsonSchemaConfig, ChatRequest, Message, MessageContent, MessageChunk, Url, FunctionName, OutputMessage, TextMessage, ToolCallMessage, ToolCallDelta, ChatCompletionComplete, ChatCompletionChoice, ChatCompletionDelta, ChatCompletionChunk, ChatCompletionLogprob, ChatCompletionLogprobs, ChatCompletionTopLogprob, ChatCompletion, CompletionRequest, CompletionComplete, SagemakerResponse, SagemakerStreamResponse, Chunk, Completion, CompletionFinal, Prompt, GenerateParameters, PrefillToken, Token, GenerateResponse, TokenizeResponse, SimpleToken, BestOfSequence, Details, FinishReason, StreamResponse, StreamDetails, ErrorResponse, GrammarType, Usage, StreamOptions, DeltaToolCall, Tool, ToolCall, Function, FunctionDefinition, ToolChoice, ModelInfo, ChatTokenizeResponse, MessageBody, ) ), tags( (name = "Text Generation Inference", description = "Hugging Face Text Generation Inference API") ), info( title = "Text Generation Inference", license( name = "Apache 2.0", url = "https://www.apache.org/licenses/LICENSE-2.0" ) ) )] pub struct ApiDoc; pub fn schema() -> ApiDoc { ApiDoc } pub fn py_resolve_tokenizer( py: pyo3::Python, tokenizer_name: &str, revision: Option<&str>, trust_remote_code: bool, ) -> pyo3::PyResult<()> { let transformers = py.import_bound("transformers")?; let auto = transformers.getattr("AutoTokenizer")?; let from_pretrained = auto.getattr("from_pretrained")?; let args = (tokenizer_name,); let kwargs = if let Some(rev) = &revision { [ ("revision", rev.to_string().into_py(py)), ("trust_remote_code", trust_remote_code.into_py(py)), ] .into_py_dict_bound(py) } else { [("trust_remote_code", trust_remote_code.into_py(py))].into_py_dict_bound(py) }; let tokenizer = from_pretrained.call(args, Some(&kwargs))?; let save = tokenizer.getattr("save_pretrained")?; let args = ("out".to_string(),); save.call1(args)?; Ok(()) } pub fn legacy_tokenizer_handle(config_filename: Option<&PathBuf>) -> Option<()> { // XXX Legacy case for FasterDecoding/medusa-vicuna-7b-v1.3 // and state-spaces/mamba-130m tracing::warn!("Odd tokenizer detected, falling back on legacy tokenization"); #[derive(serde::Deserialize)] struct FallbackConfig { base_model_name_or_path: Option<String>, model_type: Option<String>, ssm_config: Option<serde_json::Value>, } config_filename.and_then(|filename| { std::fs::read_to_string(filename) .ok() .as_ref() .and_then(|c| { let config: Result<FallbackConfig, _> = serde_json::from_str(c); if let Ok(config) = config { if config.model_type.is_none() { if let Some(base) = config.base_model_name_or_path { pyo3::Python::with_gil(|py| -> PyResult<()> { py_resolve_tokenizer(py, &base, Some("main"), false) }) .ok()?; } } if config.ssm_config.is_some() { // XXX Legacy mamba pyo3::Python::with_gil(|py| -> PyResult<()> { py_resolve_tokenizer(py, "EleutherAI/gpt-neox-20b", Some("main"), false) }) .ok()?; } } Some(()) }) }) } /// Serving method #[allow(clippy::too_many_arguments)] pub async fn run( backend: impl Backend + Send + Sync + 'static, max_concurrent_requests: usize, max_best_of: usize, max_stop_sequences: usize, max_top_n_tokens: u32, max_input_tokens: usize, max_total_tokens: usize, validation_workers: usize, api_key: Option<String>, tokenizer_name: String, tokenizer_config_path: Option<String>, revision: Option<String>, trust_remote_code: bool, hostname: String, port: u16, cors_allow_origin: Option<Vec<String>>, ngrok: bool, _ngrok_authtoken: Option<String>, _ngrok_edge: Option<String>, disable_grammar_support: bool, max_client_batch_size: usize, usage_stats_level: usage_stats::UsageStatsLevel, payload_limit: usize, prometheus_port: u16, ) -> Result<(), WebServerError> { // CORS allowed origins // map to go inside the option and then map to parse from String to HeaderValue // Finally, convert to AllowOrigin let allow_origin: Option<AllowOrigin> = cors_allow_origin.map(|cors_allow_origin| { AllowOrigin::list( cors_allow_origin .iter() .map(|origin| origin.parse::<HeaderValue>().unwrap()), ) }); // Parse Huggingface hub token let authorization_token = std::env::var("HF_TOKEN") .or_else(|_| std::env::var("HUGGING_FACE_HUB_TOKEN")) .ok(); // Tokenizer instance // This will only be used to validate payloads let local_path = Path::new(&tokenizer_name); // Shared API builder initialization let api_builder = || { let mut builder = ApiBuilder::from_env().with_progress(false); if let Some(token) = authorization_token { builder = builder.with_token(Some(token)); } if let Ok(cache_dir) = std::env::var("HUGGINGFACE_HUB_CACHE") { builder = builder.with_cache_dir(cache_dir.into()); } if let Ok(origin) = std::env::var("HF_HUB_USER_AGENT_ORIGIN") { builder = builder.with_user_agent("origin", origin.as_str()); } builder }; // Decide if we need to use the API based on the revision and local path let use_api = revision.is_some() || !local_path.exists() || !local_path.is_dir(); // Initialize API if needed #[derive(Clone)] enum Type { Api(Api), Cache(Cache), None, } let api = if use_api { if std::env::var("HF_HUB_OFFLINE") == Ok("1".to_string()) { let cache = std::env::var("HUGGINGFACE_HUB_CACHE") .map_err(|_| ()) .map(|cache_dir| Cache::new(cache_dir.into())) .unwrap_or_else(|_| Cache::from_env()); tracing::warn!("Offline mode active using cache defaults"); Type::Cache(cache) } else { tracing::info!("Using the Hugging Face API"); match api_builder().build() { Ok(api) => Type::Api(api), Err(_) => { tracing::warn!("Unable to build the Hugging Face API"); Type::None } } } } else { Type::None }; // Load tokenizer and model info let ( config_filename, tokenizer_config_filename, preprocessor_config_filename, processor_config_filename, chat_template_filename, model_info, ) = match api { Type::None => ( Some(local_path.join("config.json")), Some(local_path.join("tokenizer_config.json")), Some(local_path.join("preprocessor_config.json")), Some(local_path.join("processor_config.json")), Some(local_path.join("chat_template.json")), None, ), Type::Api(api) => { let api_repo = api.repo(Repo::with_revision( tokenizer_name.to_string(), RepoType::Model, revision.clone().unwrap_or_else(|| "main".to_string()), )); let config_filename = api_repo.get("config.json").await.ok(); let tokenizer_config_filename = api_repo.get("tokenizer_config.json").await.ok(); let preprocessor_config_filename = api_repo.get("preprocessor_config.json").await.ok(); let processor_config_filename = api_repo.get("processor_config.json").await.ok(); let chat_template_filename = api_repo.get("chat_template.json").await.ok(); let model_info = if let Some(model_info) = get_hub_model_info(&api_repo).await { Some(model_info) } else { tracing::warn!("Could not retrieve model info from the Hugging Face hub."); None }; ( config_filename, tokenizer_config_filename, preprocessor_config_filename, processor_config_filename, chat_template_filename, model_info, ) } Type::Cache(cache) => { tracing::info!("Cache {cache:?}"); let repo = cache.repo(Repo::with_revision( tokenizer_name.to_string(), RepoType::Model, revision.clone().unwrap_or_else(|| "main".to_string()), )); ( repo.get("config.json"), repo.get("tokenizer_config.json"), repo.get("preprocessor_config.json"), repo.get("processor_config.json"), repo.get("chat_template.json"), None, ) } }; // if chat_template_filename is present, load the chat template let chat_template: Option<crate::ChatTemplateVersions> = chat_template_filename .and_then(|f| std::fs::read_to_string(f).ok()) .and_then(|c| { let res = serde_json::from_str::<crate::ChatTemplateStandalone>(&c); if let Err(e) = &res { tracing::warn!("Could not parse chat template {e:?}"); } res.ok().map(|t| t.chat_template) }); // Read the JSON contents of the file as an instance of 'HubTokenizerConfig'. tracing::warn!("Tokenizer_config {tokenizer_config_path:?} - {tokenizer_config_filename:?}"); let tokenizer_config: Option<HubTokenizerConfig> = if let Some(filename) = tokenizer_config_path { HubTokenizerConfig::from_file(filename) } else { tokenizer_config_filename.and_then(HubTokenizerConfig::from_file) }; let mut tokenizer_config = tokenizer_config.unwrap_or_else(|| { tracing::warn!("Could not find tokenizer config locally and no API specified"); HubTokenizerConfig::default() }); if chat_template.is_some() { tracing::info!("Using chat template from chat_template.json"); tokenizer_config.chat_template = chat_template; } let tokenizer: Result<Tokenizer, WebServerError> = { use pyo3::prelude::*; Python::with_gil(|py| -> PyResult<()> { py_resolve_tokenizer(py, &tokenizer_name, revision.as_deref(), trust_remote_code)?; Ok(()) }) .inspect_err(|err| { tracing::error!("Failed to import python tokenizer {err}"); }) .or_else(|err| { let out = legacy_tokenizer_handle(config_filename.as_ref()); out.ok_or(err) }) .map_err(|_| WebServerError::Tokenizer("Unable to load tokenizer.".to_string()))?; let filename = "out/tokenizer.json"; if let Ok(tok) = tokenizers::Tokenizer::from_file(filename) { Ok(Tokenizer::Rust(tok)) } else { Ok(Tokenizer::Python { tokenizer_name: tokenizer_name.clone(), revision: revision.clone(), trust_remote_code, }) } }; let config: Option<Config> = config_filename.and_then(|filename| { std::fs::read_to_string(filename) .ok() .as_ref() .and_then(|c| { let config: Result<Config, _> = serde_json::from_str(c); if let Err(err) = &config { tracing::warn!("Could not parse config {err:?}"); } config.ok() }) }); let model_info = model_info.unwrap_or_else(|| HubModelInfo { model_id: tokenizer_name.to_string(), sha: None, pipeline_tag: None, }); let processor_config = processor_config_filename .and_then(HubProcessorConfig::from_file) .unwrap_or_default(); let preprocessor_config: Option<HubPreprocessorConfig> = preprocessor_config_filename.and_then(HubPreprocessorConfig::from_file); tracing::info!("Using config {config:?}"); // Only send usage stats when TGI is run in container and the function returns Some let is_container = matches!(usage_stats::is_container(), Ok(true)); // retrieve the huggingface_hub user agent origin if set, and add the origin to telemetry let origin = std::env::var("HF_HUB_USER_AGENT_ORIGIN").ok(); let user_agent = match (usage_stats_level, is_container) { (usage_stats::UsageStatsLevel::On | usage_stats::UsageStatsLevel::NoStack, true) => { let reduced_args = usage_stats::Args::new( config.clone(), tokenizer_config.tokenizer_class.clone(), max_concurrent_requests, max_best_of, max_stop_sequences, max_top_n_tokens, max_input_tokens, max_total_tokens, // waiting_served_ratio, // max_batch_prefill_tokens, // max_batch_total_tokens, // max_waiting_tokens, // max_batch_size, revision.clone(), validation_workers, disable_grammar_support, max_client_batch_size, usage_stats_level, backend.name(), origin, ); Some(usage_stats::UserAgent::new(reduced_args)) } _ => None, }; let stop_usage_thread = Arc::new(AtomicBool::new(false)); let stop_usage_thread_clone = stop_usage_thread.clone(); if let Some(ua) = user_agent.clone() { let start_event = usage_stats::UsageStatsEvent::new(ua.clone(), usage_stats::EventType::Start, None); tokio::spawn(async move { // send start event start_event.send().await; let mut last_report = Instant::now(); while !stop_usage_thread_clone.load(Ordering::Relaxed) { if last_report.elapsed() > Duration::from_secs(900) { let report_event = usage_stats::UsageStatsEvent::new( ua.clone(), usage_stats::EventType::Ping, None, ); report_event.send().await; last_report = Instant::now(); } tokio::time::sleep(Duration::from_secs(1)).await; } }); }; let compat_return_full_text = match &model_info.pipeline_tag { None => { tracing::warn!("no pipeline tag found for model {tokenizer_name}"); true } Some(pipeline_tag) => pipeline_tag.as_str() == "text-generation", }; let result = start( backend, max_concurrent_requests, max_best_of, max_stop_sequences, max_top_n_tokens, max_input_tokens, max_total_tokens, validation_workers, api_key, config, (tokenizer?, tokenizer_config), (preprocessor_config, processor_config), hostname, port, ngrok, _ngrok_authtoken, _ngrok_edge, disable_grammar_support, max_client_batch_size, model_info, compat_return_full_text, allow_origin, payload_limit, prometheus_port, ) .await; if let Some(ua) = user_agent { stop_usage_thread.store(true, Ordering::Relaxed); match result { Ok(_) => { let stop_event = usage_stats::UsageStatsEvent::new( ua.clone(), usage_stats::EventType::Stop, None, ); stop_event.send().await; Ok(()) } Err(e) => { let description = match usage_stats_level { usage_stats::UsageStatsLevel::On => Some(e.to_string()), usage_stats::UsageStatsLevel::NoStack => Some("unknow_error".to_string()), _ => None, }; let event = usage_stats::UsageStatsEvent::new( ua.clone(), usage_stats::EventType::Error, description, ); event.send().await; Err(e) } } } else { result } } #[allow(clippy::too_many_arguments)] async fn start( backend: impl Backend + Send + Sync + 'static, max_concurrent_requests: usize, max_best_of: usize, max_stop_sequences: usize, max_top_n_tokens: u32, max_input_tokens: usize, max_total_tokens: usize, validation_workers: usize, api_key: Option<String>, config: Option<Config>, (tokenizer, tokenizer_config): (Tokenizer, HubTokenizerConfig), (preprocessor_config, processor_config): (Option<HubPreprocessorConfig>, HubProcessorConfig), hostname: String, port: u16, ngrok: bool, _ngrok_authtoken: Option<String>, _ngrok_edge: Option<String>, disable_grammar_support: bool, max_client_batch_size: usize, model_info: HubModelInfo, compat_return_full_text: bool, allow_origin: Option<AllowOrigin>, payload_limit: usize, prometheus_port: u16, ) -> Result<(), WebServerError> { // Determine the server port based on the feature and environment variable. let port = if cfg!(feature = "google") { std::env::var("AIP_HTTP_PORT") .map(|aip_http_port| aip_http_port.parse::<u16>().unwrap_or(port)) .unwrap_or(port) } else { port }; let addr = match hostname.parse() { Ok(ip) => SocketAddr::new(ip, port), Err(_) => { tracing::warn!("Invalid hostname, defaulting to 0.0.0.0"); SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), port) } }; // Create state let validation = Validation::new( validation_workers, tokenizer, config, preprocessor_config, max_best_of, max_stop_sequences, max_top_n_tokens, max_input_tokens, max_total_tokens, disable_grammar_support, ); let infer = Infer::new( backend, validation, max_concurrent_requests, tokenizer_config, processor_config, ); // Duration buckets let duration_matcher = Matcher::Suffix(String::from("duration")); let n_duration_buckets = 35; let mut duration_buckets = Vec::with_capacity(n_duration_buckets); // Minimum duration in seconds let mut value = 0.0001; for _ in 0..n_duration_buckets { // geometric sequence value *= 1.5; duration_buckets.push(value); } // Input Length buckets let input_length_matcher = Matcher::Full(String::from("tgi_request_input_length")); let input_length_buckets: Vec<f64> = (0..100) .map(|x| (max_input_tokens as f64 / 100.0) * (x + 1) as f64) .collect(); // Generated tokens buckets let generated_tokens_matcher = Matcher::Full(String::from("tgi_request_generated_tokens")); let generated_tokens_buckets: Vec<f64> = (0..100) .map(|x| (max_total_tokens as f64 / 100.0) * (x + 1) as f64) .collect(); // Input Length buckets let max_new_tokens_matcher = Matcher::Full(String::from("tgi_request_max_new_tokens")); let max_new_tokens_buckets: Vec<f64> = (0..100) .map(|x| (max_total_tokens as f64 / 100.0) * (x + 1) as f64) .collect(); // Batch size buckets let batch_size_matcher = Matcher::Full(String::from("tgi_batch_next_size")); let batch_size_buckets: Vec<f64> = (0..1024).map(|x| (x + 1) as f64).collect(); // Speculated tokens buckets // let skipped_matcher = Matcher::Full(String::from("tgi_request_skipped_tokens")); // let skipped_buckets: Vec<f64> = (0..shard_info.speculate + 1).map(|x| x as f64).collect(); let mut p_addr = addr; p_addr.set_port(prometheus_port); // Prometheus handler let builder = PrometheusBuilder::new() .with_http_listener(p_addr) .set_buckets_for_metric(duration_matcher, &duration_buckets) .unwrap() .set_buckets_for_metric(input_length_matcher, &input_length_buckets) .unwrap() .set_buckets_for_metric(generated_tokens_matcher, &generated_tokens_buckets) .unwrap() .set_buckets_for_metric(max_new_tokens_matcher, &max_new_tokens_buckets) .unwrap() .set_buckets_for_metric(batch_size_matcher, &batch_size_buckets) .unwrap(); // .set_buckets_for_metric(skipped_matcher, &skipped_buckets) // .unwrap(); // See: https://github.com/metrics-rs/metrics/issues/467#issuecomment-2022755151 let (recorder, _) = builder .build() .expect("failed to build prometheus recorder"); let prom_handle = recorder.handle(); metrics::set_global_recorder(recorder).expect("Failed to set global recorder"); // Metrics descriptions metrics::describe_counter!("tgi_request_success", "Number of successful requests"); metrics::describe_histogram!( "tgi_request_duration", metrics::Unit::Seconds, "Request duration" ); metrics::describe_histogram!( "tgi_request_validation_duration", metrics::Unit::Seconds, "Request validation duration" ); metrics::describe_histogram!( "tgi_request_queue_duration", metrics::Unit::Seconds, "Request queue duration" ); metrics::describe_histogram!( "tgi_request_inference_duration", metrics::Unit::Seconds, "Request inference duration" ); metrics::describe_histogram!( "tgi_request_mean_time_per_token_duration", metrics::Unit::Seconds, "Mean time per token per request" ); metrics::describe_histogram!( "tgi_request_generated_tokens", metrics::Unit::Count, "Generated tokens per request" ); metrics::describe_counter!( "tgi_batch_inference_count", metrics::Unit::Count, "Inference calls per method (prefill or decode)" ); metrics::describe_counter!( "tgi_request_count", metrics::Unit::Count, "Total number of requests" ); metrics::describe_counter!( "tgi_batch_inference_success", metrics::Unit::Count, "Number of successful inference calls per method (prefill or decode)" ); metrics::describe_gauge!( "tgi_batch_current_size", metrics::Unit::Count, "Current batch size" ); metrics::describe_gauge!("tgi_queue_size", metrics::Unit::Count, "Current queue size"); metrics::describe_gauge!( "tgi_batch_current_max_tokens", metrics::Unit::Count, "Maximum tokens for the current batch" ); metrics::describe_gauge!( "tgi_batch_total_tokens", metrics::Unit::Count, "Maximum amount of tokens in total." ); metrics::describe_histogram!( "tgi_request_max_new_tokens", metrics::Unit::Count, "Maximum new tokens per request" ); metrics::describe_histogram!( "tgi_batch_inference_duration", metrics::Unit::Seconds, "Batch inference duration" ); metrics::describe_histogram!( "tgi_batch_forward_duration", metrics::Unit::Seconds, "Batch forward duration per method (prefill or decode)" ); metrics::describe_histogram!( "tgi_request_skipped_tokens", metrics::Unit::Count, "Speculated tokens per request" ); metrics::describe_histogram!( "tgi_batch_filter_duration", metrics::Unit::Seconds, "Time spent filtering batches and sending generated tokens per method (prefill or decode)" ); metrics::describe_histogram!( "tgi_request_queue_duration", metrics::Unit::Seconds, "Time spent in the queue per request" ); metrics::describe_histogram!( "tgi_request_validation_duration", metrics::Unit::Seconds, "Time spent validating the request" ); metrics::describe_histogram!( "tgi_request_duration", metrics::Unit::Seconds, "Total time spent processing the request" ); metrics::describe_histogram!( "tgi_batch_decode_duration", metrics::Unit::Seconds, "Time spent decoding a batch per method (prefill or decode)" ); metrics::describe_histogram!( "tgi_request_input_length", metrics::Unit::Count, "Input token length per request" ); metrics::describe_histogram!( "tgi_batch_next_size", metrics::Unit::Count, "Batch size of the next batch" ); // CORS layer let allow_origin = allow_origin.unwrap_or(AllowOrigin::any()); let cors_layer = CorsLayer::new() .allow_methods([Method::GET, Method::POST]) .allow_headers([http::header::CONTENT_TYPE]) .allow_origin(allow_origin); // Endpoint info let info = Info { model_id: model_info.model_id, model_sha: model_info.sha, // model_dtype: shard_info.dtype, // model_device_type: shard_info.device_type, model_pipeline_tag: model_info.pipeline_tag, max_concurrent_requests, max_best_of, max_stop_sequences, max_input_tokens, max_total_tokens, // waiting_served_ratio, // max_batch_total_tokens, // max_waiting_tokens, // max_batch_size, validation_workers, max_client_batch_size, router: env!("CARGO_PKG_NAME"), version: env!("CARGO_PKG_VERSION"), sha: option_env!("VERGEN_GIT_SHA"), docker_label: option_env!("DOCKER_LABEL"), }; #[allow(unused_mut)] // mut is needed for conditional compilation let mut doc = ApiDoc::openapi(); #[cfg(feature = "google")] { use crate::vertex::__path_vertex_compatibility; use crate::vertex::{VertexInstance, VertexRequest, VertexResponse}; #[derive(OpenApi)] #[openapi( paths(vertex_compatibility), components(schemas(VertexInstance, VertexRequest, VertexResponse)) )] struct VertexApiDoc; doc.merge(VertexApiDoc::openapi()); } #[cfg(feature = "kserve")] { use crate::kserve::{ InferenceOutput, InferenceRequest, LiveResponse, MetadataServerResponse, OutputChunk, ReadyResponse, }; use crate::kserve::{ __path_kerve_server_metadata, __path_kserve_health_live, __path_kserve_health_ready, __path_kserve_model_infer, __path_kserve_model_metadata, __path_kserve_model_metadata_ready, }; #[derive(OpenApi)] #[openapi( paths( kserve_health_live, kserve_health_ready, kerve_server_metadata, kserve_model_metadata, kserve_model_metadata_ready, kserve_model_infer, ), components(schemas( InferenceOutput, InferenceRequest, LiveResponse, MetadataServerResponse, OutputChunk, ReadyResponse, )) )] struct KServeApiDoc; doc.merge(KServeApiDoc::openapi()); } // Configure Swagger UI let swagger_ui = SwaggerUi::new("/docs").url("/api-doc/openapi.json", doc); // Define base and health routes let mut base_routes = Router::new() .route("/", post(compat_generate)) .route("/generate", post(generate)) .route("/generate_stream", post(generate_stream)) .route("/v1/chat/completions", post(chat_completions)) .route("/v1/completions", post(completions)) .route("/vertex", post(vertex_compatibility)) .route("/invocations", post(sagemaker_compatibility)) .route("/tokenize", post(tokenize)); if let Some(api_key) = api_key { let mut prefix = "Bearer ".to_string(); prefix.push_str(&api_key); // Leak to allow FnMut let api_key: &'static str = prefix.leak(); let auth = move |headers: HeaderMap, request: axum::extract::Request, next: axum::middleware::Next| async move { match headers.get(AUTHORIZATION) { Some(token) => match token.to_str() { Ok(token_str) if token_str.to_lowercase() == api_key.to_lowercase() => { let response = next.run(request).await; Ok(response) } _ => Err(StatusCode::UNAUTHORIZED), }, None => Err(StatusCode::UNAUTHORIZED), } }; base_routes = base_routes.layer(axum::middleware::from_fn(auth)) } let info_routes = Router::new() .route("/", get(health)) .route("/chat_tokenize", post(get_chat_tokenize)) .route("/info", get(get_model_info)) .route("/health", get(health)) .route("/ping", get(health)) .route("/metrics", get(metrics)) .route("/v1/models", get(openai_get_model_info)); let compute_type = ComputeType(std::env::var("COMPUTE_TYPE").unwrap_or("gpu+optimized".to_string())); // Combine routes and layers let mut app = Router::new() .merge(swagger_ui) .merge(base_routes) .merge(info_routes); #[cfg(feature = "google")] { tracing::info!("Built with `google` feature"); tracing::info!( "Environment variables `AIP_PREDICT_ROUTE` and `AIP_HEALTH_ROUTE` will be respected." ); if let Ok(env_predict_route) = std::env::var("AIP_PREDICT_ROUTE") { app = app.route(&env_predict_route, post(vertex_compatibility)); } if let Ok(env_health_route) = std::env::var("AIP_HEALTH_ROUTE") { app = app.route(&env_health_route, get(health)); } } #[cfg(feature = "kserve")] { tracing::info!("Built with `kserve` feature"); app = app .route( "/v2/models/:model_name/versions/:model_version/infer", post(kserve_model_infer), ) .route( "/v2/models/:model_name/versions/:model_version", get(kserve_model_metadata), ) .route("/v2/health/ready", get(kserve_health_ready)) .route("/v2/health/live", get(kserve_health_live)) .route("/v2", get(kerve_server_metadata)) .route( "/v2/models/:model_name/versions/:model_version/ready", get(kserve_model_metadata_ready), ); } // add layers after routes app = app .layer(Extension(info)) .layer(Extension(compat_return_full_text)) .layer(Extension(infer)) .layer(Extension(compute_type)) .layer(Extension(prom_handle.clone())) .layer(OtelAxumLayer::default()) .layer(DefaultBodyLimit::max(payload_limit)) .layer(axum::middleware::from_fn(trace_context_middleware)) .layer(cors_layer); tracing::info!("Connected"); if ngrok { #[cfg(feature = "ngrok")] { panic!("ngrok feature is not functional with axum=0.7 and hyper=1, waiting on https://github.com/ngrok/ngrok-rust/pull/137/files to re-enable."); // Run server } #[cfg(not(feature = "ngrok"))] { let _ngrok_authtoken = ngrok_authtoken; let _ngrok_domain = ngrok_domain; let _ngrok_username = ngrok_username; let _ngrok_password = ngrok_password; panic!("`text-generation-router` was compiled without the `ngrok` feature"); } } else { // Run server let listener = match tokio::net::TcpListener::bind(&addr).await { Ok(listener) => listener, Err(e) => { tracing::error!("Failed to bind to {addr}: {e}"); return Err(WebServerError::Axum(Box::new(e))); } }; axum::serve(listener, app) .with_graceful_shutdown(shutdown_signal()) .await .map_err(|err| WebServerError::Axum(Box::new(err)))?; } Ok(()) } /// get model info from the Huggingface Hub pub async fn get_hub_model_info(api: &ApiRepo) -> Option<HubModelInfo> { let response = api.info_request().send().await.ok()?; if response.status().is_success() { let hub_model_info: HubModelInfo = serde_json::from_str(&response.text().await.ok()?).ok()?; if let Some(sha) = &hub_model_info.sha { tracing::info!( "Serving revision {sha} of model {}", hub_model_info.model_id ); } Some(hub_model_info) } else { None } } /// get tokenizer_config from the Huggingface Hub pub async fn get_tokenizer_config(api_repo: &ApiRepo) -> Option<HubTokenizerConfig> { let tokenizer_config_filename = api_repo.get("tokenizer_config.json").await.ok()?; // Open the file in read-only mode with buffer. let file = File::open(tokenizer_config_filename).ok()?; let reader = BufReader::new(file); // Read the JSON contents of the file as an instance of 'HubTokenizerConfig'. let tokenizer_config: HubTokenizerConfig = serde_json::from_reader(reader) .map_err(|e| { tracing::warn!("Unable to parse tokenizer config: {}", e); e }) .ok()?; Some(tokenizer_config) } /// Shutdown signal handler async fn shutdown_signal() { let ctrl_c = async { signal::ctrl_c() .await .expect("failed to install Ctrl+C handler"); }; #[cfg(unix)] let terminate = async { signal::unix::signal(signal::unix::SignalKind::terminate()) .expect("failed to install signal handler") .recv() .await; }; #[cfg(not(unix))] let terminate = std::future::pending::<()>(); tokio::select! { _ = ctrl_c => {}, _ = terminate => {}, } tracing::info!("signal received, starting graceful shutdown"); opentelemetry::global::shutdown_tracer_provider(); } /// Convert to Axum supported formats impl From<InferError> for (StatusCode, Json<ErrorResponse>) { fn from(err: InferError) -> Self { let status_code = match err { InferError::GenerationError(_) => StatusCode::FAILED_DEPENDENCY, InferError::Overloaded(_) => StatusCode::TOO_MANY_REQUESTS, InferError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY, InferError::IncompleteGeneration => StatusCode::INTERNAL_SERVER_ERROR, InferError::IncompleteGenerationStream => StatusCode::INTERNAL_SERVER_ERROR, InferError::TemplateError(_) => StatusCode::UNPROCESSABLE_ENTITY, InferError::MissingTemplateVariable(_) => StatusCode::UNPROCESSABLE_ENTITY, InferError::ToolError(_) => StatusCode::UNPROCESSABLE_ENTITY, InferError::StreamSerializationError(_) => StatusCode::INTERNAL_SERVER_ERROR, }; ( status_code, Json(ErrorResponse { error: err.to_string(), error_type: err.error_type().to_string(), }), ) } } impl From<InferError> for Event { fn from(err: InferError) -> Self { Event::default() .json_data(ErrorResponse { error: err.to_string(), error_type: err.error_type().to_string(), }) .unwrap() } } #[derive(Debug, Error)] pub enum WebServerError { #[error("Axum error: {0}")] Axum(#[from] axum::BoxError), #[error("Tokenizer error: {0}")] Tokenizer(String), }
text-generation-inference/router/src/server.rs/0
{ "file_path": "text-generation-inference/router/src/server.rs", "repo_id": "text-generation-inference", "token_count": 44517 }
313
# Text Generation Inference Python gRPC Server A Python gRPC server for Text Generation Inference ## Install ```shell make install ``` ## Run ```shell make run-dev ```
text-generation-inference/server/README.md/0
{ "file_path": "text-generation-inference/server/README.md", "repo_id": "text-generation-inference", "token_count": 56 }
314
// Adapted from turboderp exllama: https://github.com/turboderp/exllama #ifndef _matrix_cuh #define _matrix_cuh #include <cuda_runtime.h> #include <cuda_fp16.h> class MatrixView_half { public: const half* data; const int height; const int width; __device__ __forceinline__ MatrixView_half(const half* data, const int height, const int width) : data(data), height(height), width(width) { } __device__ __forceinline__ half item(int row, int column) const { return data[row * width + column]; } __device__ __forceinline__ half2 item_half2(int row, int column) const { return ((half2*)data)[(row * width + column) / 2]; } __device__ __forceinline__ half2 item_half2half2(int row, int column) const { return __half2half2(data[row * width + column]); } __device__ __forceinline__ const half* item_ptr(int row, int column) const { return &data[row * width + column]; } }; class MatrixView_half_rw { public: half* data; const int height; const int width; __device__ __forceinline__ MatrixView_half_rw(half* data, const int height, const int width) : data(data), height(height), width(width) { } __device__ __forceinline__ half item(int row, int column) const { return data[row * width + column]; } __device__ __forceinline__ half2 item_half2(int row, int column) const { return ((half2*)data)[(row * width + column) / 2]; } __device__ __forceinline__ half* item_ptr(int row, int column) { return &data[row * width + column]; } __device__ __forceinline__ void set(int row, int column, half value) { data[row * width + column] = value; } __device__ __forceinline__ void set_half2(int row, int column, half2 value) { ((half2*)data)[(row * width + column) / 2] = value; } }; class MatrixView_q4_row { public: const uint32_t* data; const int height; const int width; __device__ __forceinline__ MatrixView_q4_row(const uint32_t* data, const int height, const int width) : data(data), height(height), width(width) { } __device__ __forceinline__ int item(int row, int column) const { int shift = (column & 0x07) * 4; return (data[row * width / 8 + column / 8] >> shift) & 0x0f; } }; class MatrixView_q4_column { public: const uint32_t* data; const int height; const int width; __device__ __forceinline__ MatrixView_q4_column(const uint32_t* data, const int height, const int width) : data(data), height(height), width(width) { } __device__ __forceinline__ int item(int row, int column) const { int shift = (row & 0x07) * 4; return (data[row / 8 * width + column] >> shift) & 0x0f; } __device__ __forceinline__ uint32_t item_uint32_t(int row, int column) { return data[row / 8 * width + column]; } __device__ __forceinline__ const uint32_t* item_uint32_ptr(int row, int column) { return &data[row / 8 * width + column]; } }; // TODO: Rewrite all these dot product functions using functors or something, move to q4_matmul.cu // Accumulated dot product of 8-element row vectors in h and quantized column vectors in v, constant zero/scale __device__ __forceinline__ half2 dot_product_8 ( const half2 acc, MatrixView_half& h_, const int h_row, const int h_column, // divisible by 8 MatrixView_q4_column& v_, const int v_row, // divisible by 8 const int v_column, const half2 v_scale_2, const uint32_t v_zero, // + 1 (!!) const int count ) { const half2* h_ptr = (const half2*) h_.item_ptr(h_row, h_column); const uint32_t* v_ptr = (const uint32_t*) v_.item_uint32_ptr(v_row, v_column); half2 result = acc; for (int i = 0; i < count; i++) { uint32_t v_read = *v_ptr; v_ptr += v_.width; half v_0 = __int2half_rn((int)((v_read ) & 0x0f) - v_zero); half v_1 = __int2half_rn((int)((v_read >> 4) & 0x0f) - v_zero); half v_2 = __int2half_rn((int)((v_read >> 8) & 0x0f) - v_zero); half v_3 = __int2half_rn((int)((v_read >> 12) & 0x0f) - v_zero); half v_4 = __int2half_rn((int)((v_read >> 16) & 0x0f) - v_zero); half v_5 = __int2half_rn((int)((v_read >> 20) & 0x0f) - v_zero); half v_6 = __int2half_rn((int)((v_read >> 24) & 0x0f) - v_zero); half v_7 = __int2half_rn((int)((v_read >> 28) ) - v_zero); half2 v_01 = __halves2half2(v_0, v_1); half2 v_23 = __halves2half2(v_2, v_3); half2 v_45 = __halves2half2(v_4, v_5); half2 v_67 = __halves2half2(v_6, v_7); // half2 v_01 = q4_table[v_zero - 1][(v_read ) & 0xff]; // (constant memory is too slow apparently) // half2 v_23 = q4_table[v_zero - 1][(v_read >> 8) & 0xff]; // half2 v_45 = q4_table[v_zero - 1][(v_read >> 16) & 0xff]; // half2 v_67 = q4_table[v_zero - 1][(v_read >> 24) ]; half2 tmp = __hmul2(*h_ptr++, v_01); tmp = __hfma2(*h_ptr++, v_23, tmp); tmp = __hfma2(*h_ptr++, v_45, tmp); tmp = __hfma2(*h_ptr++, v_67, tmp); result = __hfma2(v_scale_2, tmp, result); } return result; } __device__ __forceinline__ half dot_product_8_h ( const half acc, MatrixView_half& h_, const int h_row, const int h_column, // divisible by 8 MatrixView_q4_column& v_, const int v_row, // divisible by 8 const int v_column, const half v_scale, const uint32_t v_zero, // + 1 (!!) const int count ) { const half* h_ptr = h_.item_ptr(h_row, h_column); const uint32_t* v_ptr = (const uint32_t*) v_.item_uint32_ptr(v_row, v_column); half result = acc; for (int i = 0; i < count; i++) { uint32_t v_read = *v_ptr; v_ptr += v_.width; half v_0 = __int2half_rn((int)((v_read ) & 0x0f) - v_zero); half v_1 = __int2half_rn((int)((v_read >> 4) & 0x0f) - v_zero); half v_2 = __int2half_rn((int)((v_read >> 8) & 0x0f) - v_zero); half v_3 = __int2half_rn((int)((v_read >> 12) & 0x0f) - v_zero); half v_4 = __int2half_rn((int)((v_read >> 16) & 0x0f) - v_zero); half v_5 = __int2half_rn((int)((v_read >> 20) & 0x0f) - v_zero); half v_6 = __int2half_rn((int)((v_read >> 24) & 0x0f) - v_zero); half v_7 = __int2half_rn((int)((v_read >> 28) ) - v_zero); half tmp = __hmul(*h_ptr++, v_0); tmp = __hfma(*h_ptr++, v_1, tmp); tmp = __hfma(*h_ptr++, v_2, tmp); tmp = __hfma(*h_ptr++, v_3, tmp); tmp = __hfma(*h_ptr++, v_4, tmp); tmp = __hfma(*h_ptr++, v_5, tmp); tmp = __hfma(*h_ptr++, v_6, tmp); tmp = __hfma(*h_ptr++, v_7, tmp); result = __hfma(v_scale, tmp, result); } return result; } // Accumulated dot product of 8-element row vectors in h and quantized column vectors in v, constant zero/scale, with x_map __device__ __forceinline__ half2 dot_product_8_x_map ( const half2 acc, MatrixView_half& h_, const int h_row, const int h_column, // divisible by 8 MatrixView_q4_column& v_, const int v_row, // divisible by 8 const int v_column, const half2 v_scale_2, const uint32_t v_zero, // + 1 (!!) const int count, const uint32_t* x_map ) { const half* h_ptr = h_.item_ptr(h_row, 0); const uint32_t* x_map_ptr = x_map + h_column; const uint32_t* v_ptr = (const uint32_t*) v_.item_uint32_ptr(v_row, v_column); half2 result = acc; for (int i = 0; i < count; i++) { uint32_t v_read = *v_ptr; v_ptr += v_.width; half v_0 = __int2half_rn((int)((v_read ) & 0x0f) - v_zero); half v_1 = __int2half_rn((int)((v_read >> 4) & 0x0f) - v_zero); half v_2 = __int2half_rn((int)((v_read >> 8) & 0x0f) - v_zero); half v_3 = __int2half_rn((int)((v_read >> 12) & 0x0f) - v_zero); half v_4 = __int2half_rn((int)((v_read >> 16) & 0x0f) - v_zero); half v_5 = __int2half_rn((int)((v_read >> 20) & 0x0f) - v_zero); half v_6 = __int2half_rn((int)((v_read >> 24) & 0x0f) - v_zero); half v_7 = __int2half_rn((int)((v_read >> 28) ) - v_zero); half2 v_01 = __halves2half2(v_0, v_1); half2 v_23 = __halves2half2(v_2, v_3); half2 v_45 = __halves2half2(v_4, v_5); half2 v_67 = __halves2half2(v_6, v_7); half h_0 = h_ptr[*x_map_ptr++]; half h_1 = h_ptr[*x_map_ptr++]; half h_2 = h_ptr[*x_map_ptr++]; half h_3 = h_ptr[*x_map_ptr++]; half h_4 = h_ptr[*x_map_ptr++]; half h_5 = h_ptr[*x_map_ptr++]; half h_6 = h_ptr[*x_map_ptr++]; half h_7 = h_ptr[*x_map_ptr++]; half2 h_01 = __halves2half2(h_0, h_1); half2 h_23 = __halves2half2(h_2, h_3); half2 h_45 = __halves2half2(h_4, h_5); half2 h_67 = __halves2half2(h_6, h_7); half2 tmp = __hmul2(h_01, v_01); tmp = __hfma2(h_23, v_23, tmp); tmp = __hfma2(h_45, v_45, tmp); tmp = __hfma2(h_67, v_67, tmp); result = __hfma2(v_scale_2, tmp, result); } return result; } __device__ __forceinline__ half dot_product_8_x_map_h ( const half acc, MatrixView_half& h_, const int h_row, const int h_column, // divisible by 8 MatrixView_q4_column& v_, const int v_row, // divisible by 8 const int v_column, const half v_scale, const uint32_t v_zero, // + 1 (!!) const int count, const uint32_t* x_map ) { const half* h_ptr = h_.item_ptr(h_row, 0); const uint32_t* x_map_ptr = x_map + h_column; const uint32_t* v_ptr = (const uint32_t*) v_.item_uint32_ptr(v_row, v_column); half result = acc; for (int i = 0; i < count; i++) { uint32_t v_read = *v_ptr; v_ptr += v_.width; half v_0 = __int2half_rn((int)((v_read ) & 0x0f) - v_zero); half v_1 = __int2half_rn((int)((v_read >> 4) & 0x0f) - v_zero); half v_2 = __int2half_rn((int)((v_read >> 8) & 0x0f) - v_zero); half v_3 = __int2half_rn((int)((v_read >> 12) & 0x0f) - v_zero); half v_4 = __int2half_rn((int)((v_read >> 16) & 0x0f) - v_zero); half v_5 = __int2half_rn((int)((v_read >> 20) & 0x0f) - v_zero); half v_6 = __int2half_rn((int)((v_read >> 24) & 0x0f) - v_zero); half v_7 = __int2half_rn((int)((v_read >> 28) ) - v_zero); half tmp = __hmul(h_ptr[*x_map_ptr++], v_0); tmp = __hfma(h_ptr[*x_map_ptr++], v_1, tmp); tmp = __hfma(h_ptr[*x_map_ptr++], v_2, tmp); tmp = __hfma(h_ptr[*x_map_ptr++], v_3, tmp); tmp = __hfma(h_ptr[*x_map_ptr++], v_4, tmp); tmp = __hfma(h_ptr[*x_map_ptr++], v_5, tmp); tmp = __hfma(h_ptr[*x_map_ptr++], v_6, tmp); tmp = __hfma(h_ptr[*x_map_ptr++], v_7, tmp); result = __hfma(v_scale, tmp, result); } return result; } #endif
text-generation-inference/server/exllama_kernels/exllama_kernels/matrix.cuh/0
{ "file_path": "text-generation-inference/server/exllama_kernels/exllama_kernels/matrix.cuh", "repo_id": "text-generation-inference", "token_count": 5380 }
315
#ifndef _qdq_4_cuh #define _qdq_4_cuh #include "qdq_util.cuh" #include "../../config.h" #if QMODE_4BIT == 1 // Permutation: // // 77775555 33331111 66664444 22220000 __forceinline__ __device__ void shuffle_4bit_8 ( uint32_t* q, int stride ) { uint32_t qa = q[0]; uint32_t qb = 0; #pragma unroll for (int i = 0; i < 4; i++) { uint32_t qa0 = qa & 0x0f; uint32_t qa1 = (qa & 0xf0) >> 4; qa >>= 8; qb |= (qa1 << (i * 4 + 16)); qb |= (qa0 << (i * 4)); } q[0] = qb; } __forceinline__ __device__ void dequant_4bit_8 ( const uint32_t q_0, half2 (&dq)[4], int stride ) { const uint32_t c0 = 0x64006400; const half y16_ = __float2half_rn(1.0f / 16.0f); const half2 y16 = __halves2half2(y16_, y16_); const half z1_ = __float2half_rn(-1024.0f - 8.0f); const half z16_ = __float2half_rn(-1024.0f / 16.0f - 8.0f); const half2 z1 = __halves2half2(z1_, z1_); const half2 z16 = __halves2half2(z16_, z16_); uint32_t qa = q_0; half2_uint32 q0((qa & 0x000f000f) | c0); // half2(q[ 0], q[ 1]) + 1024 half2_uint32 q1((qa & 0x00f000f0) | c0); // half2(q[ 2], q[ 3]) * 16 + 1024 qa >>= 8; half2_uint32 q2((qa & 0x000f000f) | c0); // half2(q[ 4], q[ 5]) + 1024 half2_uint32 q3((qa & 0x00f000f0) | c0); // half2(q[ 6], q[ 7]) * 16 + 1024 dq[0] = __hadd2(q0.as_half2, z1); dq[1] = __hfma2(q1.as_half2, y16, z16); dq[2] = __hadd2(q2.as_half2, z1); dq[3] = __hfma2(q3.as_half2, y16, z16); } __forceinline__ __device__ void dequant_4bit_8_prep_zero_scale ( const uint32_t zero, const half scale, half2 (&z1z16)[2], half2 (&y1y16)[2] ) { half_uint16 z1(0xe400 | zero); // half(-1024.0f - zero); half z16 = __hsub(__int2half_rn(-64), __int2half_rn(zero)); half2 scale2 = __half2half2(scale); z1z16[0] = __hmul2(scale2, __half2half2(z1.as_half)); z1z16[1] = __hmul2(scale2, __half2half2(z16)); const half y1 = __float2half_rn(1.0f); const half y16 = __float2half_rn(1.0f / 16.0f); y1y16[0] = __hmul2(scale2, __half2half2(y1)); y1y16[1] = __hmul2(scale2, __half2half2(y16)); } __forceinline__ __device__ void dequant_4bit_8_prep_zero ( const uint32_t zero, half2(&z1z16)[2], half2(&y1y16)[2] ) { half_uint16 z1(0xe400 | zero); // half(-1024.0f - zero); half z16 = __hsub(__int2half_rn(-64), __int2half_rn(zero)); z1z16[0] = __half2half2(z1.as_half); z1z16[1] = __half2half2(z16); const half y1 = __float2half_rn(1.0f); const half y16 = __float2half_rn(1.0f / 16.0f); y1y16[0] = __half2half2(y1); y1y16[1] = __half2half2(y16); } __forceinline__ __device__ void dequant_4bit_8_gptq ( const uint32_t q_0, half2 (&dq)[4], half2 (&z1z16)[2], half2 (&y1y16)[2], int stride, bool scaled ) { const uint32_t c0 = 0x64006400; uint32_t qa = q_0; half2_uint32 q0((qa & 0x000f000f) | c0); // half2( q[0] + 1024, q[1] + 1024 ) half2_uint32 q1((qa & 0x00f000f0) | c0); // half2( q[2] * 16 + 1024, q[3] * 16 + 1024 ) qa >>= 8; half2_uint32 q2((qa & 0x000f000f) | c0); // half2( q[4] + 1024, q[5] + 1024 ) half2_uint32 q3((qa & 0x00f000f0) | c0); // half2( q[6] * 16 + 1024, q[7] * 16 + 1024 ) if (scaled) { dq[0] = __hfma2(q0.as_half2, y1y16[0], z1z16[0]); // half2( q[0] * s - z * s, q[1] * s - z * s) dq[1] = __hfma2(q1.as_half2, y1y16[1], z1z16[1]); // half2( q[2] * s - z * s, q[3] * s - z * s) dq[2] = __hfma2(q2.as_half2, y1y16[0], z1z16[0]); dq[3] = __hfma2(q3.as_half2, y1y16[1], z1z16[1]); } else { dq[0] = __hadd2(q0.as_half2, z1z16[0]); // half2( q[0] - z, q[1] - z ) dq[1] = __hfma2(q1.as_half2, y1y16[1], z1z16[1]); // half2( q[2] - z, q[3] - z ) dq[2] = __hadd2(q2.as_half2, z1z16[0]); // half2( q[4] - z, q[5] - z ) dq[3] = __hfma2(q3.as_half2, y1y16[1], z1z16[1]); // half2( q[6] - z, q[7] - z ) } } #else __forceinline__ __device__ void shuffle_4bit_8 ( uint32_t* q, int stride ) { } __forceinline__ __device__ void dequant_4bit_8 ( const uint32_t q_0, half2 (&dq)[4], int stride ) { half dqh[8]; for (int i = 0; i < 8; i++) dqh[i] = dq_ns(exb(q_0, i * 4, 0x0f), 8); for (int i = 0; i < 4; i++) dq[i] = __halves2half2(dqh[i * 2], dqh[i * 2 + 1]); } __forceinline__ __device__ void dequant_4bit_8_prep_zero_scale ( const uint32_t zero, const half scale, half2 (&z1)[2], half2 (&y1)[2] ) { half z = __int2half_rn(-((int)zero)); z = __hmul(z, scale); z1[0] = __half2half2(z); y1[0] = __half2half2(scale); } __forceinline__ __device__ void dequant_4bit_8_prep_zero ( const uint32_t zero, half2(&z1)[2], half2(&y1)[2] ) { half z = __int2half_rn(-((int)zero)); z1[0] = __half2half2(z); } __forceinline__ __device__ void dequant_4bit_8_gptq ( const uint32_t q_0, half2 (&dq)[4], half2 (&z1)[2], half2 (&y1)[2], int stride, bool scaled ) { half2 dqh2[8]; uint32_t qa = q_0; for (int i = 0; i < 4; i++) { half d0 = __int2half_rn(qa & 0x0f); qa >>= 4; half d1 = __int2half_rn(qa & 0x0f); qa >>= 4; dqh2[i] = __halves2half2(d0, d1); } if (scaled) { dq[0] = __hfma2(dqh2[0], y1[0], z1[0]); dq[1] = __hfma2(dqh2[1], y1[0], z1[0]); dq[2] = __hfma2(dqh2[2], y1[0], z1[0]); dq[3] = __hfma2(dqh2[3], y1[0], z1[0]); } else { dq[0] = __hadd2(dqh2[0], z1[0]); dq[1] = __hadd2(dqh2[1], z1[0]); dq[2] = __hadd2(dqh2[2], z1[0]); dq[3] = __hadd2(dqh2[3], z1[0]); } } #endif #endif
text-generation-inference/server/exllamav2_kernels/exllamav2_kernels/cuda/quant/qdq_4.cuh/0
{ "file_path": "text-generation-inference/server/exllamav2_kernels/exllamav2_kernels/cuda/quant/qdq_4.cuh", "repo_id": "text-generation-inference", "token_count": 3279 }
316
import pytest import torch from copy import copy from transformers import AutoTokenizer from text_generation_server.pb import generate_pb2 from text_generation_server.models.causal_lm import CausalLMBatch from text_generation_server.utils import weight_hub_files, download_weights from text_generation_server.models.bloom import BloomCausalLMBatch, BLOOMSharded from text_generation_server.models.custom_modeling.bloom_modeling import ( BloomForCausalLM, ) @pytest.fixture(scope="session") def default_bloom(): model_id = "bigscience/bloom-560m" revision = "main" filenames = weight_hub_files(model_id, revision, ".safetensors") download_weights(filenames, model_id, revision) return BLOOMSharded( model_id, model_class=BloomForCausalLM, ) @pytest.fixture(scope="session") def bloom_560m_tokenizer(): return AutoTokenizer.from_pretrained("bigscience/bloom-560m", padding_side="left") @pytest.fixture def default_pb_request(default_pb_parameters, default_pb_stop_parameters): return generate_pb2.Request( id=0, inputs="Test", input_chunks=generate_pb2.Input(chunks=[generate_pb2.InputChunk(text="Test")]), prefill_logprobs=True, truncate=100, parameters=default_pb_parameters, stopping_parameters=default_pb_stop_parameters, ) @pytest.fixture def default_pb_batch(default_pb_request): return generate_pb2.Batch(id=0, requests=[default_pb_request], size=1) @pytest.fixture def default_bloom_batch(default_pb_batch, bloom_560m_tokenizer): return BloomCausalLMBatch.from_pb( default_pb_batch, bloom_560m_tokenizer, torch.float32, torch.device("cpu") ) @pytest.fixture def default_multi_requests_bloom_batch(default_pb_request, bloom_560m_tokenizer): req_0 = copy(default_pb_request) req_0.id = 1 req_1 = default_pb_request req_1.id = 2 req_1.stopping_parameters.max_new_tokens = 5 batch_pb = generate_pb2.Batch(id=0, requests=[req_0, req_1], size=2) return BloomCausalLMBatch.from_pb( batch_pb, bloom_560m_tokenizer, torch.float32, torch.device("cpu") ) def test_batch_from_pb(default_pb_batch, default_bloom_batch): batch = default_bloom_batch assert batch.batch_id == default_pb_batch.id assert batch.requests == default_pb_batch.requests assert len(batch.input_ids) == default_pb_batch.size assert batch.input_ids[0][-1] == 10264 assert torch.all(batch.input_ids[0][:-1] == 3) assert batch.attention_mask[0][0] == 1 assert torch.all(batch.attention_mask[0][1:] == 0) assert batch.past_key_values is None assert all( [ torch.equal(input_ids, all_input_ids[:, 0]) for input_ids, all_input_ids in zip(batch.input_ids, batch.all_input_ids) ] ) assert batch.input_lengths == [1] assert len(batch) == default_pb_batch.size assert len(batch.next_token_choosers) == len(batch.stopping_criterias) == len(batch) assert batch.max_input_length == batch.input_lengths[0] def test_batch_concatenate_no_prefill(default_bloom_batch): with pytest.raises(ValueError): BloomCausalLMBatch.concatenate([default_bloom_batch, default_bloom_batch]) def test_causal_lm_batch_type(default_bloom): assert default_bloom.batch_type == BloomCausalLMBatch def test_causal_lm_generate_token(default_bloom, default_bloom_batch): sequence_length = len(default_bloom_batch.all_input_ids[0]) generations, next_batch, _ = default_bloom.generate_token(default_bloom_batch) assert len(generations) == len(default_bloom_batch) assert isinstance(next_batch, CausalLMBatch) assert not next_batch.keys_head_dim_last assert len(next_batch.all_input_ids) == len(next_batch) assert len(next_batch.all_input_ids[0]) == sequence_length + 1 assert len(next_batch.attention_mask[0]) == 11 assert torch.all(next_batch.all_input_ids[0][-2:] == 10264) assert torch.all(next_batch.all_input_ids[0][:-2] == 3) assert torch.all(next_batch.attention_mask[0][:2] == 1) assert torch.all(next_batch.attention_mask[0][2:] == 0) assert next_batch.input_ids.shape == (len(next_batch), 1) assert next_batch.input_ids[0, 0] == 10264 assert next_batch.input_lengths == [2] assert next_batch.max_input_length == next_batch.input_lengths[0] assert next_batch.past_key_values is not None assert all( [p[0].shape == (16, 64, sequence_length) for p in next_batch.past_key_values] ) assert all( [p[1].shape == (16, sequence_length, 64) for p in next_batch.past_key_values] ) assert all([generation.generated_text is None for generation in generations]) assert all([len(generation.prefill_tokens) == 1 for generation in generations]) assert all( [ token_id.item() == 10264 for generation in generations for token_id in generation.tokens.token_ids ] ) assert all( [ token_text == "Test" for generation in generations for token_text in generation.tokens.texts ] ) assert generations[0].request_id == 0 def test_causal_lm_generate_token_completion(default_bloom, default_bloom_batch): next_batch = default_bloom_batch for _ in range(default_bloom_batch.stopping_criterias[0].max_new_tokens - 1): generations, next_batch, _ = default_bloom.generate_token(next_batch) assert len(generations) == len(default_bloom_batch) generations, next_batch, _ = default_bloom.generate_token(next_batch) assert next_batch is None assert len(generations) == 1 assert ( generations[0].generated_text.text == "TestTestTestTestTestTestTestTestTestTest" ) assert generations[0].request_id == default_bloom_batch.requests[0].id assert ( generations[0].generated_text.generated_tokens == default_bloom_batch.stopping_criterias[0].max_new_tokens ) def test_causal_lm_generate_token_completion_multi( default_bloom, default_multi_requests_bloom_batch ): next_batch = default_multi_requests_bloom_batch for i in range( default_multi_requests_bloom_batch.stopping_criterias[1].max_new_tokens - 1 ): generations, next_batch, _ = default_bloom.generate_token(next_batch) assert len(generations) == len(default_multi_requests_bloom_batch) generations, next_batch, _ = default_bloom.generate_token(next_batch) assert next_batch is not None assert len(generations) == 2 assert generations[1].generated_text.text == "TestTestTestTestTest" assert ( generations[1].request_id == default_multi_requests_bloom_batch.requests[1].id ) assert ( generations[1].generated_text.generated_tokens == default_multi_requests_bloom_batch.stopping_criterias[1].max_new_tokens ) # Copy stopping_criterias before filtering stopping_criterias = default_multi_requests_bloom_batch.stopping_criterias.copy() next_batch = next_batch.filter([next_batch.requests[0].id]) for _ in range( stopping_criterias[0].max_new_tokens - stopping_criterias[1].max_new_tokens - 1 ): generations, next_batch, _ = default_bloom.generate_token(next_batch) assert len(generations) == len(next_batch) generations, next_batch, _ = default_bloom.generate_token(next_batch) assert next_batch is None assert len(generations) == 1 assert ( generations[0].generated_text.text == "TestTestTestTestTestTestTestTestTestTest" ) assert ( generations[0].request_id == default_multi_requests_bloom_batch.requests[0].id ) assert ( generations[0].generated_text.generated_tokens == default_multi_requests_bloom_batch.stopping_criterias[0].max_new_tokens ) def test_batch_concatenate( default_bloom, default_bloom_batch, default_multi_requests_bloom_batch ): next_batch_0 = default_bloom_batch _, next_batch_0, _ = default_bloom.generate_token(next_batch_0) _, next_batch_0, _ = default_bloom.generate_token(next_batch_0) next_batch_1 = default_multi_requests_bloom_batch _, next_batch_1, _ = default_bloom.generate_token(next_batch_1) # Clone past_key_values before concatenating to compare after, # because they are removed from the concatenated batches next_batch_0_past_key_values = [ (k.clone(), v.clone()) for (k, v) in next_batch_0.past_key_values ] next_batch_1_past_key_values = [ (k.clone(), v.clone()) for (k, v) in next_batch_1.past_key_values ] next_batch = BloomCausalLMBatch.concatenate([next_batch_0, next_batch_1]) assert torch.equal(next_batch.all_input_ids[0], next_batch_0.all_input_ids[0]) assert torch.equal(next_batch.all_input_ids[1], next_batch_1.all_input_ids[0]) assert torch.equal(next_batch.all_input_ids[2], next_batch_1.all_input_ids[1]) assert torch.all( next_batch.attention_mask[0, : -next_batch.padding_right_offset] == 1 ) assert torch.all( next_batch.attention_mask[1:, 1 : -next_batch.padding_right_offset] == 1 ) assert torch.all(next_batch.attention_mask[1:, 3:] == 0) assert next_batch.batch_id == 0 assert torch.all(next_batch.input_ids == 10264) assert next_batch.input_lengths == [3, 2, 2] assert next_batch.max_input_length == 3 assert next_batch.requests[0] == next_batch_0.requests[0] assert next_batch.requests[1:] == list(next_batch_1.requests) assert next_batch.next_token_choosers[0] == next_batch_0.next_token_choosers[0] assert next_batch.next_token_choosers[1:] == next_batch_1.next_token_choosers assert next_batch.stopping_criterias[0] == next_batch_0.stopping_criterias[0] assert next_batch.stopping_criterias[1:] == next_batch_1.stopping_criterias assert next_batch.past_key_values is not None assert all([p[0].shape == (3, 16, 64, 2) for p in next_batch.past_key_values]) assert all([p[1].shape == (3, 16, 2, 64) for p in next_batch.past_key_values]) for i, past in enumerate(next_batch.past_key_values): assert torch.equal(next_batch_0_past_key_values[i][0][:, :, -2:], past[0][0]) assert torch.equal( next_batch_1_past_key_values[i][0][:, :, -1:], past[0][1:, :, :, -1].reshape(-1, 64, 1), ) assert torch.equal(next_batch_0_past_key_values[i][1][:, -2:, :], past[1][0]) assert torch.equal( next_batch_1_past_key_values[i][1][:, -1:, :], past[1][1:, :, -1, :].reshape(-1, 1, 64), ) for _ in range( default_multi_requests_bloom_batch.stopping_criterias[1].max_new_tokens - 2 ): generations, next_batch, _ = default_bloom.generate_token(next_batch) assert len(generations) == len(next_batch) generations, next_batch, _ = default_bloom.generate_token(next_batch) assert next_batch is not None assert len(generations) == 3 assert generations[2].generated_text.text == "TestTestTestTestTest" assert ( generations[2].request_id == default_multi_requests_bloom_batch.requests[1].id ) assert ( generations[2].generated_text.generated_tokens == default_multi_requests_bloom_batch.stopping_criterias[1].max_new_tokens ) next_batch = next_batch.filter( [next_batch.requests[0].id, next_batch.requests[1].id] ) for _ in range( default_bloom_batch.stopping_criterias[0].max_new_tokens - default_multi_requests_bloom_batch.stopping_criterias[1].max_new_tokens - 2 ): generations, next_batch, _ = default_bloom.generate_token(next_batch) assert len(generations) == len(next_batch) generations, next_batch, _ = default_bloom.generate_token(next_batch) assert next_batch is not None assert len(generations) == 2 assert ( generations[0].generated_text.text == "TestTestTestTestTestTestTestTestTestTest" ) assert generations[0].request_id == default_bloom_batch.requests[0].id assert ( generations[0].generated_text.generated_tokens == default_bloom_batch.stopping_criterias[0].max_new_tokens ) next_batch = next_batch.filter([next_batch.requests[1].id]) for _ in range( default_multi_requests_bloom_batch.stopping_criterias[0].max_new_tokens - default_bloom_batch.stopping_criterias[0].max_new_tokens - default_multi_requests_bloom_batch.stopping_criterias[1].max_new_tokens - 4 ): generations, next_batch, _ = default_bloom.generate_token(next_batch) assert len(generations) == len(next_batch) generations, next_batch, _ = default_bloom.generate_token(next_batch) assert next_batch is None assert len(generations) == 1 assert ( generations[0].generated_text.text == "TestTestTestTestTestTestTestTestTestTest" ) assert ( generations[0].request_id == default_multi_requests_bloom_batch.requests[0].id ) assert ( generations[0].generated_text.generated_tokens == default_multi_requests_bloom_batch.stopping_criterias[0].max_new_tokens )
text-generation-inference/server/tests/models/test_bloom.py/0
{ "file_path": "text-generation-inference/server/tests/models/test_bloom.py", "repo_id": "text-generation-inference", "token_count": 5403 }
317
from typing import Optional import torch import torch.nn as nn import intel_extension_for_pytorch as ipex class WQLinear(nn.Module): def __init__( self, w_bit, group_size, qweight, qzeros, scales, bias: Optional[torch.Tensor] ): super().__init__() if w_bit not in [4]: raise NotImplementedError("Only 4-bit are supported for now.") self.in_features = qweight.shape[0] self.out_features = qweight.shape[1] * 32 // w_bit self.w_bit = w_bit self.group_size = group_size if group_size != -1 else self.in_features # quick sanity check (make sure aligment) assert self.in_features % self.group_size == 0 assert self.out_features % (32 // self.w_bit) == 0 self.qweight = qweight self.qzeros = qzeros self.scales = scales self.bias = bias self.woq_linear = ( ipex.llm.quantization.IPEXWeightOnlyQuantizedLinear.from_weight( self.qweight, self.scales, self.qzeros, self.in_features, self.out_features, bias=self.bias, group_size=self.group_size, quant_method=ipex.llm.quantization.QuantMethod.AWQ_GEMM, dtype=ipex.llm.quantization.QuantDtype.INT4, ) ) @torch.no_grad() def forward(self, x): out_shape = x.shape[:-1] + (self.out_features,) out = self.woq_linear(x.reshape(-1, x.shape[-1])) return out.reshape(out_shape)
text-generation-inference/server/text_generation_server/layers/awq/quantize/ipex.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/layers/awq/quantize/ipex.py", "repo_id": "text-generation-inference", "token_count": 778 }
318
import math import numpy as np import torch import torch.nn as nn import intel_extension_for_pytorch as ipex class QuantLinear(nn.Module): def __init__(self, qweight, qzeros, scales, g_idx, bias, bits, groupsize): super().__init__() self.register_buffer("qweight", qweight) self.register_buffer("qzeros", qzeros) self.register_buffer("scales", scales) self.register_buffer("g_idx", g_idx) if bias is not None: self.register_buffer("bias", bias) else: self.bias = None if bits not in [4]: raise NotImplementedError("Only 4 bits are supported.") self.bits = bits self.maxq = 2**self.bits - 1 self.groupsize = groupsize self.outfeatures = qweight.shape[1] self.infeatures = qweight.shape[0] * 32 // bits self.woq_linear = ( ipex.llm.quantization.IPEXWeightOnlyQuantizedLinear.from_weight( self.qweight, self.scales, self.qzeros, self.infeatures, self.outfeatures, bias=self.bias, group_size=self.groupsize, g_idx=g_idx, quant_method=ipex.llm.quantization.QuantMethod.GPTQ_GEMM, dtype=ipex.llm.quantization.QuantDtype.INT4, ) ) @classmethod def new(cls, bits, groupsize, infeatures, outfeatures, bias): if bits not in [4]: raise NotImplementedError("Only 4 bits are supported.") qweight = torch.zeros((infeatures // 32 * bits, outfeatures), dtype=torch.int32) qzeros = torch.zeros( (math.ceil(infeatures / groupsize), outfeatures // 32 * bits), dtype=torch.int32, ) scales = torch.zeros( (math.ceil(infeatures / groupsize), outfeatures), dtype=torch.float16 ) g_idx = torch.tensor( [i // groupsize for i in range(infeatures)], dtype=torch.int32 ) if bias: bias = torch.zeros((outfeatures), dtype=torch.float16) else: bias = None return cls(qweight, qzeros, scales, g_idx, bias, bits, groupsize) def pack(self, linear, scales, zeros, g_idx=None): self.g_idx = g_idx.clone() if g_idx is not None else self.g_idx scales = scales.t().contiguous() zeros = zeros.t().contiguous() scale_zeros = zeros * scales self.scales = scales.clone().half() if linear.bias is not None: self.bias = linear.bias.clone().half() intweight = [] for idx in range(self.infeatures): intweight.append( torch.round( (linear.weight.data[:, idx] + scale_zeros[self.g_idx[idx]]) / self.scales[self.g_idx[idx]] ).to(torch.int)[:, None] ) intweight = torch.cat(intweight, dim=1) intweight = intweight.t().contiguous() intweight = intweight.numpy().astype(np.uint32) qweight = np.zeros( (intweight.shape[0] // 32 * self.bits, intweight.shape[1]), dtype=np.uint32 ) i = 0 row = 0 while row < qweight.shape[0]: if self.bits in [4]: for j in range(i, i + (32 // self.bits)): qweight[row] |= intweight[j] << (self.bits * (j - i)) i += 32 // self.bits row += 1 else: raise NotImplementedError("Only 4 bits are supported.") qweight = qweight.astype(np.int32) self.qweight = torch.from_numpy(qweight) zeros -= 1 zeros = zeros.numpy().astype(np.uint32) qzeros = np.zeros( (zeros.shape[0], zeros.shape[1] // 32 * self.bits), dtype=np.uint32 ) i = 0 col = 0 while col < qzeros.shape[1]: if self.bits in [4]: for j in range(i, i + (32 // self.bits)): qzeros[:, col] |= zeros[:, j] << (self.bits * (j - i)) i += 32 // self.bits col += 1 else: raise NotImplementedError("Only 4 bits are supported.") qzeros = qzeros.astype(np.int32) self.qzeros = torch.from_numpy(qzeros) def forward(self, x): out_shape = x.shape[:-1] + (self.outfeatures,) out = self.woq_linear(x.reshape(-1, x.shape[-1])) return out.reshape(out_shape)
text-generation-inference/server/text_generation_server/layers/gptq/ipex.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/layers/gptq/ipex.py", "repo_id": "text-generation-inference", "token_count": 2335 }
319
# coding=utf-8 # Copyright 2023, 2024 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Tuple import torch def grouped_topk( hidden_states: torch.Tensor, gating_output: torch.Tensor, topk: int, renormalize: bool, num_expert_group: int = 0, topk_group: int = 0, ) -> Tuple[torch.Tensor, torch.Tensor]: scores = torch.softmax(gating_output, dim=-1) num_token = scores.shape[0] group_scores = ( scores.view(num_token, num_expert_group, -1).max(dim=-1).values ) # [n, n_group] group_idx = torch.topk(group_scores, k=topk_group, dim=-1, sorted=False)[ 1 ] # [n, top_k_group] group_mask = torch.zeros_like(group_scores) # [n, n_group] group_mask.scatter_(1, group_idx, 1) # [n, n_group] score_mask = ( group_mask.unsqueeze(-1) .expand(num_token, num_expert_group, scores.shape[-1] // num_expert_group) .reshape(num_token, -1) ) # [n, e] tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e] topk_weights, topk_ids = torch.topk(tmp_scores, k=topk, dim=-1, sorted=False) if renormalize: topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True) return topk_weights, topk_ids def fused_topk( hidden_states: torch.Tensor, gating_output: torch.Tensor, topk: int, renormalize: bool, ) -> Tuple[torch.Tensor, torch.Tensor]: topk_weights = torch.nn.functional.softmax( gating_output, dim=1, dtype=torch.float32 ) topk_weights, topk_ids = torch.topk(topk_weights, topk, dim=-1) if renormalize: topk_weights /= topk_weights.sum(dim=-1, keepdim=True) return topk_weights, topk_ids
text-generation-inference/server/text_generation_server/layers/moe/fused_moe_ipex.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/layers/moe/fused_moe_ipex.py", "repo_id": "text-generation-inference", "token_count": 920 }
320
# coding=utf-8 # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch import torch.distributed from torch import nn from transformers.activations import ACT2FN from transformers.configuration_utils import PretrainedConfig from typing import Optional, List, Tuple from text_generation_server.layers.attention import ( paged_attention, attention, Seqlen, ) from text_generation_server.layers import ( TensorParallelRowLinear, TensorParallelColumnLinear, TensorParallelEmbedding, SpeculativeHead, get_linear, TensorParallelMultiAdapterLinear, TensorParallelAdapterRowLinear, ) from text_generation_server.layers.attention.kv_cache import get_kv_scales from text_generation_server.layers.rotary import PositionRotaryEmbedding from text_generation_server.layers.layernorm import ( FastRMSNorm, ) from text_generation_server.utils.weights import UnquantizedWeight class Gemma2Config(PretrainedConfig): def __init__( self, vocab_size=256128, hidden_size=3072, intermediate_size=24576, num_hidden_layers=28, num_attention_heads=16, num_key_value_heads=16, head_dim=256, hidden_act="gelu_pytorch_tanh", max_position_embeddings=8192, initializer_range=0.02, rms_norm_eps=1e-6, use_cache=True, pad_token_id=None, bos_token_id=1, eos_token_id=2, tie_word_embeddings=True, rope_theta=10000.0, rope_scaling=None, attention_bias=False, attention_dropout=0.0, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.head_dim = head_dim self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads # for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self.attention_bias = attention_bias self.attention_dropout = attention_dropout super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, ) class Gemma2FastRMSNorm(FastRMSNorm): @classmethod def load(cls, prefix: str, weights, eps=1e-6): dtype = weights.dtype weights.dtype = torch.float32 weight = weights.get_tensor(f"{prefix}.weight") + 1 weights.dtype = dtype new = cls(weight, eps) new.dtype = dtype return new # perform the multiplication in full precision and downcast after def forward(self, hidden_states, residual=None): if residual is not None: hidden_states += residual residual = hidden_states hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) hidden_states = hidden_states * self.weight return hidden_states.to(self.dtype), residual def load_attention(config, prefix: str, weights): if config.num_attention_heads != config.num_key_value_heads: return _load_gqa(config, prefix, weights) else: return TensorParallelColumnLinear.load_multi( config, prefixes=[f"{prefix}.q_proj", f"{prefix}.k_proj", f"{prefix}.v_proj"], dim=0, weights=weights, bias=False, ) def _load_gqa(config, prefix: str, weights): assert config.num_attention_heads % weights.process_group.size() == 0 weight = weights.get_multi_weights_col( prefixes=[f"{prefix}.q_proj", f"{prefix}.k_proj", f"{prefix}.v_proj"], dim=0, ) if isinstance(weight, UnquantizedWeight): weight.weight = weight.weight.to(dtype=weights.dtype).to(device=weights.device) head_size = config.head_dim num_heads = config.num_attention_heads // weights.process_group.size() num_key_value_heads = config.num_key_value_heads // weights.process_group.size() assert list(weight.weight.shape) == [ (num_heads + 2 * num_key_value_heads) * head_size, config.hidden_size, ], f"{list(weight.weight.shape)} != {[(num_heads + 2 * config.num_key_value_heads) * head_size, config.hidden_size]}" return TensorParallelColumnLinear(get_linear(weight, bias=None)) class FlashGemma2Attention(torch.nn.Module): def __init__( self, prefix: str, config, weights, layer_id, causal: bool, is_sliding: bool ): super().__init__() self.num_heads = config.num_attention_heads self.head_size = config.head_dim self.causal = causal if is_sliding: self.window_size = config.sliding_window else: self.window_size = -1 self.rotary_emb = PositionRotaryEmbedding.static( config=config, dim=self.head_size, base=config.rope_theta, device=weights.device, ) # self.softmax_scale = self.head_size**-0.5 self.softmax_scale = config.query_pre_attn_scalar**-0.5 if self.num_heads % weights.process_group.size() != 0: raise ValueError( f"`num_heads` must be divisible by `num_shards` (got `num_heads`: {self.num_heads} " f"and `num_shards`: {weights.process_group.size()}" ) self.num_heads = self.num_heads // weights.process_group.size() self.num_key_value_heads = ( config.num_key_value_heads // weights.process_group.size() ) self.softcap = config.attn_logit_softcapping query_key_value = load_attention(config, prefix, weights) self.query_key_value = TensorParallelMultiAdapterLinear.load( query_key_value, layer_id, ["q_proj", "k_proj", "v_proj"], sizes=[ self.head_size * config.num_attention_heads, self.head_size * config.num_key_value_heads, self.head_size * config.num_key_value_heads, ], process_group=weights.process_group, ) self.kv_scales = get_kv_scales(weights, f"{prefix}") o_proj = TensorParallelRowLinear.load( config, prefix=f"{prefix}.o_proj", weights=weights, bias=False, ) self.o_proj = TensorParallelAdapterRowLinear.load( o_proj, layer_id, "o_proj", process_group=weights.process_group, ) self.num_groups = self.num_heads // self.num_key_value_heads self.kv_head_mapping = torch.arange( 0, self.num_key_value_heads, dtype=torch.int32, device=weights.device ).repeat_interleave(self.num_groups) def forward( self, hidden_states, cos, sin, cu_seqlen_prefill, kv_cache, block_tables, slots, seqlen, max_s, adapter_data, ): qkv = self.query_key_value(hidden_states, adapter_data) query, kv = qkv.split( [ self.head_size * self.num_heads, 2 * self.head_size * self.num_key_value_heads, ], dim=1, ) query = query.view(-1, self.num_heads, self.head_size) kv = kv.view(-1, 2, self.num_key_value_heads, self.head_size) self.rotary_emb(query, torch.select(kv, dim=1, index=0), cos, sin) kv_cache.store( key=kv[:, 0], value=kv[:, 1], slots=slots, kv_scales=self.kv_scales, ) # Prefill if cu_seqlen_prefill is not None: # flash attention attn_output = attention( query=query, key=kv[:, 0], value=kv[:, 1], kv_cache=kv_cache, kv_scales=self.kv_scales, seqlen=seqlen, block_tables=block_tables, softmax_scale=self.softmax_scale, window_size_left=self.window_size, softcap=self.softcap, ) # Decode else: attn_output = paged_attention( query, kv_cache, self.kv_head_mapping, self.softmax_scale, block_tables, seqlen, max_s, softcap=self.softcap, kv_scales=self.kv_scales, window_size_left=self.window_size, ) return self.o_proj( attn_output.view(-1, self.num_heads * self.head_size), adapter_data ) class Gemma2MLP(nn.Module): def __init__(self, prefix, config, weights, layer_id): super().__init__() act = config.hidden_activation self.act = ( ACT2FN[act] if "gelu" not in act else lambda x: torch.nn.functional.gelu( x, approximate=( "tanh" if act in ["gelu_fast", "gelu_pytorch_tanh"] else "none" ), ) ) # Fuse gate and up proj gate_up_proj = TensorParallelColumnLinear.load_multi( config, prefixes=[f"{prefix}.gate_proj", f"{prefix}.up_proj"], weights=weights, dim=0, bias=False, ) self.gate_up_proj = TensorParallelMultiAdapterLinear.load( gate_up_proj, layer_id, ["gate_proj", "up_proj"], sizes=[ config.intermediate_size, config.intermediate_size, ], process_group=weights.process_group, ) down_proj = TensorParallelRowLinear.load( config, prefix=f"{prefix}.down_proj", weights=weights, bias=False, ) self.down_proj = TensorParallelAdapterRowLinear.load( down_proj, layer_id, "down_proj", process_group=weights.process_group, ) self.intermediate_size = ( config.intermediate_size // weights.process_group.size() ) def forward(self, hidden_states, adapter_data): gate_up_states = self.gate_up_proj(hidden_states, adapter_data) gate_up_states = gate_up_states.view(-1, 2, self.intermediate_size) return self.down_proj( self.act(gate_up_states[:, 0]) * gate_up_states[:, 1], adapter_data ) class FlashGemma2Layer(nn.Module): def __init__( self, prefix: str, config, weights, layer_id, causal: bool, is_sliding: bool ): super().__init__() self.self_attn = FlashGemma2Attention( prefix=f"{prefix}.self_attn", config=config, weights=weights, layer_id=layer_id, causal=causal, is_sliding=is_sliding, ) self.mlp = Gemma2MLP( prefix=f"{prefix}.mlp", config=config, weights=weights, layer_id=layer_id ) self.input_layernorm = Gemma2FastRMSNorm.load( prefix=f"{prefix}.input_layernorm", weights=weights, eps=config.rms_norm_eps ) self.post_attention_layernorm = Gemma2FastRMSNorm.load( prefix=f"{prefix}.post_attention_layernorm", weights=weights, eps=config.rms_norm_eps, ) self.pre_feedforward_layernorm = Gemma2FastRMSNorm.load( prefix=f"{prefix}.pre_feedforward_layernorm", weights=weights, eps=config.rms_norm_eps, ) self.post_feedforward_layernorm = Gemma2FastRMSNorm.load( prefix=f"{prefix}.post_feedforward_layernorm", weights=weights, eps=config.rms_norm_eps, ) def forward( self, hidden_states, residual, cos, sin, cu_seqlen_prefill, kv_cache, block_tables, slots, seqlen, max_s, adapter_data, ): normed_hidden_states, res = self.input_layernorm(hidden_states, residual) # Self Attention attn_output = self.self_attn( normed_hidden_states, cos, sin, cu_seqlen_prefill, kv_cache, block_tables, slots, seqlen, max_s, adapter_data, ) # faster post attention rms norm normed_attn_res_output, _ = self.post_attention_layernorm(attn_output) normed_attn_res_output = normed_attn_res_output + res res = normed_attn_res_output pre_normed, _ = self.pre_feedforward_layernorm(normed_attn_res_output) mlp_output = self.mlp(pre_normed, adapter_data) post_hidden_states, _ = self.post_feedforward_layernorm(mlp_output) return post_hidden_states, normed_attn_res_output class FlashGemma2Model(torch.nn.Module): def __init__(self, prefix: str, config, weights, causal: bool): super().__init__() process_group = weights.process_group self.tp_rank = process_group.rank() self.tp_world_size = process_group.size() self.layers = nn.ModuleList( [ FlashGemma2Layer( prefix=f"{prefix}.layers.{layer_id}", config=config, weights=weights, layer_id=layer_id, causal=causal, is_sliding=layer_id % 2 == 0, ) for layer_id in range(config.num_hidden_layers) ] ) self.norm = Gemma2FastRMSNorm.load( prefix=f"{prefix}.norm", weights=weights, eps=config.rms_norm_eps ) self.head_size = self.layers[0].self_attn.head_size self.num_heads = self.layers[0].self_attn.num_heads self.num_key_value_heads = self.layers[0].self_attn.num_key_value_heads def forward( self, inputs_embeds: torch.Tensor, position_ids: torch.Tensor, cu_seqlen_prefill: Optional[torch.Tensor], kv_cache: List[Tuple[torch.Tensor, torch.Tensor]], block_tables: torch.Tensor, slots: torch.Tensor, seqlen: Seqlen, max_s: int, adapter_data: Optional[torch.Tensor] = None, ) -> torch.Tensor: hidden_states = inputs_embeds # Get rotary cos and sin for this forward # Avoid to index in each layer cos, sin = self.layers[0].self_attn.rotary_emb.get_cos_sin( position_ids, max_s, hidden_states.dtype ) residual = None for i, layer in enumerate(self.layers): hidden_states, residual = layer( hidden_states, residual, cos, sin, cu_seqlen_prefill, kv_cache[i], block_tables, slots, seqlen, max_s, adapter_data, ) hidden_states, _ = self.norm(hidden_states, residual) return hidden_states class FlashGemma2ForCausalLM(torch.nn.Module): def __init__(self, prefix: str, config, weights, *, causal: bool = True): super().__init__() embed_norm = config.hidden_size**0.5 if not prefix: prefix = "model" else: prefix = f"{prefix}.model" self.embed_tokens = TensorParallelEmbedding( prefix=f"{prefix}.embed_tokens", weights=weights ) self.embed_tokens.weight *= embed_norm self.model = FlashGemma2Model( prefix=prefix, config=config, weights=weights, causal=causal ) self.lm_head = SpeculativeHead.load( prefix=( f"{prefix}.embed_tokens" if config.tie_word_embeddings else f"{prefix}.lm_head" ), config=config, weights=weights, ) self.softcap = config.final_logit_softcapping assert isinstance(self.softcap, float) def forward( self, input_ids: torch.Tensor, position_ids: torch.Tensor, cu_seqlen_prefill: Optional[torch.Tensor], kv_cache: List[Tuple[torch.Tensor, torch.Tensor]], block_tables: torch.Tensor, slots: torch.Tensor, seqlen: Seqlen, max_s: int, prefill_cache_indices: Optional[torch.Tensor], lm_head_indices: Optional[torch.Tensor] = None, adapter_data: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: input_embeds = self.embed_tokens(input_ids) hidden_states = self.model( input_embeds, position_ids, cu_seqlen_prefill, kv_cache, block_tables, slots, seqlen, max_s, adapter_data, ) if lm_head_indices is not None: hidden_states = hidden_states[lm_head_indices] logits, speculative_logits = self.lm_head(hidden_states) logits /= self.softcap logits = torch.tanh(logits) logits *= self.softcap return logits, speculative_logits
text-generation-inference/server/text_generation_server/models/custom_modeling/flash_gemma2_modeling.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/models/custom_modeling/flash_gemma2_modeling.py", "repo_id": "text-generation-inference", "token_count": 9405 }
321
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # This file was automatically generated from src/transformers/models/gemma3/modular_gemma3.py. # Do NOT edit this file manually as any edits will be overwritten by the generation of # the file from the modular. If any change should be done, please apply the change to the # modular_gemma3.py file directly. One of our CI enforces this. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # coding=utf-8 # Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved. # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from transformers.configuration_utils import PretrainedConfig from transformers.modeling_rope_utils import rope_config_validation from transformers.utils import logging from transformers import SiglipVisionConfig logger = logging.get_logger(__name__) class Gemma3TextConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Gemma3Model`]. It is used to instantiate a Gemma3 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Gemma3-4B. e.g. [google/gemma-3-4b](https://huggingface.co/google/gemma-3-4b) Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 262144): Vocabulary size of the Gemma3 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Gemma3Model`] hidden_size (`int`, *optional*, defaults to 2304): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 9216): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 26): Number of hidden layers in the Transformer decoder. num_attention_heads (`int`, *optional*, defaults to 8): Number of attention heads for each attention layer in the Transformer decoder. num_key_value_heads (`int`, *optional*, defaults to 4): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `num_attention_heads`. head_dim (`int`, *optional*, defaults to 256): The attention head dimension. sliding_window (`int`, *optional*, defaults to 4096): in Gemma3, every other layer uses sliding window attention. This is the size of the sliding window. query_pre_attn_scalar (`float`, *optional*): The scaling factor used on the attention scores, not that rope_theta (`float`, *optional*, defaults to 1000000.0): The base period of the RoPE embeddings used for global attention. rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. Expected contents: `rope_type` (`str`): The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. `factor` (`float`, *optional*): Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length. `original_max_position_embeddings` (`int`, *optional*): Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during pretraining. `attention_factor` (`float`, *optional*): Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention computation. If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value. `beta_fast` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear ramp function. If unspecified, it defaults to 32. `beta_slow` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear ramp function. If unspecified, it defaults to 1. `short_factor` (`List[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to short contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `long_factor` (`List[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to long contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `low_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE `high_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE rope_local_base_freq (float, *optional*, defaults to 10000.0): The base period of the RoPE embeddings for local attention. sliding_window_pattern (`int`, *optional*, defaults to 6): Pattern for the sliding window attention. rms_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the rms normalization layers. hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`): The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"` if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function. pad_token_id (`int`, *optional*, defaults to 0): Padding token id. eos_token_id (`int`, *optional*, defaults to 1): End of stream token id. bos_token_id (`int`, *optional*, defaults to 2): Beginning of stream token id. tie_word_embeddings (`bool`, *optional*, defaults to `True`): Whether to tie weight embeddings max_position_embeddings (`int`, *optional*, defaults to 131072): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. attention_bias (`bool`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. final_logit_softcapping (`bool`, *optional*, defaults to `True`): Whether to apply logit softcapping or nor attn_logit_softcapping (`float`, *optional*, defaults to 50.0): Scaling factor when applying tanh soft-capping on the attention scorexs. cache_implementation (`str`, *optional*, defaults to `"hybrid"`): The cache type to be used with `generate`. ```python >>> from transformers import Gemma3Model, Gemma3TextConfig >>> # Initializing a Gemma3 gemma3-4b style configuration >>> configuration = Gemma3Config() >>> # Initializing a model from the gemma3-4b style configuration >>> model = Gemma3Model(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "gemma3_text" def __init__( self, vocab_size: int = 262_144, hidden_size: int = 2304, intermediate_size: int = 9216, num_hidden_layers: int = 26, num_attention_heads: int = 8, num_key_value_heads: int = 4, head_dim: int = 256, sliding_window: int = 4096, query_pre_attn_scalar: Optional[float] = 256, rope_theta: float = 1_000_000.0, rope_scaling=None, rope_local_base_freq: float = 10_000.0, sliding_window_pattern: int = 6, rms_norm_eps: float = 1e-6, hidden_activation: str = "gelu_pytorch_tanh", pad_token_id: int = 0, eos_token_id: int = 1, bos_token_id: int = 2, tie_word_embeddings: bool = True, max_position_embeddings: int = 131_072, initializer_range: float = 0.02, attention_bias: bool = False, attention_dropout: float = 0.0, use_cache: bool = True, final_logit_softcapping=None, attn_logit_softcapping=None, cache_implementation: str = "hybrid", **kwargs, ): super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, ) self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.head_dim = head_dim self.num_key_value_heads = num_key_value_heads self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self.rope_local_base_freq = rope_local_base_freq # For configuring HybridCache to work with 5:1 attention pattern self.sliding_window_pattern = sliding_window_pattern self.attention_bias = attention_bias self.attention_dropout = attention_dropout self.hidden_activation = hidden_activation self.query_pre_attn_scalar = query_pre_attn_scalar self.sliding_window = sliding_window self.final_logit_softcapping = final_logit_softcapping self.attn_logit_softcapping = attn_logit_softcapping self.cache_implementation = cache_implementation rope_config_validation(self) class Gemma3Config(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Gemma3ForConditionalGeneration`]. It is used to instantiate an Gemma3ForConditionalGeneration according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the PaliGemma-2B. e.g. [google/gemma-3-4b](https://huggingface.co/google/gemma-3-4b) Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: text_config (`Union[Gemma3TextConfig, dict]`, *optional*): The config object of the text backbone. vision_config (`Union[AutoConfig, dict]`, *optional*): Custom vision config or dict. mm_tokens_per_image (`int`, *optional*, defaults to 256): The number of tokens per image embedding. boi_token_index (`int`, *optional*, defaults to 255999): The begin-of-image token index to wrap the image prompt. eoi_token_index (`int`, *optional*, defaults to 256000): The end-of-image token index to wrap the image prompt. image_token_index (`int`, *optional*, defaults to 262144): The image token index to encode the image prompt. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. Example: ```python >>> from transformers import Gemma3ForConditionalGeneration, Gemma3Config, SiglipVisionConfig, Gemma3TextConfig >>> # Initializing a Siglip-like vision config >>> vision_config = SiglipVisionConfig() >>> # Initializing a Gemma3 Text config >>> text_config = Gemma3TextConfig() >>> # Initializing a Gemma3 gemma-3-4b style configuration >>> configuration = Gemma3Config(vision_config, text_config) >>> # Initializing a model from the gemma-3-4b style configuration >>> model = Gemma3TextConfig(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "gemma3" sub_configs = { "text_config": Gemma3TextConfig, "vision_config": SiglipVisionConfig, } def __init__( self, text_config: Optional[Gemma3TextConfig] = None, vision_config: Optional[SiglipVisionConfig] = None, mm_tokens_per_image: int = 256, boi_token_index: int = 255_999, eoi_token_index: int = 256_000, image_token_index: int = 262_144, initializer_range: float = 0.02, **kwargs, ): if text_config is None: text_config = Gemma3TextConfig() logger.info( "text_config is None, using default Gemma3TextConfig vision config." ) elif isinstance(text_config, dict): text_config = Gemma3TextConfig(**text_config) if isinstance(vision_config, dict): vision_config = SiglipVisionConfig(**vision_config) else: vision_config = SiglipVisionConfig() logger.info( "vision_config is None or incompatible with Gemma3VisionConfig intialization. Gemma3 will be limited " "to text tasks." ) self.text_config = text_config self.vision_config = vision_config self.mm_tokens_per_image = mm_tokens_per_image self.boi_token_index = boi_token_index self.eoi_token_index = eoi_token_index self.image_token_index = image_token_index self.initializer_range = initializer_range super().__init__(**kwargs) __all__ = ["Gemma3Config", "Gemma3TextConfig"]
text-generation-inference/server/text_generation_server/models/custom_modeling/gemma3/configuration_gemma3.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/models/custom_modeling/gemma3/configuration_gemma3.py", "repo_id": "text-generation-inference", "token_count": 6692 }
322
# coding=utf-8 # Copyright 2022 EleutherAI The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PyTorch GPTNeoX model.""" from typing import Optional, Tuple, Union import os import torch import torch.distributed import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from transformers.activations import ACT2FN from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, ) from transformers.modeling_utils import PreTrainedModel from text_generation_server.layers import ( TensorParallelColumnLinear, TensorParallelEmbedding, TensorParallelRowLinear, SpeculativeHead, ) CUSTOM_KERNELS_ENABLED = False if ( torch.cuda.is_available() and not os.environ.get("DISABLE_CUSTOM_KERNELS", "False") == "True" ): try: from custom_kernels import fused_attention_cuda CUSTOM_KERNELS_ENABLED = True except ImportError: pass def make_causal_mask( input_ids_shape: torch.Size, device: torch.device, past_key_values_length: int ) -> torch.BoolTensor: """ Make causal mask used for self-attention. """ batch_size, target_length = input_ids_shape mask = torch.ones( (target_length, target_length + past_key_values_length), dtype=torch.bool, device=device, ) mask = mask.triu(1 + past_key_values_length) expanded_mask = mask.unsqueeze(0).expand( batch_size, target_length, target_length + past_key_values_length ) return expanded_mask def expand_mask(mask: torch.Tensor, tgt_length: int) -> torch.BoolTensor: """ Expands attention_mask from `[batch_size, src_length]` to `[batch_size, 1, tgt_length, src_length]`. """ batch_size, src_length = mask.shape tgt_length = tgt_length if tgt_length is not None else src_length expanded_mask = ~(mask[:, None, :].to(torch.bool)) return expanded_mask.expand(batch_size, tgt_length, src_length) def prepare_attn_mask( attention_mask: torch.Tensor, input_shape: Tuple[int, int], past_key_values_length: int, ) -> torch.BoolTensor: # create causal mask # [batch_size, seq_length] -> [batch_size, tgt_length, src_length] combined_attention_mask = None device = attention_mask.device _, src_length = input_shape if src_length > 1: combined_attention_mask = make_causal_mask( input_shape, device=device, past_key_values_length=past_key_values_length ) # [batch_size, seq_length] -> [batch_size, tgt_length, src_length] expanded_attn_mask = expand_mask(attention_mask, tgt_length=src_length) combined_attention_mask = ( expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask ) return combined_attention_mask class GPTNeoXPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ class GPTNeoXAttention(nn.Module): def __init__(self, config, prefix, weights): super().__init__() self.num_attention_heads = config.num_attention_heads self.hidden_size = config.hidden_size self.head_size = self.hidden_size // self.num_attention_heads self.rotary_ndims = int(self.head_size * config.rotary_pct) # ??? TODO # self.register_buffer( # "bias", # torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view( # 1, 1, max_positions, max_positions # ), # ) # self.register_buffer("masked_bias", torch.tensor(-1e9)) self.rotary_emb = RotaryEmbedding( self.rotary_ndims, config.max_position_embeddings, base=config.rotary_emb_base, ) self.rotary_emb.inv_freq = nn.Parameter( weights.get_tensor(f"{prefix}.rotary_emb.inv_freq") ) self.inv_norm_factor = 1.0 / torch.sqrt( torch.tensor(self.head_size, dtype=torch.float32) ).to(torch.get_default_dtype()) if self.num_attention_heads % weights.process_group.size() != 0: raise ValueError( f"`num_attention_heads` must be divisible by `num_shards` " f"(got `num_attention_heads`: {self.num_attention_heads} " f"and `num_shards`: {weights.process_group.size()}" ) self.num_attention_heads = ( self.num_attention_heads // weights.process_group.size() ) self.query_key_value = TensorParallelColumnLinear.load( config, prefix=f"{prefix}.query_key_value", weights=weights, bias=True ) self.dense = TensorParallelRowLinear.load( config, prefix=f"{prefix}.dense", weights=weights, bias=True ) def forward( self, hidden_states, position_ids, attention_mask, head_mask=None, layer_past=None, use_cache=False, output_attentions=False, ): has_layer_past = layer_past is not None # Compute QKV # Attention heads [batch, seq_len, hidden_size] # --> [batch, seq_len, (np * 3 * head_size)] qkv = self.query_key_value(hidden_states) # [batch, seq_len, (num_heads * 3 * head_size)] # --> [batch, seq_len, num_heads, 3 * head_size] new_qkv_shape = qkv.size()[:-1] + (self.num_attention_heads, 3 * self.head_size) qkv = qkv.view(*new_qkv_shape).permute(0, 2, 1, 3) # [batch, seq_len, num_attention_heads, 3 * head_size] --> 3 [batch, num_attention_heads, seq_len, head_size] query, key, value = qkv.split(self.head_size, -1) # Compute token offset for rotary embeddings (when decoding) seq_len = key.shape[-2] if has_layer_past: seq_len += layer_past[0].shape[-2] # Compute rotary embeddings on rotary_ndims query_rot = query[..., : self.rotary_ndims] key_rot = key[..., : self.rotary_ndims] query_rot, key_rot = self.rotary_emb(query_rot, key_rot, position_ids, seq_len) query[..., : self.rotary_ndims] = query_rot key[..., : self.rotary_ndims] = key_rot if CUSTOM_KERNELS_ENABLED: attn_output, present, attn_weights = fused_attention_cuda.forward( query, key, value, layer_past, attention_mask, head_mask, self.inv_norm_factor, self.num_attention_heads, use_cache, ) else: # Cache QKV values if has_layer_past: past_key = layer_past[0] past_value = layer_past[1] key = torch.cat((past_key, key), dim=-2) value = torch.cat((past_value, value), dim=-2) present = (key, value) if use_cache else None # Compute attention attn_output, attn_weights = self._attn( query, key, value, attention_mask, head_mask ) # Reshape outputs attn_output = self._merge_heads( attn_output, self.num_attention_heads, self.head_size ) attn_output = self.dense(attn_output) outputs = (attn_output, present) if output_attentions: outputs += (attn_weights,) return outputs @classmethod def _split_heads(cls, tensor, num_attention_heads, attn_head_size): """ Splits hidden dim into attn_head_size and num_attention_heads """ # tensor: [bs, seq_len, hidden_size] new_shape = tensor.size()[:-1] + (num_attention_heads, attn_head_size) # -> [bs, seq_len, num_attention_heads, attn_head_size] tensor = tensor.view(new_shape) # -> [bs, num_attention_heads, seq_len, attn_head_size] tensor = tensor.permute(0, 2, 1, 3) return tensor @classmethod def _merge_heads(cls, tensor, num_attention_heads, attn_head_size): """ Merges attn_head_size dim and num_attn_heads dim into hidden dim """ # tensor [bs, num_attention_heads, seq_len, attn_head_size] tensor = tensor.permute(0, 2, 1, 3).contiguous() # -> [bs, seq_len, num_attention_heads, attn_head_size] tensor = tensor.view( tensor.size(0), tensor.size(1), num_attention_heads * attn_head_size ) # -> [bs, seq_len, hidden_size] return tensor def _attn(self, query, key, value, attention_mask=None, head_mask=None): # q, k, v: [bs, num_attention_heads, seq_len, attn_head_size] # compute causal mask from causal mask buffer batch_size, num_attention_heads, query_length, attn_head_size = query.size() key_length = key.size(-2) query = query.reshape( batch_size * num_attention_heads, query_length, attn_head_size ) key = key.reshape(batch_size * num_attention_heads, key_length, attn_head_size) attn_scores = torch.zeros( 1, dtype=query.dtype, device=key.device, ).expand(batch_size * num_attention_heads, query_length, key_length) attn_scores = torch.baddbmm( attn_scores, query, key.transpose(1, 2), beta=1.0, alpha=self.inv_norm_factor, ) # cast attention scores to fp32, compute scaled softmax and cast back to initial dtype - [batch_size, num_heads, q_length, kv_length] input_dtype = attn_scores.dtype if input_dtype in [torch.float16, torch.bfloat16]: attn_scores = attn_scores.to(torch.float) attn_scores = torch.where( attention_mask, torch.finfo(attn_scores.dtype).min, attn_scores ) attn_scores = attn_scores.view( batch_size, num_attention_heads, query_length, key_length ) attn_weights = nn.functional.softmax(attn_scores, dim=-1) attn_weights = attn_weights.to(value.dtype) # Mask heads if we want to if head_mask is not None: attn_weights = attn_weights * head_mask attn_output = torch.matmul(attn_weights, value) return attn_output, attn_weights class RotaryEmbedding(torch.nn.Module): def __init__(self, dim, max_position_embeddings, base=10000, device=None): super().__init__() self.true_inv_freq = 1.0 / ( base ** (torch.arange(0, dim, 2).float().to(device) / dim) ) self.register_buffer("inv_freq", self.true_inv_freq) # Build here to make `torch.jit.trace` work. self.max_seq_len_cached = max_position_embeddings self.cos_cached = None self.sin_cached = None @staticmethod def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) @staticmethod def _create_cos_sin(inv_freq, max_position_embeddings, dtype, device): t = torch.arange( max_position_embeddings, device=inv_freq.device, dtype=inv_freq.dtype ) freqs = torch.einsum("i,j->ij", t, inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) return emb.cos().to(device).to(dtype), emb.sin().to(device).to(dtype) def forward(self, q, k, position_ids, seq_len=None): # x: [bs, num_attention_heads, seq_len, head_size] if ( seq_len > self.max_seq_len_cached or self.cos_cached is None or self.sin_cached is None ): if seq_len > self.max_seq_len_cached: self.max_seq_len_cached = seq_len self.cos_cached, self.sin_cached = self._create_cos_sin( self.true_inv_freq, self.max_seq_len_cached, q.dtype, q.device ) return rotary_forward(q, k, self.cos_cached, self.sin_cached, position_ids) @torch.jit.script def rotary_forward(q, k, cos, sin, position_ids): cos = cos[position_ids].unsqueeze(1) sin = sin[position_ids].unsqueeze(1) chunk_size = q.shape[-1] // 2 q1, q2 = q.split(chunk_size, -1) q_rotated = torch.cat((-q2, q1), dim=-1) k1, k2 = k.split(chunk_size, -1) k_rotated = torch.cat((-k2, k1), dim=-1) q_embed = (q * cos) + (q_rotated * sin) k_embed = (k * cos) + (k_rotated * sin) return q_embed, k_embed class GPTNeoXMLP(nn.Module): def __init__(self, config, prefix, weights): super().__init__() self.act = ( ACT2FN[config.hidden_act] if "gelu_fast" not in config.hidden_act else lambda x: torch.nn.functional.gelu(x, approximate="tanh") ) self.dense_h_to_4h = TensorParallelColumnLinear.load( config, prefix=f"{prefix}.dense_h_to_4h", weights=weights, bias=True ) self.dense_4h_to_h = TensorParallelRowLinear.load( config, prefix=f"{prefix}.dense_4h_to_h", weights=weights, bias=True ) def forward(self, hidden_states): hidden_states = self.dense_h_to_4h(hidden_states) hidden_states = self.act(hidden_states) hidden_states = self.dense_4h_to_h(hidden_states) return hidden_states class GPTNeoXLayer(nn.Module): def __init__(self, layer_id, prefix: str, config, weights): super().__init__() self.use_parallel_residual = config.use_parallel_residual self.input_layernorm = nn.LayerNorm.load( prefix=f"{prefix}.layers.{layer_id}.input_layernorm", weights=weights, eps=config.layer_norm_eps, ) self.post_attention_layernorm = nn.LayerNorm.load( prefix=f"{prefix}.layers.{layer_id}.post_attention_layernorm", weights=weights, eps=config.layer_norm_eps, ) self.attention = GPTNeoXAttention( config, prefix=f"{prefix}.layers.{layer_id}.attention", weights=weights ) self.mlp = GPTNeoXMLP( config, prefix=f"{prefix}.layers.{layer_id}.mlp", weights=weights ) def forward( self, hidden_states, position_ids, attention_mask=None, head_mask=None, use_cache=False, layer_past=None, output_attentions=False, ): attention_layer_outputs = self.attention( self.input_layernorm(hidden_states), attention_mask=attention_mask, position_ids=position_ids, layer_past=layer_past, head_mask=head_mask, use_cache=use_cache, output_attentions=output_attentions, ) attn_output = attention_layer_outputs[ 0 ] # output_attn: attn_output, present, (attn_weights) outputs = attention_layer_outputs[1:] if self.use_parallel_residual: # pseudocode: # x = x + attn(ln1(x)) + mlp(ln2(x)) mlp_output = self.mlp(self.post_attention_layernorm(hidden_states)) hidden_states = mlp_output + attn_output + hidden_states else: # pseudocode: # x = x + attn(ln1(x)) # x = x + mlp(ln2(x)) attn_output = attn_output + hidden_states mlp_output = self.mlp(self.post_attention_layernorm(attn_output)) hidden_states = mlp_output + attn_output if use_cache: outputs = ( hidden_states, ) + outputs # hidden_states, present, (attn_weights) else: outputs = (hidden_states,) + outputs[1:] # hidden_states, (attn_weights) return outputs class GPTNeoXModel(GPTNeoXPreTrainedModel): def __init__(self, prefix: str, config, weights): super().__init__(config) self.config = config self.num_attention_heads = config.num_attention_heads self.embed_in = TensorParallelEmbedding( prefix=f"{prefix}.embed_in", weights=weights ) self.layers = nn.ModuleList( [ GPTNeoXLayer(layer_id, prefix, config, weights) for layer_id in range(config.num_hidden_layers) ] ) self.final_layer_norm = nn.LayerNorm.load( prefix=f"{prefix}.final_layer_norm", weights=weights, eps=config.layer_norm_eps, ) self.tp_world_size = weights.process_group.size() def forward( self, input_ids: Optional[torch.LongTensor] = None, position_ids=None, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPast]: r""" past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). """ output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) use_cache = use_cache if use_cache is not None else self.config.use_cache if input_ids is not None and inputs_embeds is not None: raise ValueError( "You cannot specify both input_ids and inputs_embeds at the same time" ) elif input_ids is not None: input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") batch_size, seq_length = input_shape if past_key_values is None: past_length = 0 past_key_values = tuple([None] * self.config.num_hidden_layers) else: past_length = past_key_values[0][0].size(-2) if position_ids is None: device = input_ids.device if input_ids is not None else inputs_embeds.device position_ids = torch.arange( past_length, seq_length + past_length, dtype=torch.long, device=device ) position_ids = position_ids.unsqueeze(0).view(-1, seq_length) else: position_ids = position_ids.view(-1, seq_length).long() if inputs_embeds is None: inputs_embeds = self.embed_in(input_ids) hidden_states = inputs_embeds # Attention mask. seq_length_with_past = seq_length past_key_values_length = 0 if past_key_values[0] is not None: past_key_values_length = past_key_values[0][0].shape[-1] seq_length_with_past = seq_length_with_past + past_key_values_length if attention_mask is None: attention_mask = torch.ones( (batch_size, seq_length_with_past), device=hidden_states.device ) else: attention_mask = attention_mask.to(hidden_states.device) causal_mask = prepare_attn_mask( attention_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length, ) assert self.num_attention_heads % self.tp_world_size == 0 block_size = self.num_attention_heads // self.tp_world_size causal_mask = torch.repeat_interleave(causal_mask, block_size, dim=0) # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) presents = () if use_cache else None all_attentions = () if output_attentions else None all_hidden_states = () if output_hidden_states else None for i, (layer, layer_past) in enumerate(zip(self.layers, past_key_values)): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) outputs = layer( hidden_states, position_ids=position_ids, attention_mask=causal_mask, head_mask=head_mask[i], layer_past=layer_past, use_cache=use_cache, output_attentions=output_attentions, ) hidden_states = outputs[0] if use_cache is True: presents = presents + (outputs[1],) if output_attentions: all_attentions = all_attentions + (outputs[2 if use_cache else 1],) hidden_states = self.final_layer_norm(hidden_states) # Add last hidden state if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [hidden_states, presents, all_hidden_states, all_attentions] if v is not None ) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_attentions, ) class GPTNeoxForCausalLM(GPTNeoXPreTrainedModel): _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] def __init__(self, prefix: str, config, weights): super().__init__(config) if not prefix: prefix = "gpt_neox" else: prefix = f"{prefix}.gpt_neox" self.gpt_neox = GPTNeoXModel(prefix, config, weights) self.embed_out = SpeculativeHead.load( config, prefix="embed_out", weights=weights ) def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, position_ids: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, CausalLMOutputWithPast]: r""" past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional tensors are only required when the model is used as a decoder in a Sequence to Sequence model. Contains pre-computed hidden-states (key and values in the self-attention blocks that can be used (see `past_key_values` input) to speed up sequential decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). Returns: Example: ```python >>> from transformers import AutoTokenizer, GPTNeoXForCausalLM, GPTNeoXConfig >>> import torch >>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b") >>> config = GPTNeoXConfig.from_pretrained("EleutherAI/gpt-neox-20b") >>> config.is_decoder = True >>> model = GPTNeoXForCausalLM.from_pretrained("EleutherAI/gpt-neox-20b", config=config) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> prediction_logits = outputs.logits ```""" return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) outputs = self.gpt_neox( input_ids, attention_mask=attention_mask, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = outputs[0] lm_logits, speculative_logits = self.embed_out(hidden_states) lm_loss = None if labels is not None: # move labels to correct device to enable model parallelism labels = labels.to(lm_logits.device) # we are doing next-token prediction; shift prediction scores and input ids by one shift_logits = lm_logits[:, :-1, :].contiguous() labels = labels[:, 1:].contiguous() loss_fct = CrossEntropyLoss() lm_loss = loss_fct( shift_logits.view(-1, shift_logits.size(-1)), labels.view(-1) ) if not return_dict: output = (lm_logits,) + outputs[1:] return ((lm_loss,) + output) if lm_loss is not None else output return ( CausalLMOutputWithPast( loss=lm_loss, logits=lm_logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ), speculative_logits, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs, ): input_shape = input_ids.shape # cut decoder_input_ids if past is used if past_key_values and past_key_values[0] is not None: input_ids = input_ids[:, -1:] position_ids = kwargs.get("position_ids", None) if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if past_key_values: position_ids = position_ids[:, -1].unsqueeze(-1) # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly if attention_mask is None: attention_mask = input_ids.new_ones(input_shape) # if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and past_key_values is None: model_inputs = {"inputs_embeds": inputs_embeds} else: model_inputs = {"input_ids": input_ids} model_inputs.update( { "attention_mask": attention_mask, "past_key_values": past_key_values, "position_ids": position_ids, } ) return model_inputs def _reorder_cache(self, past_key_values, beam_idx): reordered_past = () for layer_past in past_key_values: reordered_past += ( tuple( past_state.index_select(0, beam_idx) for past_state in layer_past[:2] ) + layer_past[2:], ) return reordered_past
text-generation-inference/server/text_generation_server/models/custom_modeling/neox_modeling.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/models/custom_modeling/neox_modeling.py", "repo_id": "text-generation-inference", "token_count": 14228 }
323
import torch import torch.distributed import time from dataclasses import dataclass from opentelemetry import trace from transformers import ( AutoTokenizer, AutoModelForSeq2SeqLM, PreTrainedTokenizerBase, AutoConfig, ) from typing import Optional, Tuple, List, Type, Dict from text_generation_server.utils.import_utils import SYSTEM from text_generation_server.utils import ( initialize_torch_distributed, weight_files, Weights, ) from text_generation_server.utils.chunks import concat_text_chunks from text_generation_server.utils.quantization import get_loader from text_generation_server.utils.tokens import batch_top_tokens from text_generation_server.models import Model from text_generation_server.models.types import ( GeneratedText, Batch, Generation, Tokens, ) from text_generation_server.pb import generate_pb2 from text_generation_server.utils import NextTokenChooser, StoppingCriteria, Sampling tracer = trace.get_tracer(__name__) @dataclass class Seq2SeqLMBatch(Batch): batch_id: int requests: List[generate_pb2.Request] requests_idx_mapping: Dict[int, int] # Encoder values input_ids: Optional[torch.Tensor] attention_mask: torch.Tensor # Decoder values decoder_input_ids: torch.Tensor decoder_attention_mask: Optional[torch.Tensor] encoder_last_hidden_state: Optional[torch.Tensor] # All tokens all_decoder_input_ids: List[torch.Tensor] # Seq2SeqLM keeps track of both encoder and decoder attention keys and values past_key_values: Optional[List[Tuple]] # Lengths of all generations present in the batch input_lengths: List[int] decoder_input_lengths: List[int] prefix_offsets: List[int] read_offsets: List[int] # Generation helpers next_token_choosers: List[NextTokenChooser] stopping_criterias: List[StoppingCriteria] top_n_tokens: List[int] top_n_tokens_tensor: torch.Tensor # Metadata used for padding max_input_length: int max_decoder_input_length: int padding_right_offset: int # Maximum number of tokens this batch will grow to max_tokens: int def to_pb(self) -> generate_pb2.CachedBatch: """Convert a Seq2SeqLMBatch to a text_generation_server.v1.CachedBatch protobuf""" return generate_pb2.CachedBatch( id=self.batch_id, request_ids=[r.id for r in self.requests], size=len(self), max_tokens=self.max_tokens, current_tokens=len(self.decoder_input_ids), ) @classmethod def from_pb( cls, pb: generate_pb2.Batch, tokenizer: PreTrainedTokenizerBase, dtype: torch.dtype, device: torch.device, ) -> "Seq2SeqLMBatch": """Convert a text_generation_server.v1.Batch protobuf to a Seq2SeqLMBatch""" inputs = [] next_token_choosers = [] stopping_criterias = [] top_n_tokens = [] decoder_input_lengths = [] prefix_offsets = [] read_offsets = [] requests_idx_mapping = {} # Parse batch max_truncation = 0 padding_right_offset = 0 max_decode_tokens = 0 for i, r in enumerate(pb.requests): inputs.append(concat_text_chunks(r.input_chunks.chunks)) requests_idx_mapping[r.id] = i decoder_input_lengths.append(1) next_token_choosers.append( NextTokenChooser.from_pb(r.parameters, device, tokenizer) ) stopping_criteria = StoppingCriteria.from_pb( r.stopping_parameters, tokenizer ) stopping_criterias.append(stopping_criteria) top_n_tokens.append(r.top_n_tokens) max_truncation = max(max_truncation, r.truncate) max_decode_tokens += stopping_criteria.max_new_tokens padding_right_offset = max( padding_right_offset, stopping_criteria.max_new_tokens ) # Tokenize batch tokenized_inputs = tokenizer( inputs, return_tensors="pt", padding=True, return_token_type_ids=False, truncation=True, max_length=max_truncation, ).to(device) input_lengths = tokenized_inputs["attention_mask"].sum(1) max_input_length = input_lengths.max() # Decoder sequence only contains the bos_token decoder_input_ids = ( torch.tensor(tokenizer.bos_token_id, device=device) .repeat(len(pb.requests)) .view(-1, 1) ) for _ in pb.requests: prefix_offsets.append(0) read_offsets.append(1) all_decoder_input_ids = decoder_input_ids.view(-1).split(1) top_n_tokens_tensor = torch.tensor( top_n_tokens, device=device, dtype=torch.int64 ) max_tokens = len(inputs) * (max_input_length + max_decode_tokens) return cls( batch_id=pb.id, requests=pb.requests, requests_idx_mapping=requests_idx_mapping, input_ids=tokenized_inputs["input_ids"], attention_mask=tokenized_inputs["attention_mask"], decoder_input_ids=decoder_input_ids, all_decoder_input_ids=list(all_decoder_input_ids), decoder_attention_mask=None, encoder_last_hidden_state=None, past_key_values=None, input_lengths=input_lengths.tolist(), decoder_input_lengths=decoder_input_lengths, prefix_offsets=prefix_offsets, read_offsets=read_offsets, next_token_choosers=next_token_choosers, stopping_criterias=stopping_criterias, top_n_tokens=top_n_tokens, top_n_tokens_tensor=top_n_tokens_tensor, max_input_length=max_input_length.item(), max_decoder_input_length=1, padding_right_offset=padding_right_offset, max_tokens=max_tokens, ) @tracer.start_as_current_span("filter") def filter(self, request_ids: List[int]) -> Optional["Seq2SeqLMBatch"]: if len(request_ids) == 0: raise ValueError("Batch must have at least one request") if len(request_ids) == len(self): return self keep_indices = [] # New values after filtering requests_idx_mapping = {} requests = [] input_lengths = [] decoder_input_lengths = [] prefix_offsets = [] read_offsets = [] all_decoder_input_ids = [] next_token_choosers = [] stopping_criterias = [] top_n_tokens = [] max_input_length = 0 max_decoder_input_length = 0 padding_right_offset = 0 total_remaining_decode_tokens = 0 for i, request_id in enumerate(request_ids): idx = self.requests_idx_mapping[request_id] requests_idx_mapping[request_id] = i keep_indices.append(idx) requests.append(self.requests[idx]) prefix_offsets.append(self.prefix_offsets[idx]) read_offsets.append(self.read_offsets[idx]) all_decoder_input_ids.append(self.all_decoder_input_ids[idx]) request_input_length = self.input_lengths[idx] input_lengths.append(request_input_length) max_input_length = max(max_input_length, request_input_length) request_decoder_input_length = self.decoder_input_lengths[idx] decoder_input_lengths.append(request_decoder_input_length) max_decoder_input_length = max( max_decoder_input_length, request_decoder_input_length ) next_token_choosers.append(self.next_token_choosers[idx]) stopping_criteria = self.stopping_criterias[idx] stopping_criterias.append(stopping_criteria) top_n_tokens.append(self.top_n_tokens[idx]) remaining_decode_tokens = ( stopping_criteria.max_new_tokens - stopping_criteria.current_tokens ) total_remaining_decode_tokens += remaining_decode_tokens padding_right_offset = max(padding_right_offset, remaining_decode_tokens) # Apply indices to input_ids, attention mask, past key values and other items that need to be cached self.decoder_input_ids = self.decoder_input_ids[keep_indices] self.attention_mask = self.attention_mask[keep_indices, -max_input_length:] if self.decoder_attention_mask is not None: self.decoder_attention_mask = self.decoder_attention_mask[ keep_indices, -(self.padding_right_offset + max_decoder_input_length) : ( self.decoder_attention_mask.shape[1] - self.padding_right_offset ) + padding_right_offset, ] self.encoder_last_hidden_state = self.encoder_last_hidden_state[ keep_indices, -max_input_length: ] # Ensure that past_key_values tensors can be updated in-place if type(self.past_key_values[0]) is tuple: self.past_key_values = [ [t for t in layer] for layer in self.past_key_values ] decoder_past_seq_len = max_decoder_input_length - 1 for layer in self.past_key_values: layer[0] = layer[0][keep_indices, :, -decoder_past_seq_len:] layer[1] = layer[1][keep_indices, :, -decoder_past_seq_len:] layer[2] = layer[2][keep_indices, :, -max_input_length:] layer[3] = layer[3][keep_indices, :, -max_input_length:] top_n_tokens_tensor = self.top_n_tokens_tensor[keep_indices] max_tokens = ( len(request_ids) * (max_input_length + max_decoder_input_length) + remaining_decode_tokens ) self.requests = requests self.requests_idx_mapping = requests_idx_mapping self.input_ids = None self.all_decoder_input_ids = all_decoder_input_ids self.input_lengths = input_lengths self.decoder_input_lengths = decoder_input_lengths self.prefix_offsets = prefix_offsets self.read_offsets = read_offsets self.next_token_choosers = next_token_choosers self.stopping_criterias = stopping_criterias self.top_n_tokens = top_n_tokens self.top_n_tokens_tensor = top_n_tokens_tensor self.max_input_length = max_input_length self.max_decoder_input_length = max_decoder_input_length self.padding_right_offset = padding_right_offset self.max_tokens = max_tokens return self @classmethod @tracer.start_as_current_span("concatenate") def concatenate(cls, batches: List["Seq2SeqLMBatch"]) -> "Seq2SeqLMBatch": """Concatenate multiple batches together by padding internal torch tensors""" # Used for padding total_batch_size = 0 max_input_length = 0 max_decoder_input_length = 0 padding_right_offset = 0 for batch in batches: total_batch_size += len(batch) max_input_length = max(max_input_length, batch.max_input_length) max_decoder_input_length = max( max_decoder_input_length, batch.max_decoder_input_length ) padding_right_offset = max(padding_right_offset, batch.padding_right_offset) # Batch attributes requests = [] requests_idx_mapping = {} all_decoder_input_ids = [] input_lengths = [] decoder_input_lengths = [] prefix_offsets = [] read_offsets = [] next_token_choosers = [] stopping_criterias = [] top_n_tokens = [] max_tokens = 0 # Batch tensors attention_mask = None decoder_input_ids = None decoder_attention_mask = None encoder_last_hidden_state = None top_n_tokens_tensor = None past_key_values = [] # Used for slicing correctly inside the tensors # Equivalent to a cumsum on batch sizes start_index = 0 for i, batch in enumerate(batches): # Extend all list attributes requests.extend(batch.requests) all_decoder_input_ids.extend(batch.all_decoder_input_ids) input_lengths.extend(batch.input_lengths) decoder_input_lengths.extend(batch.decoder_input_lengths) prefix_offsets.extend(batch.prefix_offsets) read_offsets.extend(batch.read_offsets) next_token_choosers.extend(batch.next_token_choosers) stopping_criterias.extend(batch.stopping_criterias) top_n_tokens.extend(batch.top_n_tokens) if i == 0: requests_idx_mapping = batch.requests_idx_mapping else: # We need to offset the mapping for each batch by the cumulative batch size for k, v in batch.requests_idx_mapping.items(): requests_idx_mapping[k] = v + start_index # Slicing end index for this batch end_index = start_index + len(batch) # We only concatenate batches that did at least one step if batch.encoder_last_hidden_state is None: raise ValueError("Batch encoder_last_hidden_state cannot be None") # Create padded tensor if attention_mask is None: attention_mask = batch.attention_mask.new_zeros( (total_batch_size, max_input_length), ) # Copy to correct indices attention_mask[start_index:end_index, -batch.max_input_length :] = ( batch.attention_mask[:, -batch.max_input_length :] ) # Create padded tensor if decoder_input_ids is None: decoder_input_ids = batch.decoder_input_ids.new_zeros( (total_batch_size, 1), ) # Copy to correct indices decoder_input_ids[start_index:end_index] = batch.decoder_input_ids # Create padded tensor if decoder_attention_mask is None: # As decoder_attention_mask might not exist, we use `batch.attention_mask` for device here decoder_attention_mask = batch.attention_mask.new_zeros( (total_batch_size, max_decoder_input_length + padding_right_offset), ) # If the decoder mask does not exist yet, all generations started at the same time and we never concatenated # this batch. All generations are of length `batch.max_decoder_input_length`. left_offset = max_decoder_input_length - batch.max_decoder_input_length if batch.decoder_attention_mask is None: decoder_attention_mask[ start_index:end_index, left_offset:-padding_right_offset, ] = 1 # If it exists, we need to index else: batch_left_offset = ( batch.decoder_attention_mask.shape[1] - batch.max_decoder_input_length - batch.padding_right_offset ) decoder_attention_mask[ start_index:end_index, left_offset:-padding_right_offset, ] = batch.decoder_attention_mask[ :, batch_left_offset : -batch.padding_right_offset, ] # Create padded tensor if encoder_last_hidden_state is None: encoder_last_hidden_state = batch.encoder_last_hidden_state.new_zeros( ( total_batch_size, max_input_length, batch.encoder_last_hidden_state.shape[-1], ), ) if top_n_tokens_tensor is None: top_n_tokens_tensor = batches[0].top_n_tokens_tensor.new_zeros( total_batch_size, ) top_n_tokens_tensor[start_index:end_index] = batch.top_n_tokens_tensor # Copy to correct indices encoder_last_hidden_state[ start_index:end_index, -batch.max_input_length :, : ] = batch.encoder_last_hidden_state[:, -batch.max_input_length :, :] batch.encoder_last_hidden_state = None # Ensure that we can update tensors in-place if isinstance(batch.past_key_values[0], tuple): batch.past_key_values = [ [t for t in layer] for layer in batch.past_key_values ] # Add eventual padding tokens that were added while concatenating max_tokens += batch.max_tokens + ( max_input_length - batch.max_input_length + max_decoder_input_length - batch.max_decoder_input_length ) * len(batch) start_index = end_index # Determine shapes for new past kv tensors first_past_kvs = batches[0].past_key_values _, num_heads, _, head_dim = first_past_kvs[0][0].shape padded_dec_t_shape = ( total_batch_size, num_heads, (max_decoder_input_length - 1), head_dim, ) padded_enc_t_shape = ( total_batch_size, num_heads, max_input_length, head_dim, ) # Iterate over attention layers for j in range(len(first_past_kvs)): past_key_values.append([]) # Decoder past for k in range(0, 2): # Initialize tensors padded_past_values = first_past_kvs[j][k].new_zeros(padded_dec_t_shape) past_key_values[j].append(padded_past_values) start_index = 0 for batch in batches: t = batch.past_key_values[j][k] # Clear reference to the original tensor batch.past_key_values[j][k] = None # Slicing end index for this batch end_index = start_index + len(batch) # We slice the past keys and values to remove the padding from previous batches past_seq_len = batch.max_decoder_input_length - 1 padded_past_values[start_index:end_index, :, -past_seq_len:, :] = t[ :, :, -past_seq_len:, : ] del t start_index = end_index # Encoder past for k in range(2, 4): # Initialize tensors padded_past_values = first_past_kvs[j][k].new_zeros(padded_enc_t_shape) past_key_values[j].append(padded_past_values) start_index = 0 for batch in batches: t = batch.past_key_values[j][k] # Clear reference to the original tensor batch.past_key_values[j][k] = None # Slicing end index for this batch end_index = start_index + len(batch) # We slice the past keys and values to remove the padding from previous batches padded_past_values[ start_index:end_index, :, -batch.max_input_length :, : ] = t[:, :, -batch.max_input_length :, :] del t start_index = end_index return cls( batch_id=batches[0].batch_id, requests=requests, requests_idx_mapping=requests_idx_mapping, input_ids=None, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, all_decoder_input_ids=all_decoder_input_ids, decoder_attention_mask=decoder_attention_mask, encoder_last_hidden_state=encoder_last_hidden_state, past_key_values=past_key_values, input_lengths=input_lengths, decoder_input_lengths=decoder_input_lengths, prefix_offsets=prefix_offsets, read_offsets=read_offsets, next_token_choosers=next_token_choosers, stopping_criterias=stopping_criterias, top_n_tokens=top_n_tokens, top_n_tokens_tensor=top_n_tokens_tensor, max_input_length=max_input_length, max_decoder_input_length=max_decoder_input_length, padding_right_offset=padding_right_offset, max_tokens=max_tokens, ) def __len__(self): return len(self.requests) class Seq2SeqLM(Model): def __init__( self, model_id: str, model_class, revision: Optional[str] = None, quantize: Optional[str] = None, speculator: Optional[str] = None, dtype: Optional[torch.dtype] = None, default_dtype=torch.float16, trust_remote_code: bool = False, config_class=AutoConfig, tokenizer_class=AutoTokenizer, aliases=None, ): self.quantize = quantize self.process_group, rank, world_size = initialize_torch_distributed() if torch.cuda.is_available(): device = torch.device(f"cuda:{rank}") dtype = default_dtype if dtype is None else dtype elif hasattr(torch, "xpu") and torch.xpu.is_available(): device = torch.device(f"xpu:{rank}") dtype = default_dtype if dtype is None else dtype elif SYSTEM == "ipex": device = torch.device("cpu") # Float16 doesn't exist on target. dtype = torch.bfloat16 if dtype is None else dtype else: device = torch.device("cpu") dtype = torch.float32 if dtype is None else dtype config = config_class.from_pretrained( model_id, revision=revision, trust_remote_code=trust_remote_code, ) config.quantize = quantize config.speculator = speculator tokenizer = tokenizer_class.from_pretrained( model_id, revision=revision, padding_side="left", truncation_side="left", trust_remote_code=trust_remote_code, ) tokenizer.bos_token_id = config.decoder_start_token_id weights_loader = get_loader( quantize=quantize, model_id=model_id, revision=revision ) torch.distributed.barrier(group=self.process_group) filenames = weight_files(model_id, revision=revision, extension=".safetensors") weights = Weights( filenames, device=device, dtype=dtype, process_group=self.process_group, aliases=aliases, weights_loader=weights_loader, ) if config.quantize in ["awq", "exl2", "gptq", "marlin"]: weights._set_gptq_params(model_id, revision) model = model_class(config, weights) torch.distributed.barrier(group=self.process_group) super().__init__( model_id=model_id, model=model, tokenizer=tokenizer, requires_padding=True, dtype=dtype, device=device, rank=rank, world_size=world_size, ) @classmethod def fallback( cls, model_id: str, revision: Optional[str] = None, quantize: Optional[str] = None, speculator: Optional[str] = None, dtype: Optional[torch.dtype] = None, trust_remote_code: bool = False, ): if speculator: raise RuntimeError("Speculator decoding is not enabled for AutoModel") device_count = 0 if torch.cuda.is_available(): device = torch.device("cuda") device_count = torch.cuda.device_count() dtype = torch.float16 if dtype is None else dtype elif hasattr(torch, "xpu") and torch.xpu.is_available(): device = torch.device("xpu") device_count = torch.xpu.device_count() dtype = torch.float16 if dtype is None else dtype else: if quantize: raise ValueError("quantization is not available on CPU") device = torch.device("cpu") dtype = torch.float32 if dtype is None else dtype model = AutoModelForSeq2SeqLM.from_pretrained( model_id, revision=revision, torch_dtype=dtype, device_map=("auto" if device_count > 1 else None), load_in_8bit=quantize == "bitsandbytes", trust_remote_code=trust_remote_code, ) if device_count == 1: model = model.to(device) tokenizer = AutoTokenizer.from_pretrained( model_id, revision=revision, padding_side="left", truncation_side="left", trust_remote_code=trust_remote_code, ) tokenizer.bos_token_id = model.config.decoder_start_token_id self = cls.__new__( cls, ) super().__init__( self, model_id=model_id, model=model, tokenizer=tokenizer, requires_padding=True, dtype=dtype, device=device, ) self.quantize = quantize return self @property def batch_type(self) -> Type[Seq2SeqLMBatch]: return Seq2SeqLMBatch def forward( self, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask: Optional, encoder_last_hidden_state: Optional, past_key_values: Optional = None, ) -> Tuple[ torch.Tensor, Optional[torch.Tensor], torch.Tensor, List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]], ]: # Model Forward outputs = self.model.forward( input_ids=input_ids, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, encoder_outputs=encoder_last_hidden_state, past_key_values=past_key_values, use_cache=True, ) if isinstance(outputs, tuple): # Our custom models outputs, speculative_logits = outputs else: # Generic transformers models speculative_logits = None return ( outputs.logits, speculative_logits, outputs.encoder_last_hidden_state, outputs.past_key_values, ) @tracer.start_as_current_span("generate_token") def generate_token( self, batch: Seq2SeqLMBatch ) -> Tuple[List[Generation], Optional[Seq2SeqLMBatch], Tuple[int, int]]: start = time.time_ns() if batch.decoder_attention_mask is not None: # slice to the correct shape decoder_attention_mask = batch.decoder_attention_mask[ :, : -batch.padding_right_offset ] else: decoder_attention_mask = None # Wrap `encoder_last_hidden_state` because for some reason, Transformers does a `encoder_last_hidden_state[0]` # internally... if batch.encoder_last_hidden_state is not None: encoder_last_hidden_state = [batch.encoder_last_hidden_state] else: encoder_last_hidden_state = None logits, speculative_logits, encoder_last_hidden_state, past = self.forward( batch.input_ids, batch.attention_mask, batch.decoder_input_ids, decoder_attention_mask, encoder_last_hidden_state, batch.past_key_values, ) # Speculation is not active for seq2seq accepted_ids = torch.ones_like(batch.decoder_input_ids)[:, 0] batch_top_token_ids, batch_top_token_logprobs = batch_top_tokens( batch.top_n_tokens, batch.top_n_tokens_tensor, torch.log_softmax(logits[:, -1], -1), accepted_ids, ) start_decode = time.time_ns() # Finished requests generations: List[Generation] = [] stopped = True # Zipped iterator iterator = zip( batch.requests, batch.input_lengths, batch.prefix_offsets, batch.read_offsets, batch.decoder_input_lengths, logits, batch.next_token_choosers, batch.stopping_criterias, batch.all_decoder_input_ids, batch.top_n_tokens, batch_top_token_ids, batch_top_token_logprobs, ) # For each member of the batch for i, ( request, input_length, prefix_offset, read_offset, decoder_input_length, logits, next_token_chooser, stopping_criteria, all_decoder_input_ids, top_n_tokens, top_token_ids, top_token_logprobs, ) in enumerate(iterator): # Select next token next_token_id, logprobs = next_token_chooser( all_decoder_input_ids.view(1, -1), logits[-1:, :] ) # Append next token to decoder tokens all_decoder_input_ids = torch.cat( [all_decoder_input_ids, next_token_id.squeeze(1)] ) new_decoder_input_length = decoder_input_length + 1 # Generated token next_token_logprob = logprobs[-1, next_token_id] next_token_id_squeezed = next_token_id.squeeze() next_token_text, prefix_offset, read_offset = self.decode_token( all_decoder_input_ids, prefix_offset, read_offset ) # Evaluate stopping criteria stop, reason = stopping_criteria(next_token_id, next_token_text) if not stop: stopped = False # Shard generations # All generations will be appended in the rust sharded client if i % self.world_size == self.rank: if stop: # Slice with decoder_input_length to remove padding # Decode all tokens output_text, _, _ = self.decode_token( all_decoder_input_ids, prefix_offset=len(all_decoder_input_ids) - decoder_input_length - 1, read_offset=len(all_decoder_input_ids) - decoder_input_length, skip_special_tokens=True, ) # Get seed if isinstance(next_token_chooser.choice, Sampling): seed = next_token_chooser.choice.seed else: seed = None generated_text = GeneratedText( output_text, stopping_criteria.current_tokens, reason, seed ) else: generated_text = None # Prefill if stopping_criteria.current_tokens == 1 and request.prefill_logprobs: prefill_tokens = Tokens( [self.tokenizer.bos_token_id], [float("nan")], [self.tokenizer.bos_token], [False], ) else: prefill_tokens = None if top_n_tokens > 0: all_top_tokens = [] for top_token_ids, top_token_logprobs in zip( top_token_ids, top_token_logprobs ): toptoken_texts = self.tokenizer.batch_decode( top_token_ids, clean_up_tokenization_spaces=False, skip_special_tokens=False, ) special_toptokens = [ token_id in self.all_special_ids for token_id in top_token_ids ] top_tokens = Tokens( top_token_ids, top_token_logprobs, toptoken_texts, special_toptokens, ) all_top_tokens.append(top_tokens) top_tokens = all_top_tokens else: top_tokens = None generation = Generation( request.id, prefill_tokens, Tokens( [next_token_id_squeezed], [next_token_logprob], [next_token_text], [next_token_id_squeezed.item() in self.all_special_ids], ), generated_text, top_tokens, ) generations.append(generation) # Update values batch.next_token_choosers[i] = batch.next_token_choosers[i].advance_grammar( next_token_id_squeezed.item() ) batch.decoder_input_ids[i] = next_token_id batch.all_decoder_input_ids[i] = all_decoder_input_ids batch.input_lengths[i] = input_length batch.decoder_input_lengths[i] = new_decoder_input_length batch.prefix_offsets[i] = prefix_offset batch.read_offsets[i] = read_offset batch.max_input_length = max(batch.max_input_length, input_length) batch.max_decoder_input_length = max( batch.max_decoder_input_length, new_decoder_input_length ) # We finished all generations in the batch; there is no next batch if stopped: forward_ns = start_decode - start decode_ns = time.time_ns() - start_decode return generations, None, (forward_ns, decode_ns) # We don't need input_ids after the prefill forward batch.input_ids = None batch.encoder_last_hidden_state = encoder_last_hidden_state batch.past_key_values = past # Update decoder_attention_mask as we added a new token to input_ids if batch.decoder_attention_mask is not None: batch.decoder_attention_mask[:, -batch.padding_right_offset] = 1 batch.padding_right_offset -= 1 forward_ns = start_decode - start decode_ns = time.time_ns() - start_decode return generations, batch, (forward_ns, decode_ns)
text-generation-inference/server/text_generation_server/models/seq2seq_lm.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/models/seq2seq_lm.py", "repo_id": "text-generation-inference", "token_count": 17976 }
324
from functools import lru_cache from text_generation_server.utils.dist import RANK @lru_cache(10) def log_once(log, msg: str, master=True): if master: log_master(log, msg) else: log(msg) def log_master(log, msg: str): if RANK == 0: log(msg)
text-generation-inference/server/text_generation_server/utils/log.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/utils/log.py", "repo_id": "text-generation-inference", "token_count": 126 }
325
extern crate napi_build; fn main() { napi_build::setup(); }
tokenizers/bindings/node/build.rs/0
{ "file_path": "tokenizers/bindings/node/build.rs", "repo_id": "tokenizers", "token_count": 26 }
326
// import { promisify } from 'util' import { BPE, Tokenizer, mergeEncodings, slice } from '../../' describe('slice', () => { const text = 'My name is John 👋' const sliceText = slice.bind({}, text) it('returns the full text when no params', () => { const sliced = sliceText() expect(sliced).toEqual(text) }) it('accepts `undefined` as second parameter', () => { const original = sliceText(undefined) expect(original).toEqual(text) }) it('accepts `undefined` as third parameter', () => { const original = sliceText(0, undefined) expect(original).toEqual(text) }) it('throws an error when `begin` is out of range', () => { expect(() => sliceText(1000)).toThrow() }) it('returns slice starting at the specified index', () => { const original = sliceText(3) expect(original).toEqual('name is John 👋') }) it('throws an error when `end` is out of range', () => { expect(() => sliceText(0, 1000)).toThrow() }) it('returns the text between the two specified indexes', () => { const original = sliceText(3, 7) expect(original).toEqual('name') }) describe('with only a negative `begin`', () => { it('returns the original string counting from the end when in the range', () => { const original = sliceText(-1) expect(original).toEqual('👋') }) it('throws an error when out of range', () => { expect(() => sliceText(-1000)).toThrow() }) }) describe('with a positive `begin` and a negative `end`', () => { it('returns correct slice when resulting range is valid', () => { const original = sliceText(3, -7) expect(original).toEqual('name is') }) it('throws an error when resulting `end` index is lower than `begin`', () => { expect(() => sliceText(7, -12)).toThrow() }) it('throws an error when `begin` is out of range', () => { expect(() => sliceText(1000, -12)).toThrow() }) it('throws an error when resulting `end` index is out of range', () => { expect(() => sliceText(7, -1000)).toThrow() }) }) describe('with a negative `begin` and a positive `end`', () => { it('returns correct slice when resulting range is valid', () => { const original = sliceText(-9, 10) expect(original).toEqual('is') }) it('throws an error when resulting `begin` index is upper than `end`', () => { expect(() => sliceText(-3, 5)).toThrow() }) it('throws an error when `end` is out of range', () => { expect(() => sliceText(-5, 1000)).toThrow() }) it('throws an error when resulting `begin` index is out of range', () => { expect(() => sliceText(-1000, 10)).toThrow() }) }) describe('with negatives `begin` and `end`', () => { it('returns correct slice when resulting range is valid', () => { const original = sliceText(-9, -7) expect(original).toEqual('is') }) it('throws an error when resulting `end` index is lower than `begin`', () => { expect(() => sliceText(-5, -10)).toThrow() }) it('throws an error when resulting `begin` index is out of range', () => { expect(() => sliceText(-1000, -10)).toThrow() }) it('throws an error when resulting `end` index is out of range', () => { expect(() => sliceText(-10, -1000)).toThrow() }) }) }) describe('mergeEncodings', () => { const model = BPE.empty() const tokenizer = new Tokenizer(model) tokenizer.addTokens(['my', 'name', 'is', 'john']) it('accepts `undefined` as a second parameter', () => { const encoding = mergeEncodings([], undefined) expect(encoding.constructor.name).toEqual('Encoding') }) it('returns correct result with `growingOffsets` not provided', async () => { const firstEncoding = await tokenizer.encode('my name is', null) const secondEncoding = await tokenizer.encode('john', null) const encoding = mergeEncodings([firstEncoding, secondEncoding]) expect(encoding.getTokens()).toEqual(['my', 'name', 'is', 'john']) expect(encoding.getOffsets()).toEqual([ [0, 2], [3, 7], [8, 10], [0, 4], ]) }) it('returns correct result when `growingOffsets` is `false`', async () => { const firstEncoding = await tokenizer.encode('my name is', null) const secondEncoding = await tokenizer.encode('john', null) const encoding = mergeEncodings([firstEncoding, secondEncoding], false) expect(encoding.getTokens()).toEqual(['my', 'name', 'is', 'john']) expect(encoding.getOffsets()).toEqual([ [0, 2], [3, 7], [8, 10], [0, 4], ]) }) it('returns correct result when `growingOffsets` is `true`', async () => { const firstEncoding = await tokenizer.encode('my name is', null) const secondEncoding = await tokenizer.encode('john', null) const encoding = mergeEncodings([firstEncoding, secondEncoding], true) expect(encoding.getTokens()).toEqual(['my', 'name', 'is', 'john']) expect(encoding.getOffsets()).toEqual([ [0, 2], [3, 7], [8, 10], [10, 14], ]) }) })
tokenizers/bindings/node/lib/bindings/utils.test.ts/0
{ "file_path": "tokenizers/bindings/node/lib/bindings/utils.test.ts", "repo_id": "tokenizers", "token_count": 1866 }
327
{ "name": "tokenizers-linux-arm64-musl", "version": "0.13.4-rc1", "os": [ "linux" ], "cpu": [ "arm64" ], "main": "tokenizers.linux-arm64-musl.node", "files": [ "tokenizers.linux-arm64-musl.node" ], "description": "Tokenizers platform specific bindings", "keywords": [ "napi-rs", "NAPI", "N-API", "Rust", "node-addon", "node-addon-api" ], "license": "MIT", "engines": { "node": ">= 10" }, "publishConfig": { "registry": "https://registry.npmjs.org/", "access": "public" }, "repository": "tokenizers", "libc": [ "musl" ] }
tokenizers/bindings/node/npm/linux-arm64-musl/package.json/0
{ "file_path": "tokenizers/bindings/node/npm/linux-arm64-musl/package.json", "repo_id": "tokenizers", "token_count": 291 }
328
#![deny(clippy::all)] pub const VERSION: &str = env!("CARGO_PKG_VERSION"); mod arc_rwlock_serde; pub mod decoders; pub mod encoding; pub mod models; pub mod normalizers; pub mod pre_tokenizers; pub mod processors; pub mod tasks; pub mod tokenizer; pub mod trainers; pub mod utils;
tokenizers/bindings/node/src/lib.rs/0
{ "file_path": "tokenizers/bindings/node/src/lib.rs", "repo_id": "tokenizers", "token_count": 102 }
329
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [0.13.2] - [#1096] Python 3.11 support ## [0.13.1] - [#1072] Fixing Roberta type ids. ## [0.13.0] - [#956] PyO3 version upgrade - [#1055] M1 automated builds - [#1008] `Decoder` is now a composable trait, but without being backward incompatible - [#1047, #1051, #1052] `Processor` is now a composable trait, but without being backward incompatible Both trait changes warrant a "major" number since, despite best efforts to not break backward compatibility, the code is different enough that we cannot be exactly sure. ## [0.12.1] - [#938] **Reverted breaking change**. https://github.com/huggingface/transformers/issues/16520 ## [0.12.0] YANKED Bump minor version because of a breaking change. - [#938] [REVERTED IN 0.12.1] **Breaking change**. Decoder trait is modified to be composable. This is only breaking if you are using decoders on their own. tokenizers should be error free. - [#939] Making the regex in `ByteLevel` pre_tokenizer optional (necessary for BigScience) - [#952] Fixed the vocabulary size of UnigramTrainer output (to respect added tokens) - [#954] Fixed not being able to save vocabularies with holes in vocab (ConvBert). Yell warnings instead, but stop panicking. - [#962] Fix tests for python 3.10 - [#961] Added link for Ruby port of `tokenizers` ## [0.11.6] - [#919] Fixing single_word AddedToken. (regression from 0.11.2) - [#916] Deserializing faster `added_tokens` by loading them in batch. ## [0.11.5] - [#895] Build `python 3.10` wheels. ## [0.11.4] - [#884] Fixing bad deserialization following inclusion of a default for Punctuation ## [0.11.3] - [#882] Fixing Punctuation deserialize without argument. - [#868] Fixing missing direction in TruncationParams - [#860] Adding TruncationSide to TruncationParams ## [0.11.0] ### Fixed - [#585] Conda version should now work on old CentOS - [#844] Fixing interaction between `is_pretokenized` and `trim_offsets`. - [#851] Doc links ### Added - [#657]: Add SplitDelimiterBehavior customization to Punctuation constructor - [#845]: Documentation for `Decoders`. ### Changed - [#850]: Added a feature gate to enable disabling `http` features - [#718]: Fix `WordLevel` tokenizer determinism during training - [#762]: Add a way to specify the unknown token in `SentencePieceUnigramTokenizer` - [#770]: Improved documentation for `UnigramTrainer` - [#780]: Add `Tokenizer.from_pretrained` to load tokenizers from the Hugging Face Hub - [#793]: Saving a pretty JSON file by default when saving a tokenizer ## [0.10.3] ### Fixed - [#686]: Fix SPM conversion process for whitespace deduplication - [#707]: Fix stripping strings containing Unicode characters ### Added - [#693]: Add a CTC Decoder for Wave2Vec models ### Removed - [#714]: Removed support for Python 3.5 ## [0.10.2] ### Fixed - [#652]: Fix offsets for `Precompiled` corner case - [#656]: Fix BPE `continuing_subword_prefix` - [#674]: Fix `Metaspace` serialization problems ## [0.10.1] ### Fixed - [#616]: Fix SentencePiece tokenizers conversion - [#617]: Fix offsets produced by Precompiled Normalizer (used by tokenizers converted from SPM) - [#618]: Fix Normalizer.normalize with `PyNormalizedStringRefMut` - [#620]: Fix serialization/deserialization for overlapping models - [#621]: Fix `ByteLevel` instantiation from a previously saved state (using `__getstate__()`) ## [0.10.0] ### Added - [#508]: Add a Visualizer for notebooks to help understand how the tokenizers work - [#519]: Add a `WordLevelTrainer` used to train a `WordLevel` model - [#533]: Add support for conda builds - [#542]: Add Split pre-tokenizer to easily split using a pattern - [#544]: Ability to train from memory. This also improves the integration with `datasets` - [#590]: Add getters/setters for components on BaseTokenizer - [#574]: Add `fust_unk` option to SentencePieceBPETokenizer ### Changed - [#509]: Automatically stubbing the `.pyi` files - [#519]: Each `Model` can return its associated `Trainer` with `get_trainer()` - [#530]: The various attributes on each component can be get/set (ie. `tokenizer.model.dropout = 0.1`) - [#538]: The API Reference has been improved and is now up-to-date. ### Fixed - [#519]: During training, the `Model` is now trained in-place. This fixes several bugs that were forcing to reload the `Model` after a training. - [#539]: Fix `BaseTokenizer` enable_truncation docstring ## [0.9.4] ### Fixed - [#492]: Fix `from_file` on `BertWordPieceTokenizer` - [#498]: Fix the link to download `sentencepiece_model_pb2.py` - [#500]: Fix a typo in the docs quicktour ### Changed - [#506]: Improve Encoding mappings for pairs of sequence ## [0.9.3] ### Fixed - [#470]: Fix hanging error when training with custom component - [#476]: TemplateProcessing serialization is now deterministic - [#481]: Fix SentencePieceBPETokenizer.from_files ### Added - [#477]: UnicodeScripts PreTokenizer to avoid merges between various scripts - [#480]: Unigram now accepts an `initial_alphabet` and handles `special_tokens` correctly ## [0.9.2] ### Fixed - [#464]: Fix a problem with RobertaProcessing being deserialized as BertProcessing ## [0.9.1] ### Fixed - [#459]: Fix a problem with deserialization ## [0.9.0] ### Fixed - [#362]: Fix training deadlock with Python components. - [#363]: Fix a crash when calling `.train` with some non-existent files - [#355]: Remove a lot of possible crashes - [#389]: Improve truncation (crash and consistency) ### Added - [#379]: Add the ability to call `encode`/`encode_batch` with numpy arrays - [#292]: Support for the Unigram algorithm - [#378], [#394], [#416], [#417]: Many new Normalizer and PreTokenizer - [#403]: Add `TemplateProcessing` `PostProcessor`. - [#420]: Ability to fuse the "unk" token in BPE. ### Changed - [#360]: Lots of improvements related to words/alignment tracking - [#426]: Improvements on error messages thanks to PyO3 0.12 ## [0.8.1] ### Fixed - [#333]: Fix deserialization of `AddedToken`, where the content was not restored properly ### Changed - [#329]: Improved warning and behavior when we detect a fork - [#330]: BertNormalizer now keeps the same behavior than the original implementation when `strip_accents` is not specified. ## [0.8.0] ### Highlights of this release - We can now encode both pre-tokenized inputs, and raw strings. This is especially usefull when processing datasets that are already pre-tokenized like for NER (Name Entity Recognition), and helps while applying labels to each word. - Full tokenizer serialization. It is now easy to save a tokenizer to a single JSON file, to later load it back with just one line of code. That's what sharing a Tokenizer means now: 1 line of code. - With the serialization comes the compatibility with `Pickle`! The Tokenizer, all of its components, Encodings, everything can be pickled! - Training a tokenizer is now even faster (up to 5-10x) than before! - Compatibility with `multiprocessing`, even when using the `fork` start method. Since this library makes heavy use of the multithreading capacities of our computers to allows a very fast tokenization, this led to problems (deadlocks) when used with `multiprocessing`. This version now allows to disable the parallelism, and will warn you if this is necessary. - And a lot of other improvements, and fixes. ### Fixed - [#286]: Fix various crash when training a BPE model - [#309]: Fixed a few bugs related to additional vocabulary/tokens ### Added - [#272]: Serialization of the `Tokenizer` and all the parts (`PreTokenizer`, `Normalizer`, ...). This adds some methods to easily save/load an entire tokenizer (`from_str`, `from_file`). - [#273]: `Tokenizer` and its parts are now pickable - [#289]: Ability to pad to a multiple of a specified value. This is especially useful to ensure activation of the Tensor Cores, while ensuring padding to a multiple of 8. Use with `enable_padding(pad_to_multiple_of=8)` for example. - [#298]: Ability to get the currently set truncation/padding params - [#311]: Ability to enable/disable the parallelism using the `TOKENIZERS_PARALLELISM` environment variable. This is especially usefull when using `multiprocessing` capabilities, with the `fork` start method, which happens to be the default on Linux systems. Without disabling the parallelism, the process dead-locks while encoding. (Cf [#187] for more information) ### Changed - Improved errors generated during truncation: When the provided max length is too low are now handled properly. - [#249] `encode` and `encode_batch` now accept pre-tokenized inputs. When the input is pre-tokenized, the argument `is_pretokenized=True` must be specified. - [#276]: Improve BPE training speeds, by reading files sequentially, but parallelizing the processing of each file - [#280]: Use `onig` for byte-level pre-tokenization to remove all the differences with the original implementation from GPT-2 - [#309]: Improved the management of the additional vocabulary. This introduces an option `normalized`, controlling whether a token should be extracted from the normalized version of the input text. ## [0.7.0] ### Changed - Only one progress bar while reading files during training. This is better for use-cases with a high number of files as it avoids having too many progress bars on screen. Also avoids reading the size of each file before starting to actually read these files, as this process could take really long. - [#193]: `encode` and `encode_batch` now take a new optional argument, specifying whether we should add the special tokens. This is activated by default. - [#197]: `original_str` and `normalized_str` have been removed from the `Encoding` returned by `encode` and `encode_batch`. This brings a reduction of 70% of the memory footprint. - [#197]: The offsets provided on `Encoding` are now relative to the original string, and not the normalized one anymore. - The added token given to `add_special_tokens` or `add_tokens` on a `Tokenizer`, or while using `train(special_tokens=...)` can now be instances of `AddedToken` to provide more control over these tokens. - [#136]: Updated Pyo3 version - [#136]: Static methods `Model.from_files` and `Model.empty` are removed in favor of using constructors. - [#239]: `CharBPETokenizer` now corresponds to OpenAI GPT BPE implementation by default. ### Added - [#188]: `ByteLevel` is also a `PostProcessor` now and handles trimming the offsets if activated. This avoids the unintuitive inclusion of the whitespaces in the produced offsets, even if these whitespaces are part of the actual token. It has been added to `ByteLevelBPETokenizer` but it is off by default (`trim_offsets=False`). - [#236]: `RobertaProcessing` also handles trimming the offsets. - [#234]: New alignment mappings on the `Encoding`. Provide methods to easily convert between `char` or `word` (input space) and `token` (output space). - `post_process` can be called on the `Tokenizer` - [#208]: Ability to retrieve the vocabulary from the `Tokenizer` with `get_vocab(with_added_tokens: bool)` - [#136] Models can now be instantiated through object constructors. ### Fixed - [#193]: Fix some issues with the offsets being wrong with the `ByteLevel` BPE: - when `add_prefix_space=True` - [#156]: when a Unicode character gets split-up in multiple byte-level characters - Fix a bug where offsets were wrong when there was any added tokens in the sequence being encoded. - [#175]: Fix a bug that prevented the addition of more than a certain amount of tokens (even if not advised, but that's not the question). - [#205]: Trim the decoded string in `BPEDecoder` used by `CharBPETokenizer` ### How to migrate - Add the `ByteLevel` `PostProcessor` to your byte-level BPE tokenizers if relevant. If you are using `ByteLevelBPETokenizer`, this option is disabled by default (`trim_offsets=False`). - `BertWordPieceTokenizer` option to `add_special_tokens` must now be given to `encode` or `encode_batch` - Access to the `original_str` on the `Encoding` has been removed. The original string is the input of `encode` so it didn't make sense to keep it here. - No need to call `original_str.offsets(offsets[N])` to convert offsets to the original string. They are now relative to the original string by default. - Access to the `normalized_str` on the `Encoding` has been removed. Can be retrieved by calling `normalize(sequence)` on the `Tokenizer` - Change `Model.from_files` and `Model.empty` to use constructor. The model constructor should take the same arguments as the old methods. (ie `BPE(vocab, merges)` or `BPE()`) - If you were using the `CharBPETokenizer` and want to keep the same behavior as before, set `bert_normalizer=False` and `split_on_whitespace_only=True`. ## [0.6.0] ### Changed - [#165]: Big improvements in speed for BPE (Both training and tokenization) ### Fixed - [#160]: Some default tokens were missing from `BertWordPieceTokenizer` - [#156]: There was a bug in ByteLevel PreTokenizer that caused offsets to be wrong if a char got split up in multiple bytes. - [#174]: The `longest_first` truncation strategy had a bug ## [0.5.2] - [#163]: Do not open all files directly while training ### Fixed - We introduced a bug related to the saving of the WordPiece model in 0.5.1: The `vocab.txt` file was named `vocab.json`. This is now fixed. - The `WordLevel` model was also saving its vocabulary to the wrong format. ## [0.5.1] ### Changed - `name` argument is now optional when saving a `Model`'s vocabulary. When the name is not specified, the files get a more generic naming, like `vocab.json` or `merges.txt`. ## [0.5.0] ### Changed - [#145]: `BertWordPieceTokenizer` now cleans up some tokenization artifacts while decoding - [#149]: `ByteLevelBPETokenizer` now has `dropout`. - `do_lowercase` has been changed to `lowercase` for consistency between the different tokenizers. (Especially `ByteLevelBPETokenizer` and `CharBPETokenizer`) - [#139]: Expose `__len__` on `Encoding` - Improved padding performances. ### Added - Added a new `Strip` normalizer ### Fixed - [#145]: Decoding was buggy on `BertWordPieceTokenizer`. - [#152]: Some documentation and examples were still using the old `BPETokenizer` ### How to migrate - Use `lowercase` when initializing `ByteLevelBPETokenizer` or `CharBPETokenizer` instead of `do_lowercase`. ## [0.4.2] ### Fixed - [#137]: Fix a bug in the class `WordPieceTrainer` that prevented `BertWordPieceTokenizer` from being trained. ## [0.4.1] ### Fixed - [#134]: Fix a bug related to the punctuation in BertWordPieceTokenizer ## [0.4.0] ### Changed - [#131]: Replaced all .new() class methods by a proper __new__ implementation - Improved typings ### How to migrate - Remove all `.new` on all classe instanciations ## [0.3.0] ### Changed - BPETokenizer has been renamed to CharBPETokenizer for clarity. - Improve truncation/padding and the handling of overflowing tokens. Now when a sequence gets truncated, we provide a list of overflowing `Encoding` that are ready to be processed by a language model, just as the main `Encoding`. - Provide mapping to the original string offsets using: ``` output = tokenizer.encode(...) print(output.original_str.offsets(output.offsets[3])) ``` - [#99]: Exposed the vocabulary size on all tokenizers ### Added - Added `CharDelimiterSplit`: a new `PreTokenizer` that allows splitting sequences on the given delimiter (Works like `.split(delimiter)`) - Added `WordLevel`: a new model that simply maps `tokens` to their `ids`. ### Fixed - Fix a bug with IndexableString - Fix a bug with truncation ### How to migrate - Rename `BPETokenizer` to `CharBPETokenizer` - `Encoding.overflowing` is now a List instead of a `Optional[Encoding]` ## [0.2.1] ### Fixed - Fix a bug with the IDs associated with added tokens. - Fix a bug that was causing crashes in Python 3.5 [#1096]: https://github.com/huggingface/tokenizers/pull/1096 [#1072]: https://github.com/huggingface/tokenizers/pull/1072 [#956]: https://github.com/huggingface/tokenizers/pull/956 [#1008]: https://github.com/huggingface/tokenizers/pull/1008 [#1009]: https://github.com/huggingface/tokenizers/pull/1009 [#1047]: https://github.com/huggingface/tokenizers/pull/1047 [#1055]: https://github.com/huggingface/tokenizers/pull/1055 [#1051]: https://github.com/huggingface/tokenizers/pull/1051 [#1052]: https://github.com/huggingface/tokenizers/pull/1052 [#938]: https://github.com/huggingface/tokenizers/pull/938 [#939]: https://github.com/huggingface/tokenizers/pull/939 [#952]: https://github.com/huggingface/tokenizers/pull/952 [#954]: https://github.com/huggingface/tokenizers/pull/954 [#962]: https://github.com/huggingface/tokenizers/pull/962 [#961]: https://github.com/huggingface/tokenizers/pull/961 [#960]: https://github.com/huggingface/tokenizers/pull/960 [#919]: https://github.com/huggingface/tokenizers/pull/919 [#916]: https://github.com/huggingface/tokenizers/pull/916 [#895]: https://github.com/huggingface/tokenizers/pull/895 [#884]: https://github.com/huggingface/tokenizers/pull/884 [#882]: https://github.com/huggingface/tokenizers/pull/882 [#868]: https://github.com/huggingface/tokenizers/pull/868 [#860]: https://github.com/huggingface/tokenizers/pull/860 [#850]: https://github.com/huggingface/tokenizers/pull/850 [#844]: https://github.com/huggingface/tokenizers/pull/844 [#845]: https://github.com/huggingface/tokenizers/pull/845 [#851]: https://github.com/huggingface/tokenizers/pull/851 [#585]: https://github.com/huggingface/tokenizers/pull/585 [#793]: https://github.com/huggingface/tokenizers/pull/793 [#780]: https://github.com/huggingface/tokenizers/pull/780 [#770]: https://github.com/huggingface/tokenizers/pull/770 [#762]: https://github.com/huggingface/tokenizers/pull/762 [#718]: https://github.com/huggingface/tokenizers/pull/718 [#714]: https://github.com/huggingface/tokenizers/pull/714 [#707]: https://github.com/huggingface/tokenizers/pull/707 [#693]: https://github.com/huggingface/tokenizers/pull/693 [#686]: https://github.com/huggingface/tokenizers/pull/686 [#674]: https://github.com/huggingface/tokenizers/pull/674 [#657]: https://github.com/huggingface/tokenizers/pull/657 [#656]: https://github.com/huggingface/tokenizers/pull/656 [#652]: https://github.com/huggingface/tokenizers/pull/652 [#621]: https://github.com/huggingface/tokenizers/pull/621 [#620]: https://github.com/huggingface/tokenizers/pull/620 [#618]: https://github.com/huggingface/tokenizers/pull/618 [#617]: https://github.com/huggingface/tokenizers/pull/617 [#616]: https://github.com/huggingface/tokenizers/pull/616 [#590]: https://github.com/huggingface/tokenizers/pull/590 [#574]: https://github.com/huggingface/tokenizers/pull/574 [#544]: https://github.com/huggingface/tokenizers/pull/544 [#542]: https://github.com/huggingface/tokenizers/pull/542 [#539]: https://github.com/huggingface/tokenizers/pull/539 [#538]: https://github.com/huggingface/tokenizers/pull/538 [#533]: https://github.com/huggingface/tokenizers/pull/533 [#530]: https://github.com/huggingface/tokenizers/pull/530 [#519]: https://github.com/huggingface/tokenizers/pull/519 [#509]: https://github.com/huggingface/tokenizers/pull/509 [#508]: https://github.com/huggingface/tokenizers/pull/508 [#506]: https://github.com/huggingface/tokenizers/pull/506 [#500]: https://github.com/huggingface/tokenizers/pull/500 [#498]: https://github.com/huggingface/tokenizers/pull/498 [#492]: https://github.com/huggingface/tokenizers/pull/492 [#481]: https://github.com/huggingface/tokenizers/pull/481 [#480]: https://github.com/huggingface/tokenizers/pull/480 [#477]: https://github.com/huggingface/tokenizers/pull/477 [#476]: https://github.com/huggingface/tokenizers/pull/476 [#470]: https://github.com/huggingface/tokenizers/pull/470 [#464]: https://github.com/huggingface/tokenizers/pull/464 [#459]: https://github.com/huggingface/tokenizers/pull/459 [#420]: https://github.com/huggingface/tokenizers/pull/420 [#417]: https://github.com/huggingface/tokenizers/pull/417 [#416]: https://github.com/huggingface/tokenizers/pull/416 [#403]: https://github.com/huggingface/tokenizers/pull/403 [#394]: https://github.com/huggingface/tokenizers/pull/394 [#389]: https://github.com/huggingface/tokenizers/pull/389 [#379]: https://github.com/huggingface/tokenizers/pull/379 [#378]: https://github.com/huggingface/tokenizers/pull/378 [#363]: https://github.com/huggingface/tokenizers/pull/363 [#362]: https://github.com/huggingface/tokenizers/pull/362 [#360]: https://github.com/huggingface/tokenizers/pull/360 [#355]: https://github.com/huggingface/tokenizers/pull/355 [#333]: https://github.com/huggingface/tokenizers/pull/333 [#330]: https://github.com/huggingface/tokenizers/pull/330 [#329]: https://github.com/huggingface/tokenizers/pull/329 [#311]: https://github.com/huggingface/tokenizers/pull/311 [#309]: https://github.com/huggingface/tokenizers/pull/309 [#292]: https://github.com/huggingface/tokenizers/pull/292 [#289]: https://github.com/huggingface/tokenizers/pull/289 [#286]: https://github.com/huggingface/tokenizers/pull/286 [#280]: https://github.com/huggingface/tokenizers/pull/280 [#276]: https://github.com/huggingface/tokenizers/pull/276 [#273]: https://github.com/huggingface/tokenizers/pull/273 [#272]: https://github.com/huggingface/tokenizers/pull/272 [#249]: https://github.com/huggingface/tokenizers/pull/249 [#239]: https://github.com/huggingface/tokenizers/pull/239 [#236]: https://github.com/huggingface/tokenizers/pull/236 [#234]: https://github.com/huggingface/tokenizers/pull/234 [#208]: https://github.com/huggingface/tokenizers/pull/208 [#205]: https://github.com/huggingface/tokenizers/issues/205 [#197]: https://github.com/huggingface/tokenizers/pull/197 [#193]: https://github.com/huggingface/tokenizers/pull/193 [#190]: https://github.com/huggingface/tokenizers/pull/190 [#188]: https://github.com/huggingface/tokenizers/pull/188 [#187]: https://github.com/huggingface/tokenizers/issues/187 [#175]: https://github.com/huggingface/tokenizers/issues/175 [#174]: https://github.com/huggingface/tokenizers/issues/174 [#165]: https://github.com/huggingface/tokenizers/pull/165 [#163]: https://github.com/huggingface/tokenizers/issues/163 [#160]: https://github.com/huggingface/tokenizers/issues/160 [#156]: https://github.com/huggingface/tokenizers/pull/156 [#152]: https://github.com/huggingface/tokenizers/issues/152 [#149]: https://github.com/huggingface/tokenizers/issues/149 [#145]: https://github.com/huggingface/tokenizers/issues/145 [#139]: https://github.com/huggingface/tokenizers/issues/139 [#137]: https://github.com/huggingface/tokenizers/issues/137 [#134]: https://github.com/huggingface/tokenizers/issues/134 [#131]: https://github.com/huggingface/tokenizers/issues/131 [#99]: https://github.com/huggingface/tokenizers/pull/99
tokenizers/bindings/python/CHANGELOG.md/0
{ "file_path": "tokenizers/bindings/python/CHANGELOG.md", "repo_id": "tokenizers", "token_count": 7408 }
330
# Generated content DO NOT EDIT class DecodeStream: """ Class needed for streaming decode """ def __init__(self, skip_special_tokens): pass class Decoder: """ Base class for all decoders This class is not supposed to be instantiated directly. Instead, any implementation of a Decoder will return an instance of this class when instantiated. """ def decode(self, tokens): """ Decode the given list of tokens to a final string Args: tokens (:obj:`List[str]`): The list of tokens to decode Returns: :obj:`str`: The decoded string """ pass class BPEDecoder(Decoder): """ BPEDecoder Decoder Args: suffix (:obj:`str`, `optional`, defaults to :obj:`</w>`): The suffix that was used to characterize an end-of-word. This suffix will be replaced by whitespaces during the decoding """ def __init__(self, suffix="</w>"): pass def decode(self, tokens): """ Decode the given list of tokens to a final string Args: tokens (:obj:`List[str]`): The list of tokens to decode Returns: :obj:`str`: The decoded string """ pass class ByteFallback(Decoder): """ ByteFallback Decoder ByteFallback is a simple trick which converts tokens looking like `<0x61>` to pure bytes, and attempts to make them into a string. If the tokens cannot be decoded you will get � instead for each inconvertible byte token """ def __init__(self): pass def decode(self, tokens): """ Decode the given list of tokens to a final string Args: tokens (:obj:`List[str]`): The list of tokens to decode Returns: :obj:`str`: The decoded string """ pass class ByteLevel(Decoder): """ ByteLevel Decoder This decoder is to be used in tandem with the :class:`~tokenizers.pre_tokenizers.ByteLevel` :class:`~tokenizers.pre_tokenizers.PreTokenizer`. """ def __init__(self): pass def decode(self, tokens): """ Decode the given list of tokens to a final string Args: tokens (:obj:`List[str]`): The list of tokens to decode Returns: :obj:`str`: The decoded string """ pass class CTC(Decoder): """ CTC Decoder Args: pad_token (:obj:`str`, `optional`, defaults to :obj:`<pad>`): The pad token used by CTC to delimit a new token. word_delimiter_token (:obj:`str`, `optional`, defaults to :obj:`|`): The word delimiter token. It will be replaced by a <space> cleanup (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether to cleanup some tokenization artifacts. Mainly spaces before punctuation, and some abbreviated english forms. """ def __init__(self, pad_token="<pad>", word_delimiter_token="|", cleanup=True): pass def decode(self, tokens): """ Decode the given list of tokens to a final string Args: tokens (:obj:`List[str]`): The list of tokens to decode Returns: :obj:`str`: The decoded string """ pass class Fuse(Decoder): """ Fuse Decoder Fuse simply fuses every token into a single string. This is the last step of decoding, this decoder exists only if there is need to add other decoders *after* the fusion """ def __init__(self): pass def decode(self, tokens): """ Decode the given list of tokens to a final string Args: tokens (:obj:`List[str]`): The list of tokens to decode Returns: :obj:`str`: The decoded string """ pass class Metaspace(Decoder): """ Metaspace Decoder Args: replacement (:obj:`str`, `optional`, defaults to :obj:`▁`): The replacement character. Must be exactly one character. By default we use the `▁` (U+2581) meta symbol (Same as in SentencePiece). prepend_scheme (:obj:`str`, `optional`, defaults to :obj:`"always"`): Whether to add a space to the first word if there isn't already one. This lets us treat `hello` exactly like `say hello`. Choices: "always", "never", "first". First means the space is only added on the first token (relevant when special tokens are used or other pre_tokenizer are used). """ def __init__(self, replacement="▁", prepend_scheme="always", split=True): pass def decode(self, tokens): """ Decode the given list of tokens to a final string Args: tokens (:obj:`List[str]`): The list of tokens to decode Returns: :obj:`str`: The decoded string """ pass class Replace(Decoder): """ Replace Decoder This decoder is to be used in tandem with the :class:`~tokenizers.pre_tokenizers.Replace` :class:`~tokenizers.pre_tokenizers.PreTokenizer`. """ def __init__(self, pattern, content): pass def decode(self, tokens): """ Decode the given list of tokens to a final string Args: tokens (:obj:`List[str]`): The list of tokens to decode Returns: :obj:`str`: The decoded string """ pass class Sequence(Decoder): """ Sequence Decoder Args: decoders (:obj:`List[Decoder]`) The decoders that need to be chained """ def __init__(self, decoders): pass def decode(self, tokens): """ Decode the given list of tokens to a final string Args: tokens (:obj:`List[str]`): The list of tokens to decode Returns: :obj:`str`: The decoded string """ pass class Strip(Decoder): """ Strip normalizer Strips n left characters of each token, or n right characters of each token """ def __init__(self, content, left=0, right=0): pass def decode(self, tokens): """ Decode the given list of tokens to a final string Args: tokens (:obj:`List[str]`): The list of tokens to decode Returns: :obj:`str`: The decoded string """ pass class WordPiece(Decoder): """ WordPiece Decoder Args: prefix (:obj:`str`, `optional`, defaults to :obj:`##`): The prefix to use for subwords that are not a beginning-of-word cleanup (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether to cleanup some tokenization artifacts. Mainly spaces before punctuation, and some abbreviated english forms. """ def __init__(self, prefix="##", cleanup=True): pass def decode(self, tokens): """ Decode the given list of tokens to a final string Args: tokens (:obj:`List[str]`): The list of tokens to decode Returns: :obj:`str`: The decoded string """ pass
tokenizers/bindings/python/py_src/tokenizers/decoders/__init__.pyi/0
{ "file_path": "tokenizers/bindings/python/py_src/tokenizers/decoders/__init__.pyi", "repo_id": "tokenizers", "token_count": 3236 }
331
from .visualizer import Annotation, EncodingVisualizer
tokenizers/bindings/python/py_src/tokenizers/tools/__init__.py/0
{ "file_path": "tokenizers/bindings/python/py_src/tokenizers/tools/__init__.py", "repo_id": "tokenizers", "token_count": 13 }
332
use pyo3::exceptions::PyException; use pyo3::types::*; use pyo3::{exceptions, prelude::*}; use std::sync::{Arc, RwLock}; use crate::error::ToPyResult; use crate::utils::{PyNormalizedString, PyNormalizedStringRefMut, PyPattern}; use serde::ser::SerializeStruct; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use tk::normalizers::{ BertNormalizer, ByteLevel, Lowercase, Nmt, NormalizerWrapper, Precompiled, Prepend, Replace, Strip, StripAccents, NFC, NFD, NFKC, NFKD, }; use tk::{NormalizedString, Normalizer}; use tokenizers as tk; /// Represents the different kind of NormalizedString we can receive from Python: /// - Owned: Created in Python and owned by Python /// - RefMut: A mutable reference to a NormalizedString owned by Rust #[derive(FromPyObject)] enum PyNormalizedStringMut<'p> { Owned(PyRefMut<'p, PyNormalizedString>), RefMut(PyNormalizedStringRefMut), } impl PyNormalizedStringMut<'_> { /// Normalized the underlying `NormalizedString` using the provided normalizer pub fn normalize_with<N>(&mut self, normalizer: &N) -> PyResult<()> where N: Normalizer, { match self { PyNormalizedStringMut::Owned(ref mut n) => normalizer.normalize(&mut n.normalized), PyNormalizedStringMut::RefMut(n) => n.map_as_mut(|n| normalizer.normalize(n))?, } .map_err(|e| exceptions::PyException::new_err(format!("{e}"))) } } /// Base class for all normalizers /// /// This class is not supposed to be instantiated directly. Instead, any implementation of a /// Normalizer will return an instance of this class when instantiated. #[pyclass(dict, module = "tokenizers.normalizers", name = "Normalizer", subclass)] #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(transparent)] pub struct PyNormalizer { pub(crate) normalizer: PyNormalizerTypeWrapper, } impl PyNormalizer { pub(crate) fn new(normalizer: PyNormalizerTypeWrapper) -> Self { PyNormalizer { normalizer } } pub(crate) fn get_as_subtype(&self, py: Python<'_>) -> PyResult<PyObject> { let base = self.clone(); Ok(match self.normalizer { PyNormalizerTypeWrapper::Sequence(_) => Py::new(py, (PySequence {}, base))? .into_pyobject(py)? .into_any() .into(), PyNormalizerTypeWrapper::Single(ref inner) => match &*inner .as_ref() .read() .map_err(|_| PyException::new_err("RwLock synchronisation primitive is poisoned, cannot get subtype of PyNormalizer"))? { PyNormalizerWrapper::Custom(_) => { Py::new(py, base)?.into_pyobject(py)?.into_any().into() } PyNormalizerWrapper::Wrapped(ref inner) => match inner { NormalizerWrapper::Sequence(_) => Py::new(py, (PySequence {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::BertNormalizer(_) => { Py::new(py, (PyBertNormalizer {}, base))? .into_pyobject(py)? .into_any() .into() } NormalizerWrapper::StripNormalizer(_) => Py::new(py, (PyStrip {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::Prepend(_) => Py::new(py, (PyPrepend {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::ByteLevel(_) => Py::new(py, (PyByteLevel {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::StripAccents(_) => Py::new(py, (PyStripAccents {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::NFC(_) => Py::new(py, (PyNFC {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::NFD(_) => Py::new(py, (PyNFD {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::NFKC(_) => Py::new(py, (PyNFKC {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::NFKD(_) => Py::new(py, (PyNFKD {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::Lowercase(_) => Py::new(py, (PyLowercase {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::Precompiled(_) => Py::new(py, (PyPrecompiled {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::Replace(_) => Py::new(py, (PyReplace {}, base))? .into_pyobject(py)? .into_any() .into(), NormalizerWrapper::Nmt(_) => Py::new(py, (PyNmt {}, base))? .into_pyobject(py)? .into_any() .into(), }, }, }) } } impl Normalizer for PyNormalizer { fn normalize(&self, normalized: &mut NormalizedString) -> tk::Result<()> { self.normalizer.normalize(normalized) } } #[pymethods] impl PyNormalizer { #[staticmethod] fn custom(obj: PyObject) -> Self { Self { normalizer: PyNormalizerWrapper::Custom(CustomNormalizer::new(obj)).into(), } } fn __getstate__(&self, py: Python) -> PyResult<PyObject> { let data = serde_json::to_string(&self.normalizer).map_err(|e| { exceptions::PyException::new_err(format!( "Error while attempting to pickle Normalizer: {e}" )) })?; Ok(PyBytes::new(py, data.as_bytes()).into()) } fn __setstate__(&mut self, py: Python, state: PyObject) -> PyResult<()> { match state.extract::<&[u8]>(py) { Ok(s) => { self.normalizer = serde_json::from_slice(s).map_err(|e| { exceptions::PyException::new_err(format!( "Error while attempting to unpickle Normalizer: {e}" )) })?; Ok(()) } Err(e) => Err(e), } } /// Normalize a :class:`~tokenizers.NormalizedString` in-place /// /// This method allows to modify a :class:`~tokenizers.NormalizedString` to /// keep track of the alignment information. If you just want to see the result /// of the normalization on a raw string, you can use /// :meth:`~tokenizers.normalizers.Normalizer.normalize_str` /// /// Args: /// normalized (:class:`~tokenizers.NormalizedString`): /// The normalized string on which to apply this /// :class:`~tokenizers.normalizers.Normalizer` #[pyo3(text_signature = "(self, normalized)")] fn normalize(&self, mut normalized: PyNormalizedStringMut) -> PyResult<()> { normalized.normalize_with(&self.normalizer) } /// Normalize the given string /// /// This method provides a way to visualize the effect of a /// :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment /// information. If you need to get/convert offsets, you can use /// :meth:`~tokenizers.normalizers.Normalizer.normalize` /// /// Args: /// sequence (:obj:`str`): /// A string to normalize /// /// Returns: /// :obj:`str`: A string after normalization #[pyo3(text_signature = "(self, sequence)")] fn normalize_str(&self, sequence: &str) -> PyResult<String> { let mut normalized = NormalizedString::from(sequence); ToPyResult(self.normalizer.normalize(&mut normalized)).into_py()?; Ok(normalized.get().to_owned()) } fn __repr__(&self) -> PyResult<String> { crate::utils::serde_pyo3::repr(self) .map_err(|e| exceptions::PyException::new_err(e.to_string())) } fn __str__(&self) -> PyResult<String> { crate::utils::serde_pyo3::to_string(self) .map_err(|e| exceptions::PyException::new_err(e.to_string())) } } macro_rules! getter { ($self: ident, $variant: ident, $name: ident) => {{ let super_ = $self.as_ref(); if let PyNormalizerTypeWrapper::Single(ref norm) = super_.normalizer { let wrapper = norm.read().expect( "RwLock synchronisation primitive is poisoned, cannot get subtype of PyNormalizer", ); if let PyNormalizerWrapper::Wrapped(NormalizerWrapper::$variant(o)) = (&*wrapper) { o.$name.clone() } else { unreachable!() } } else { unreachable!() } }}; } macro_rules! setter { ($self: ident, $variant: ident, $name: ident, $value: expr) => {{ let super_ = $self.as_ref(); if let PyNormalizerTypeWrapper::Single(ref norm) = super_.normalizer { let mut wrapper = norm.write().expect( "RwLock synchronisation primitive is poisoned, cannot get subtype of PyNormalizer", ); if let PyNormalizerWrapper::Wrapped(NormalizerWrapper::$variant(ref mut o)) = *wrapper { o.$name = $value; } } }}; } /// BertNormalizer /// /// Takes care of normalizing raw text before giving it to a Bert model. /// This includes cleaning the text, handling accents, chinese chars and lowercasing /// /// Args: /// clean_text (:obj:`bool`, `optional`, defaults to :obj:`True`): /// Whether to clean the text, by removing any control characters /// and replacing all whitespaces by the classic one. /// /// handle_chinese_chars (:obj:`bool`, `optional`, defaults to :obj:`True`): /// Whether to handle chinese chars by putting spaces around them. /// /// strip_accents (:obj:`bool`, `optional`): /// Whether to strip all accents. If this option is not specified (ie == None), /// then it will be determined by the value for `lowercase` (as in the original Bert). /// /// lowercase (:obj:`bool`, `optional`, defaults to :obj:`True`): /// Whether to lowercase. #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "BertNormalizer")] pub struct PyBertNormalizer {} #[pymethods] impl PyBertNormalizer { #[getter] fn get_clean_text(self_: PyRef<Self>) -> bool { getter!(self_, BertNormalizer, clean_text) } #[setter] fn set_clean_text(self_: PyRef<Self>, clean_text: bool) { setter!(self_, BertNormalizer, clean_text, clean_text); } #[getter] fn get_handle_chinese_chars(self_: PyRef<Self>) -> bool { getter!(self_, BertNormalizer, handle_chinese_chars) } #[setter] fn set_handle_chinese_chars(self_: PyRef<Self>, handle_chinese_chars: bool) { setter!( self_, BertNormalizer, handle_chinese_chars, handle_chinese_chars ); } #[getter] fn get_strip_accents(self_: PyRef<Self>) -> Option<bool> { getter!(self_, BertNormalizer, strip_accents) } #[setter] fn set_strip_accents(self_: PyRef<Self>, strip_accents: Option<bool>) { setter!(self_, BertNormalizer, strip_accents, strip_accents); } #[getter] fn get_lowercase(self_: PyRef<Self>) -> bool { getter!(self_, BertNormalizer, lowercase) } #[setter] fn set_lowercase(self_: PyRef<Self>, lowercase: bool) { setter!(self_, BertNormalizer, lowercase, lowercase) } #[new] #[pyo3(signature = ( clean_text = true, handle_chinese_chars = true, strip_accents = None, lowercase = true ), text_signature = "(self, clean_text=True, handle_chinese_chars=True, strip_accents=None, lowercase=True)")] fn new( clean_text: bool, handle_chinese_chars: bool, strip_accents: Option<bool>, lowercase: bool, ) -> (Self, PyNormalizer) { let normalizer = BertNormalizer::new(clean_text, handle_chinese_chars, strip_accents, lowercase); (PyBertNormalizer {}, normalizer.into()) } } /// NFD Unicode Normalizer #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "NFD")] pub struct PyNFD {} #[pymethods] impl PyNFD { #[new] #[pyo3(text_signature = "(self)")] fn new() -> (Self, PyNormalizer) { (PyNFD {}, PyNormalizer::new(NFD.into())) } } /// NFKD Unicode Normalizer #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "NFKD")] pub struct PyNFKD {} #[pymethods] impl PyNFKD { #[new] #[pyo3(text_signature = "(self)")] fn new() -> (Self, PyNormalizer) { (PyNFKD {}, NFKD.into()) } } /// NFC Unicode Normalizer #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "NFC")] pub struct PyNFC {} #[pymethods] impl PyNFC { #[new] #[pyo3(text_signature = "(self)")] fn new() -> (Self, PyNormalizer) { (PyNFC {}, NFC.into()) } } /// NFKC Unicode Normalizer #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "NFKC")] pub struct PyNFKC {} #[pymethods] impl PyNFKC { #[new] #[pyo3(text_signature = "(self)")] fn new() -> (Self, PyNormalizer) { (PyNFKC {}, NFKC.into()) } } /// Allows concatenating multiple other Normalizer as a Sequence. /// All the normalizers run in sequence in the given order /// /// Args: /// normalizers (:obj:`List[Normalizer]`): /// A list of Normalizer to be run as a sequence #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "Sequence")] pub struct PySequence {} #[pymethods] impl PySequence { #[new] #[pyo3(text_signature = None)] fn new(normalizers: &Bound<'_, PyList>) -> PyResult<(Self, PyNormalizer)> { let mut sequence = Vec::with_capacity(normalizers.len()); for n in normalizers.iter() { let normalizer: PyRef<PyNormalizer> = n.extract()?; match &normalizer.normalizer { PyNormalizerTypeWrapper::Sequence(inner) => sequence.extend(inner.iter().cloned()), PyNormalizerTypeWrapper::Single(inner) => sequence.push(inner.clone()), } } Ok(( PySequence {}, PyNormalizer::new(PyNormalizerTypeWrapper::Sequence(sequence)), )) } fn __getnewargs__<'p>(&self, py: Python<'p>) -> PyResult<Bound<'p, PyTuple>> { PyTuple::new(py, [PyList::empty(py)]) } fn __len__(self_: PyRef<'_, Self>) -> usize { match &self_.as_ref().normalizer { PyNormalizerTypeWrapper::Sequence(inner) => inner.len(), PyNormalizerTypeWrapper::Single(_) => 1, } } fn __getitem__(self_: PyRef<'_, Self>, py: Python<'_>, index: usize) -> PyResult<Py<PyAny>> { match &self_.as_ref().normalizer { PyNormalizerTypeWrapper::Sequence(inner) => match inner.get(index) { Some(item) => PyNormalizer::new(PyNormalizerTypeWrapper::Single(item.clone())) .get_as_subtype(py), _ => Err(PyErr::new::<pyo3::exceptions::PyIndexError, _>( "Index not found", )), }, PyNormalizerTypeWrapper::Single(inner) => { PyNormalizer::new(PyNormalizerTypeWrapper::Single(inner.clone())).get_as_subtype(py) } } } fn __setitem__(self_: PyRef<'_, Self>, index: usize, value: Bound<'_, PyAny>) -> PyResult<()> { let norm: PyNormalizer = value.extract()?; let PyNormalizerTypeWrapper::Single(norm) = norm.normalizer else { return Err(PyException::new_err("normalizer should not be a sequence")); }; match &self_.as_ref().normalizer { PyNormalizerTypeWrapper::Sequence(inner) => match inner.get(index) { Some(item) => { *item .write() .map_err(|_| PyException::new_err("RwLock synchronisation primitive is poisoned, cannot get subtype of PyNormalizer"))? = norm .read() .map_err(|_| PyException::new_err("RwLock synchronisation primitive is poisoned, cannot get subtype of PyNormalizer"))? .clone(); } _ => { return Err(PyErr::new::<pyo3::exceptions::PyIndexError, _>( "Index not found", )) } }, PyNormalizerTypeWrapper::Single(_) => { return Err(PyException::new_err("normalizer is not a sequence")) } }; Ok(()) } } /// Lowercase Normalizer #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "Lowercase")] pub struct PyLowercase {} #[pymethods] impl PyLowercase { #[new] #[pyo3(text_signature = "(self)")] fn new() -> (Self, PyNormalizer) { (PyLowercase {}, Lowercase.into()) } } /// Strip normalizer #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "Strip")] pub struct PyStrip {} #[pymethods] impl PyStrip { #[getter] fn get_left(self_: PyRef<Self>) -> bool { getter!(self_, StripNormalizer, strip_left) } #[setter] fn set_left(self_: PyRef<Self>, left: bool) { setter!(self_, StripNormalizer, strip_left, left) } #[getter] fn get_right(self_: PyRef<Self>) -> bool { getter!(self_, StripNormalizer, strip_right) } #[setter] fn set_right(self_: PyRef<Self>, right: bool) { setter!(self_, StripNormalizer, strip_right, right) } #[new] #[pyo3(signature = (left = true, right = true), text_signature = "(self, left=True, right=True)")] fn new(left: bool, right: bool) -> (Self, PyNormalizer) { (PyStrip {}, Strip::new(left, right).into()) } } /// Prepend normalizer #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "Prepend")] pub struct PyPrepend {} #[pymethods] impl PyPrepend { #[getter] fn get_prepend(self_: PyRef<Self>) -> String { getter!(self_, Prepend, prepend) } #[setter] fn set_prepend(self_: PyRef<Self>, prepend: String) { setter!(self_, Prepend, prepend, prepend) } #[new] #[pyo3(signature = (prepend="▁".to_string()), text_signature = "(self, prepend)")] fn new(prepend: String) -> (Self, PyNormalizer) { (PyPrepend {}, Prepend::new(prepend).into()) } } /// Bytelevel Normalizer #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "ByteLevel")] pub struct PyByteLevel {} #[pymethods] impl PyByteLevel { #[new] #[pyo3(text_signature = "(self)")] fn new() -> (Self, PyNormalizer) { (PyByteLevel {}, ByteLevel::new().into()) } } /// StripAccents normalizer #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "StripAccents")] pub struct PyStripAccents {} #[pymethods] impl PyStripAccents { #[new] #[pyo3(text_signature = "(self)")] fn new() -> (Self, PyNormalizer) { (PyStripAccents {}, StripAccents.into()) } } /// Nmt normalizer #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "Nmt")] pub struct PyNmt {} #[pymethods] impl PyNmt { #[new] #[pyo3(text_signature = "(self)")] fn new() -> (Self, PyNormalizer) { (PyNmt {}, Nmt.into()) } } /// Precompiled normalizer /// Don't use manually it is used for compatibility for SentencePiece. #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "Precompiled")] pub struct PyPrecompiled {} #[pymethods] impl PyPrecompiled { #[new] #[pyo3(text_signature = "(self, precompiled_charsmap)")] fn new(precompiled_charsmap: Vec<u8>) -> PyResult<(Self, PyNormalizer)> { // let precompiled_charsmap: Vec<u8> = FromPyObject::extract(py_precompiled_charsmap)?; Ok(( PyPrecompiled {}, Precompiled::from(&precompiled_charsmap) .map_err(|e| { exceptions::PyException::new_err(format!( "Error while attempting to build Precompiled normalizer: {e}" )) })? .into(), )) } } /// Replace normalizer #[pyclass(extends=PyNormalizer, module = "tokenizers.normalizers", name = "Replace")] pub struct PyReplace {} #[pymethods] impl PyReplace { #[new] #[pyo3(text_signature = "(self, pattern, content)")] fn new(pattern: PyPattern, content: String) -> PyResult<(Self, PyNormalizer)> { Ok(( PyReplace {}, ToPyResult(Replace::new(pattern, content)).into_py()?.into(), )) } #[getter] fn get_pattern(_self: PyRef<Self>) -> PyResult<()> { Err(PyException::new_err("Cannot get pattern")) } #[setter] fn set_pattern(_self: PyRef<Self>, _pattern: PyPattern) -> PyResult<()> { Err(PyException::new_err( "Cannot set pattern, please instantiate a new replace pattern instead", )) } #[getter] fn get_content(self_: PyRef<Self>) -> String { getter!(self_, Replace, content) } #[setter] fn set_content(self_: PyRef<Self>, content: String) { setter!(self_, Replace, content, content) } } #[derive(Clone, Debug)] pub(crate) struct CustomNormalizer { inner: PyObject, } impl CustomNormalizer { pub fn new(inner: PyObject) -> Self { Self { inner } } } impl tk::tokenizer::Normalizer for CustomNormalizer { fn normalize(&self, normalized: &mut NormalizedString) -> tk::Result<()> { Python::with_gil(|py| { let normalized = PyNormalizedStringRefMut::new(normalized); let py_normalized = self.inner.bind(py); py_normalized.call_method("normalize", (normalized.get().clone(),), None)?; Ok(()) }) } } impl Serialize for CustomNormalizer { fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { Err(serde::ser::Error::custom( "Custom Normalizer cannot be serialized", )) } } impl<'de> Deserialize<'de> for CustomNormalizer { fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { Err(serde::de::Error::custom( "Custom Normalizer cannot be deserialized", )) } } #[derive(Clone, Debug, Deserialize)] #[serde(untagged)] pub(crate) enum PyNormalizerWrapper { Custom(CustomNormalizer), Wrapped(NormalizerWrapper), } impl Serialize for PyNormalizerWrapper { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { match self { PyNormalizerWrapper::Wrapped(inner) => inner.serialize(serializer), PyNormalizerWrapper::Custom(inner) => inner.serialize(serializer), } } } #[derive(Debug, Clone)] pub(crate) enum PyNormalizerTypeWrapper { Sequence(Vec<Arc<RwLock<PyNormalizerWrapper>>>), Single(Arc<RwLock<PyNormalizerWrapper>>), } /// XXX: we need to manually implement deserialize here because of the structure of the /// PyNormalizerTypeWrapper enum. Given the underlying PyNormalizerWrapper can contain a Sequence, /// default deserialization will give us a PyNormalizerTypeWrapper::Single(Sequence) when we'd like /// it to be PyNormalizerTypeWrapper::Sequence(// ...). impl<'de> Deserialize<'de> for PyNormalizerTypeWrapper { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let wrapper = NormalizerWrapper::deserialize(deserializer)?; let py_wrapper: PyNormalizerWrapper = wrapper.into(); Ok(py_wrapper.into()) } } impl Serialize for PyNormalizerTypeWrapper { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { PyNormalizerTypeWrapper::Sequence(seq) => { let mut ser = serializer.serialize_struct("Sequence", 2)?; ser.serialize_field("type", "Sequence")?; ser.serialize_field("normalizers", seq)?; ser.end() } PyNormalizerTypeWrapper::Single(inner) => inner.serialize(serializer), } } } impl<I> From<I> for PyNormalizerWrapper where I: Into<NormalizerWrapper>, { fn from(norm: I) -> Self { PyNormalizerWrapper::Wrapped(norm.into()) } } impl<I> From<I> for PyNormalizerTypeWrapper where I: Into<PyNormalizerWrapper>, { fn from(norm: I) -> Self { let norm = norm.into(); match norm { PyNormalizerWrapper::Wrapped(NormalizerWrapper::Sequence(seq)) => { PyNormalizerTypeWrapper::Sequence( seq.into_iter() .map(|e| Arc::new(RwLock::new(PyNormalizerWrapper::Wrapped(e.clone())))) .collect(), ) } _ => PyNormalizerTypeWrapper::Single(Arc::new(RwLock::new(norm))), } } } impl<I> From<I> for PyNormalizer where I: Into<NormalizerWrapper>, { fn from(norm: I) -> Self { PyNormalizer { normalizer: norm.into().into(), } } } impl Normalizer for PyNormalizerTypeWrapper { fn normalize(&self, normalized: &mut NormalizedString) -> tk::Result<()> { match self { PyNormalizerTypeWrapper::Single(inner) => inner .read() .map_err(|_| PyException::new_err("RwLock synchronisation primitive is poisoned, cannot get subtype of PyNormalizer"))? .normalize(normalized), PyNormalizerTypeWrapper::Sequence(inner) => inner.iter().try_for_each(|n| { n.read() .map_err(|_| PyException::new_err("RwLock synchronisation primitive is poisoned, cannot get subtype of PyNormalizer"))? .normalize(normalized) }), } } } impl Normalizer for PyNormalizerWrapper { fn normalize(&self, normalized: &mut NormalizedString) -> tk::Result<()> { match self { PyNormalizerWrapper::Wrapped(inner) => inner.normalize(normalized), PyNormalizerWrapper::Custom(inner) => inner.normalize(normalized), } } } /// Normalizers Module #[pymodule] pub fn normalizers(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::<PyNormalizer>()?; m.add_class::<PyBertNormalizer>()?; m.add_class::<PyNFD>()?; m.add_class::<PyNFKD>()?; m.add_class::<PyNFC>()?; m.add_class::<PyNFKC>()?; m.add_class::<PySequence>()?; m.add_class::<PyLowercase>()?; m.add_class::<PyStrip>()?; m.add_class::<PyStripAccents>()?; m.add_class::<PyPrepend>()?; m.add_class::<PyByteLevel>()?; m.add_class::<PyNmt>()?; m.add_class::<PyPrecompiled>()?; m.add_class::<PyReplace>()?; Ok(()) } #[cfg(test)] mod test { use pyo3::prelude::*; use tk::normalizers::unicode::{NFC, NFKC}; use tk::normalizers::utils::Sequence; use tk::normalizers::NormalizerWrapper; use crate::normalizers::{PyNormalizer, PyNormalizerTypeWrapper, PyNormalizerWrapper}; #[test] fn get_subtype() { Python::with_gil(|py| { let py_norm = PyNormalizer::new(NFC.into()); let py_nfc = py_norm.get_as_subtype(py).unwrap(); assert_eq!("NFC", py_nfc.bind(py).get_type().qualname().unwrap()); }) } #[test] fn serialize() { let py_wrapped: PyNormalizerWrapper = NFKC.into(); let py_ser = serde_json::to_string(&py_wrapped).unwrap(); let rs_wrapped = NormalizerWrapper::NFKC(NFKC); let rs_ser = serde_json::to_string(&rs_wrapped).unwrap(); assert_eq!(py_ser, rs_ser); let py_norm: PyNormalizer = serde_json::from_str(&rs_ser).unwrap(); match py_norm.normalizer { PyNormalizerTypeWrapper::Single(inner) => match *inner.as_ref().read().unwrap() { PyNormalizerWrapper::Wrapped(NormalizerWrapper::NFKC(_)) => {} _ => panic!("Expected NFKC"), }, _ => panic!("Expected wrapped, not sequence."), } let py_seq: PyNormalizerWrapper = Sequence::new(vec![NFC.into(), NFKC.into()]).into(); let py_wrapper_ser = serde_json::to_string(&py_seq).unwrap(); let rs_wrapped = NormalizerWrapper::Sequence(Sequence::new(vec![NFC.into(), NFKC.into()])); let rs_ser = serde_json::to_string(&rs_wrapped).unwrap(); assert_eq!(py_wrapper_ser, rs_ser); let py_seq = PyNormalizer::new(py_seq.into()); let py_ser = serde_json::to_string(&py_seq).unwrap(); assert_eq!(py_wrapper_ser, py_ser); let rs_seq = Sequence::new(vec![NFC.into(), NFKC.into()]); let rs_ser = serde_json::to_string(&rs_seq).unwrap(); assert_eq!(py_wrapper_ser, rs_ser); } #[test] fn deserialize_sequence() { let string = r#"{"type": "NFKC"}"#; let normalizer: PyNormalizer = serde_json::from_str(string).unwrap(); match normalizer.normalizer { PyNormalizerTypeWrapper::Single(inner) => match *inner.as_ref().read().unwrap() { PyNormalizerWrapper::Wrapped(NormalizerWrapper::NFKC(_)) => {} _ => panic!("Expected NFKC"), }, _ => panic!("Expected wrapped, not sequence."), } let sequence_string = format!(r#"{{"type": "Sequence", "normalizers": [{string}]}}"#); let normalizer: PyNormalizer = serde_json::from_str(&sequence_string).unwrap(); match normalizer.normalizer { PyNormalizerTypeWrapper::Sequence(inner) => { assert_eq!(inner.len(), 1); match *inner[0].as_ref().read().unwrap() { PyNormalizerWrapper::Wrapped(NormalizerWrapper::NFKC(_)) => {} _ => panic!("Expected NFKC"), }; } _ => panic!("Expected sequence"), }; } }
tokenizers/bindings/python/src/normalizers.rs/0
{ "file_path": "tokenizers/bindings/python/src/normalizers.rs", "repo_id": "tokenizers", "token_count": 14563 }
333
import json import pickle import pytest from tokenizers.decoders import ( CTC, BPEDecoder, ByteLevel, Decoder, Metaspace, Sequence, WordPiece, ByteFallback, Replace, Strip, Fuse, ) class TestByteLevel: def test_instantiate(self): assert ByteLevel() is not None assert isinstance(ByteLevel(), Decoder) assert isinstance(ByteLevel(), ByteLevel) assert isinstance(pickle.loads(pickle.dumps(ByteLevel())), ByteLevel) def test_decoding(self): decoder = ByteLevel() assert decoder.decode(["My", "Ġname", "Ġis", "ĠJohn"]) == "My name is John" def test_manual_reload(self): byte_level = ByteLevel() state = json.loads(byte_level.__getstate__()) reloaded = ByteLevel(**state) assert isinstance(reloaded, ByteLevel) class TestReplace: def test_instantiate(self): assert Replace("_", " ") is not None assert isinstance(Replace("_", " "), Decoder) assert isinstance(Replace("_", " "), Replace) # assert isinstance(pickle.loads(pickle.dumps(Replace("_", " "))), Replace) def test_decoding(self): decoder = Replace("_", " ") assert decoder.decode(["My", "_name", "_is", "_John"]) == "My name is John" class TestWordPiece: def test_instantiate(self): assert WordPiece() is not None assert WordPiece(prefix="__") is not None assert WordPiece(cleanup=True) is not None assert isinstance(WordPiece(), Decoder) assert isinstance(WordPiece(), WordPiece) assert isinstance(pickle.loads(pickle.dumps(WordPiece())), WordPiece) def test_decoding(self): decoder = WordPiece() assert decoder.decode(["My", "na", "##me", "is", "Jo", "##hn"]) == "My name is John" assert decoder.decode(["I", "'m", "Jo", "##hn"]) == "I'm John" decoder = WordPiece(prefix="__", cleanup=False) assert decoder.decode(["My", "na", "__me", "is", "Jo", "__hn"]) == "My name is John" assert decoder.decode(["I", "'m", "Jo", "__hn"]) == "I 'm John" def test_can_modify(self): decoder = WordPiece(prefix="$$", cleanup=False) assert decoder.prefix == "$$" assert decoder.cleanup == False # Modify these decoder.prefix = "__" assert decoder.prefix == "__" decoder.cleanup = True assert decoder.cleanup == True class TestByteFallback: def test_instantiate(self): assert ByteFallback() is not None assert isinstance(ByteFallback(), Decoder) assert isinstance(ByteFallback(), ByteFallback) assert isinstance(pickle.loads(pickle.dumps(ByteFallback())), ByteFallback) def test_decoding(self): decoder = ByteFallback() assert decoder.decode(["My", " na", "me"]) == "My name" assert decoder.decode(["<0x61>"]) == "a" assert decoder.decode(["<0xE5>"]) == "�" assert decoder.decode(["<0xE5>", "<0x8f>"]) == "��" assert decoder.decode(["<0xE5>", "<0x8f>", "<0xab>"]) == "叫" assert decoder.decode(["<0xE5>", "<0x8f>", "a"]) == "��a" assert decoder.decode(["<0xE5>", "<0x8f>", "<0xab>", "a"]) == "叫a" class TestFuse: def test_instantiate(self): assert Fuse() is not None assert isinstance(Fuse(), Decoder) assert isinstance(Fuse(), Fuse) assert isinstance(pickle.loads(pickle.dumps(Fuse())), Fuse) def test_decoding(self): decoder = Fuse() assert decoder.decode(["My", " na", "me"]) == "My name" class TestStrip: def test_instantiate(self): assert Strip(left=0, right=0) is not None assert isinstance(Strip(content="_", left=0, right=0), Decoder) assert isinstance(Strip(content="_", left=0, right=0), Strip) assert isinstance(pickle.loads(pickle.dumps(Strip(content="_", left=0, right=0))), Strip) def test_decoding(self): decoder = Strip(content="_", left=1, right=0) assert decoder.decode(["_My", " na", "me", " _-", "__-"]) == "My name _-_-" class TestMetaspace: def test_instantiate(self): assert Metaspace() is not None assert Metaspace(replacement="-") is not None with pytest.raises(ValueError, match="expected a string of length 1"): Metaspace(replacement="") assert Metaspace(prepend_scheme="always") is not None assert isinstance(Metaspace(), Decoder) assert isinstance(Metaspace(), Metaspace) assert isinstance(pickle.loads(pickle.dumps(Metaspace())), Metaspace) def test_decoding(self): decoder = Metaspace() assert decoder.decode(["▁My", "▁name", "▁is", "▁John"]) == "My name is John" decoder = Metaspace(replacement="-", prepend_scheme="never") assert decoder.decode(["-My", "-name", "-is", "-John"]) == " My name is John" def test_can_modify(self): decoder = Metaspace(replacement="*", prepend_scheme="never") assert decoder.replacement == "*" assert decoder.prepend_scheme == "never" # Modify these decoder.replacement = "&" assert decoder.replacement == "&" decoder.prepend_scheme = "first" assert decoder.prepend_scheme == "first" class TestBPEDecoder: def test_instantiate(self): assert BPEDecoder() is not None assert BPEDecoder(suffix="_") is not None assert isinstance(BPEDecoder(), Decoder) assert isinstance(BPEDecoder(), BPEDecoder) assert isinstance(pickle.loads(pickle.dumps(BPEDecoder())), BPEDecoder) def test_decoding(self): decoder = BPEDecoder() assert decoder.decode(["My</w>", "na", "me</w>", "is</w>", "Jo", "hn</w>"]) == "My name is John" decoder = BPEDecoder(suffix="_") assert decoder.decode(["My_", "na", "me_", "is_", "Jo", "hn_"]) == "My name is John" def test_can_modify(self): decoder = BPEDecoder(suffix="123") assert decoder.suffix == "123" # Modify these decoder.suffix = "</w>" assert decoder.suffix == "</w>" class TestCTCDecoder: def test_instantiate(self): assert CTC() is not None assert CTC(pad_token="[PAD]") is not None assert isinstance(CTC(), Decoder) assert isinstance(CTC(), CTC) assert isinstance(pickle.loads(pickle.dumps(CTC())), CTC) def test_decoding(self): decoder = CTC() assert ( decoder.decode(["<pad>", "<pad>", "h", "e", "e", "l", "l", "<pad>", "l", "o", "o", "o", "<pad>"]) == "hello" ) decoder = CTC(pad_token="[PAD]") assert ( decoder.decode(["[PAD]", "[PAD]", "h", "e", "e", "l", "l", "[PAD]", "l", "o", "o", "o", "[PAD]"]) == "hello" ) def test_can_modify(self): decoder = CTC(pad_token="[PAD]") assert decoder.pad_token == "[PAD]" assert decoder.word_delimiter_token == "|" assert decoder.cleanup == True # Modify these decoder.pad_token = "{pad}" assert decoder.pad_token == "{pad}" decoder.word_delimiter_token = "_" assert decoder.word_delimiter_token == "_" decoder.cleanup = False assert decoder.cleanup == False class TestSequenceDecoder: def test_instantiate(self): assert Sequence([]) is not None assert Sequence([CTC()]) is not None assert isinstance(Sequence([]), Decoder) assert isinstance(Sequence([]), Sequence) serialized = pickle.dumps(Sequence([])) assert isinstance(pickle.loads(serialized), Sequence) def test_decoding(self): decoder = Sequence([CTC(), Metaspace()]) initial = ["▁", "▁", "H", "H", "i", "i", "▁", "y", "o", "u"] expected = "Hi you" assert decoder.decode(initial) == expected
tokenizers/bindings/python/tests/bindings/test_decoders.py/0
{ "file_path": "tokenizers/bindings/python/tests/bindings/test_decoders.py", "repo_id": "tokenizers", "token_count": 3527 }
334
# Tokenizer <tokenizerslangcontent> <python> ## Tokenizer [[autodoc]] tokenizers.Tokenizer - all - decoder - model - normalizer - padding - post_processor - pre_tokenizer - truncation </python> <rust> The Rust API Reference is available directly on the [Docs.rs](https://docs.rs/tokenizers/latest/tokenizers/) website. </rust> <node> The node API has not been documented yet. </node> </tokenizerslangcontent>
tokenizers/docs/source-doc-builder/api/tokenizer.mdx/0
{ "file_path": "tokenizers/docs/source-doc-builder/api/tokenizer.mdx", "repo_id": "tokenizers", "token_count": 156 }
335
.highlight .c1, .highlight .sd{ color: #999 } .highlight .nn, .highlight .k, .highlight .s1, .highlight .nb, .highlight .bp, .highlight .kc, .highlight .kt { color: #FB8D68; } .highlight .kn, .highlight .nv, .highlight .s2, .highlight .ow, .highlight .kd, .highlight .kr, .highlight .s { color: #6670FF; } .highlight .gp { color: #FB8D68; }
tokenizers/docs/source/_static/css/code-snippets.css/0
{ "file_path": "tokenizers/docs/source/_static/css/code-snippets.css", "repo_id": "tokenizers", "token_count": 166 }
336
Quicktour ==================================================================================================== Let's have a quick look at the 🤗 Tokenizers library features. The library provides an implementation of today's most used tokenizers that is both easy to use and blazing fast. .. only:: python It can be used to instantiate a :ref:`pretrained tokenizer <pretrained>` but we will start our quicktour by building one from scratch and see how we can train it. Build a tokenizer from scratch ---------------------------------------------------------------------------------------------------- To illustrate how fast the 🤗 Tokenizers library is, let's train a new tokenizer on `wikitext-103 <https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/>`__ (516M of text) in just a few seconds. First things first, you will need to download this dataset and unzip it with: .. code-block:: bash wget https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-103-raw-v1.zip unzip wikitext-103-raw-v1.zip Training the tokenizer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. entities:: python BpeTrainer :class:`~tokenizers.trainers.BpeTrainer` vocab_size :obj:`vocab_size` min_frequency :obj:`min_frequency` special_tokens :obj:`special_tokens` unk_token :obj:`unk_token` pad_token :obj:`pad_token` .. entities:: rust BpeTrainer :rust_struct:`~tokenizers::models::bpe::BpeTrainer` vocab_size :obj:`vocab_size` min_frequency :obj:`min_frequency` special_tokens :obj:`special_tokens` unk_token :obj:`unk_token` pad_token :obj:`pad_token` .. entities:: node BpeTrainer BpeTrainer vocab_size :obj:`vocabSize` min_frequency :obj:`minFrequency` special_tokens :obj:`specialTokens` unk_token :obj:`unkToken` pad_token :obj:`padToken` In this tour, we will build and train a Byte-Pair Encoding (BPE) tokenizer. For more information about the different type of tokenizers, check out this `guide <https://huggingface.co/docs/transformers/main/en/tokenizer_summary#summary-of-the-tokenizers>`__ in the 🤗 Transformers documentation. Here, training the tokenizer means it will learn merge rules by: - Start with all the characters present in the training corpus as tokens. - Identify the most common pair of tokens and merge it into one token. - Repeat until the vocabulary (e.g., the number of tokens) has reached the size we want. The main API of the library is the :entity:`class` :entity:`Tokenizer`, here is how we instantiate one with a BPE model: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START init_tokenizer :end-before: END init_tokenizer :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_init_tokenizer :end-before: END quicktour_init_tokenizer :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START init_tokenizer :end-before: END init_tokenizer :dedent: 4 To train our tokenizer on the wikitext files, we will need to instantiate a `trainer`, in this case a :entity:`BpeTrainer` .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START init_trainer :end-before: END init_trainer :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_init_trainer :end-before: END quicktour_init_trainer :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START init_trainer :end-before: END init_trainer :dedent: 4 We can set the training arguments like :entity:`vocab_size` or :entity:`min_frequency` (here left at their default values of 30,000 and 0) but the most important part is to give the :entity:`special_tokens` we plan to use later on (they are not used at all during training) so that they get inserted in the vocabulary. .. note:: The order in which you write the special tokens list matters: here :obj:`"[UNK]"` will get the ID 0, :obj:`"[CLS]"` will get the ID 1 and so forth. We could train our tokenizer right now, but it wouldn't be optimal. Without a pre-tokenizer that will split our inputs into words, we might get tokens that overlap several words: for instance we could get an :obj:`"it is"` token since those two words often appear next to each other. Using a pre-tokenizer will ensure no token is bigger than a word returned by the pre-tokenizer. Here we want to train a subword BPE tokenizer, and we will use the easiest pre-tokenizer possible by splitting on whitespace. .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START init_pretok :end-before: END init_pretok :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_init_pretok :end-before: END quicktour_init_pretok :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START init_pretok :end-before: END init_pretok :dedent: 4 Now, we can just call the :entity:`Tokenizer.train` method with any list of files we want to use: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START train :end-before: END train :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_train :end-before: END quicktour_train :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START train :end-before: END train :dedent: 4 This should only take a few seconds to train our tokenizer on the full wikitext dataset! To save the tokenizer in one file that contains all its configuration and vocabulary, just use the :entity:`Tokenizer.save` method: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START save :end-before: END save :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_save :end-before: END quicktour_save :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START save :end-before: END save :dedent: 4 and you can reload your tokenizer from that file with the :entity:`Tokenizer.from_file` :entity:`classmethod`: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START reload_tokenizer :end-before: END reload_tokenizer :dedent: 12 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_reload_tokenizer :end-before: END quicktour_reload_tokenizer :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START reload_tokenizer :end-before: END reload_tokenizer :dedent: 4 Using the tokenizer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Now that we have trained a tokenizer, we can use it on any text we want with the :entity:`Tokenizer.encode` method: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START encode :end-before: END encode :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_encode :end-before: END quicktour_encode :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START encode :end-before: END encode :dedent: 4 This applied the full pipeline of the tokenizer on the text, returning an :entity:`Encoding` object. To learn more about this pipeline, and how to apply (or customize) parts of it, check out :doc:`this page <pipeline>`. This :entity:`Encoding` object then has all the attributes you need for your deep learning model (or other). The :obj:`tokens` attribute contains the segmentation of your text in tokens: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START print_tokens :end-before: END print_tokens :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_print_tokens :end-before: END quicktour_print_tokens :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START print_tokens :end-before: END print_tokens :dedent: 4 Similarly, the :obj:`ids` attribute will contain the index of each of those tokens in the tokenizer's vocabulary: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START print_ids :end-before: END print_ids :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_print_ids :end-before: END quicktour_print_ids :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START print_ids :end-before: END print_ids :dedent: 4 An important feature of the 🤗 Tokenizers library is that it comes with full alignment tracking, meaning you can always get the part of your original sentence that corresponds to a given token. Those are stored in the :obj:`offsets` attribute of our :entity:`Encoding` object. For instance, let's assume we would want to find back what caused the :obj:`"[UNK]"` token to appear, which is the token at index 9 in the list, we can just ask for the offset at the index: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START print_offsets :end-before: END print_offsets :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_print_offsets :end-before: END quicktour_print_offsets :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START print_offsets :end-before: END print_offsets :dedent: 4 and those are the indices that correspond to the emoji in the original sentence: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START use_offsets :end-before: END use_offsets :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_use_offsets :end-before: END quicktour_use_offsets :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START use_offsets :end-before: END use_offsets :dedent: 4 Post-processing ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We might want our tokenizer to automatically add special tokens, like :obj:`"[CLS]"` or :obj:`"[SEP]"`. To do this, we use a post-processor. :entity:`TemplateProcessing` is the most commonly used, you just have to specify a template for the processing of single sentences and pairs of sentences, along with the special tokens and their IDs. When we built our tokenizer, we set :obj:`"[CLS]"` and :obj:`"[SEP]"` in positions 1 and 2 of our list of special tokens, so this should be their IDs. To double-check, we can use the :entity:`Tokenizer.token_to_id` method: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START check_sep :end-before: END check_sep :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_check_sep :end-before: END quicktour_check_sep :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START check_sep :end-before: END check_sep :dedent: 4 Here is how we can set the post-processing to give us the traditional BERT inputs: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START init_template_processing :end-before: END init_template_processing :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_init_template_processing :end-before: END quicktour_init_template_processing :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START init_template_processing :end-before: END init_template_processing :dedent: 4 Let's go over this snippet of code in more details. First we specify the template for single sentences: those should have the form :obj:`"[CLS] $A [SEP]"` where :obj:`$A` represents our sentence. Then, we specify the template for sentence pairs, which should have the form :obj:`"[CLS] $A [SEP] $B [SEP]"` where :obj:`$A` represents the first sentence and :obj:`$B` the second one. The :obj:`:1` added in the template represent the `type IDs` we want for each part of our input: it defaults to 0 for everything (which is why we don't have :obj:`$A:0`) and here we set it to 1 for the tokens of the second sentence and the last :obj:`"[SEP]"` token. Lastly, we specify the special tokens we used and their IDs in our tokenizer's vocabulary. To check out this worked properly, let's try to encode the same sentence as before: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START print_special_tokens :end-before: END print_special_tokens :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_print_special_tokens :end-before: END quicktour_print_special_tokens :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START print_special_tokens :end-before: END print_special_tokens :dedent: 4 To check the results on a pair of sentences, we just pass the two sentences to :entity:`Tokenizer.encode`: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START print_special_tokens_pair :end-before: END print_special_tokens_pair :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_print_special_tokens_pair :end-before: END quicktour_print_special_tokens_pair :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START print_special_tokens_pair :end-before: END print_special_tokens_pair :dedent: 4 You can then check the type IDs attributed to each token is correct with .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START print_type_ids :end-before: END print_type_ids :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_print_type_ids :end-before: END quicktour_print_type_ids :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START print_type_ids :end-before: END print_type_ids :dedent: 4 If you save your tokenizer with :entity:`Tokenizer.save`, the post-processor will be saved along. Encoding multiple sentences in a batch ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To get the full speed of the 🤗 Tokenizers library, it's best to process your texts by batches by using the :entity:`Tokenizer.encode_batch` method: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START encode_batch :end-before: END encode_batch :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_encode_batch :end-before: END quicktour_encode_batch :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START encode_batch :end-before: END encode_batch :dedent: 4 The output is then a list of :entity:`Encoding` objects like the ones we saw before. You can process together as many texts as you like, as long as it fits in memory. To process a batch of sentences pairs, pass two lists to the :entity:`Tokenizer.encode_batch` method: the list of sentences A and the list of sentences B: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START encode_batch_pair :end-before: END encode_batch_pair :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_encode_batch_pair :end-before: END quicktour_encode_batch_pair :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START encode_batch_pair :end-before: END encode_batch_pair :dedent: 4 When encoding multiple sentences, you can automatically pad the outputs to the longest sentence present by using :entity:`Tokenizer.enable_padding`, with the :entity:`pad_token` and its ID (which we can double-check the id for the padding token with :entity:`Tokenizer.token_to_id` like before): .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START enable_padding :end-before: END enable_padding :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_enable_padding :end-before: END quicktour_enable_padding :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START enable_padding :end-before: END enable_padding :dedent: 4 We can set the :obj:`direction` of the padding (defaults to the right) or a given :obj:`length` if we want to pad every sample to that specific number (here we leave it unset to pad to the size of the longest text). .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START print_batch_tokens :end-before: END print_batch_tokens :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_print_batch_tokens :end-before: END quicktour_print_batch_tokens :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START print_batch_tokens :end-before: END print_batch_tokens :dedent: 4 In this case, the `attention mask` generated by the tokenizer takes the padding into account: .. only:: python .. literalinclude:: ../../bindings/python/tests/documentation/test_quicktour.py :language: python :start-after: START print_attention_mask :end-before: END print_attention_mask :dedent: 8 .. only:: rust .. literalinclude:: ../../tokenizers/tests/documentation.rs :language: rust :start-after: START quicktour_print_attention_mask :end-before: END quicktour_print_attention_mask :dedent: 4 .. only:: node .. literalinclude:: ../../bindings/node/examples/documentation/quicktour.test.ts :language: javascript :start-after: START print_attention_mask :end-before: END print_attention_mask :dedent: 4 .. _pretrained: .. only:: python Using a pretrained tokenizer ------------------------------------------------------------------------------------------------ You can load any tokenizer from the Hugging Face Hub as long as a `tokenizer.json` file is available in the repository. .. code-block:: python from tokenizers import Tokenizer tokenizer = Tokenizer.from_pretrained("bert-base-uncased") Importing a pretrained tokenizer from legacy vocabulary files ------------------------------------------------------------------------------------------------ You can also import a pretrained tokenizer directly in, as long as you have its vocabulary file. For instance, here is how to import the classic pretrained BERT tokenizer: .. code-block:: python from tokenizers import BertWordPieceTokenizer tokenizer = BertWordPieceTokenizer("bert-base-uncased-vocab.txt", lowercase=True) as long as you have downloaded the file `bert-base-uncased-vocab.txt` with .. code-block:: bash wget https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt
tokenizers/docs/source/quicktour.rst/0
{ "file_path": "tokenizers/docs/source/quicktour.rst", "repo_id": "tokenizers", "token_count": 8904 }
337
{ "name": "create-wasm-app", "version": "0.1.0", "description": "create an app to consume rust-generated wasm packages", "main": "index.js", "bin": { "create-wasm-app": ".bin/create-wasm-app.js" }, "scripts": { "build": "webpack --config webpack.config.js", "start": "NODE_OPTIONS=--openssl-legacy-provider webpack-dev-server" }, "repository": { "type": "git", "url": "git+https://github.com/rustwasm/create-wasm-app.git" }, "keywords": ["webassembly", "wasm", "rust", "webpack"], "author": "Ashley Williams <ashley666ashley@gmail.com>", "license": "(MIT OR Apache-2.0)", "bugs": { "url": "https://github.com/rustwasm/create-wasm-app/issues" }, "homepage": "https://github.com/rustwasm/create-wasm-app#readme", "devDependencies": { "copy-webpack-plugin": "^11.0.0", "webpack": "^5.75.0", "webpack-cli": "^5.0.1", "webpack-dev-server": "^5.2.1" }, "dependencies": { "unstable_wasm": "file:../pkg" } }
tokenizers/tokenizers/examples/unstable_wasm/www/package.json/0
{ "file_path": "tokenizers/tokenizers/examples/unstable_wasm/www/package.json", "repo_id": "tokenizers", "token_count": 516 }
338
use super::Pair; use ahash::AHashMap; use dary_heap::QuaternaryHeap; use rand::{rng, Rng}; use std::cmp::Ordering; #[derive(Debug, Eq)] struct Merge { pos: usize, rank: u32, new_id: u32, } impl PartialEq for Merge { fn eq(&self, other: &Self) -> bool { self.rank == other.rank && self.pos == other.pos } } impl PartialOrd for Merge { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { // By manually implementing this, we make the containing BinaryHeap a // min-heap ordered first on the rank, and the pos otherwise Some(self.cmp(other)) } } impl Ord for Merge { fn cmp(&self, other: &Self) -> Ordering { if self.rank != other.rank { other.rank.cmp(&self.rank) } else { other.pos.cmp(&self.pos) } } } #[derive(Debug, Clone, Copy)] struct Symbol { c: u32, prev: isize, next: isize, len: usize, } impl Symbol { /// Merges the current Symbol with the other one. /// In order to update prev/next, we consider Self to be the Symbol on the left, /// and other to be the next one on the right. pub fn merge_with(&mut self, other: &Self, new_c: u32) { self.c = new_c; self.len += other.len; self.next = other.next; } } #[derive(Clone, Default)] pub(super) struct Word { symbols: Vec<Symbol>, } impl std::fmt::Debug for Word { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { fmt.debug_struct("Word") .field( "chars", &self .symbols .iter() .map(|s| s.c.to_string()) .collect::<Vec<_>>() .join(" "), ) .field("symbols", &self.symbols) .finish() } } impl Word { pub(super) fn new() -> Self { Word { symbols: vec![] } } pub(super) fn with_capacity(capacity: usize) -> Self { Self { symbols: Vec::with_capacity(capacity), } } pub(super) fn add(&mut self, c: u32, byte_len: usize) { let (prev, next) = { let len = self.symbols.len() as isize; if let Some(last) = self.symbols.last_mut() { // Update `next` on the previous one last.next = len; (len - 1, -1) } else { (-1, -1) } }; self.symbols.push(Symbol { c, prev, next, len: byte_len, }); } pub(super) fn merge( &mut self, c1: u32, c2: u32, replacement: u32, max_length: usize, ) -> Vec<(Pair, i32)> { let mut changes: Vec<(Pair, i32)> = vec![]; let mut i = 0; loop { if i >= self.symbols.len() { break; } // Found a pair if self.symbols[i].c == c1 && i + 1 < self.symbols.len() && self.symbols[i + 1].c == c2 { let first = self.symbols[i]; let second = self.symbols[i + 1]; // Remove in place let new_s = Symbol { c: replacement, prev: first.prev, next: second.next, len: first.len + second.len, }; // If there are other characters before the pair if i > 0 { changes.push(((self.symbols[i - 1].c, first.c), -1)); if self.symbols[i - 1].len + new_s.len < max_length { changes.push(((self.symbols[i - 1].c, replacement), 1)); } } self.symbols.insert(i, new_s); // Insert replacement before first char of pair self.symbols.remove(i + 1); // Remove first char of pair self.symbols.remove(i + 1); // And then the second // If there are other characters after the pair if i < self.symbols.len() - 1 { changes.push(((second.c, self.symbols[i + 1].c), -1)); if self.symbols[i + 1].len + new_s.len < max_length { changes.push(((replacement, self.symbols[i + 1].c), 1)); } } } i += 1; } changes } pub(super) fn merge_all(&mut self, merges: &AHashMap<Pair, (u32, u32)>, dropout: Option<f32>) { let mut queue = QuaternaryHeap::with_capacity(self.symbols.len()); let mut skip = Vec::with_capacity(queue.len()); queue.extend( self.symbols .windows(2) .enumerate() .filter_map(|(index, window)| { let pair = (window[0].c, window[1].c); merges.get(&pair).map(|m| Merge { pos: index, rank: m.0, new_id: m.1, }) }), ); while let Some(top) = queue.pop() { if dropout.map(|d| rng().random::<f32>() < d).unwrap_or(false) { skip.push(top); } else { // Re-insert the skipped elements queue.extend(skip.drain(..)); if self.symbols[top.pos].len == 0 { continue; } // Do nothing if we are the last symbol if self.symbols[top.pos].next == -1 { continue; } let next_pos = self.symbols[top.pos].next as usize; let right = self.symbols[next_pos]; // Make sure we are not processing an expired queue entry let target_new_pair = (self.symbols[top.pos].c, right.c); if merges .get(&target_new_pair) .is_none_or(|(_, new_id)| *new_id != top.new_id) { continue; } // Otherwise, let's merge self.symbols[top.pos].merge_with(&right, top.new_id); // Tag the right part as removed self.symbols[next_pos].len = 0; // Update `prev` on the new `next` to the current pos if right.next > -1 && (right.next as usize) < self.symbols.len() { self.symbols[right.next as usize].prev = top.pos as isize; } // Insert the new pair formed with the previous symbol let current = &self.symbols[top.pos]; if current.prev >= 0 { let prev = current.prev as usize; let prev_symbol = self.symbols[prev]; let new_pair = (prev_symbol.c, current.c); if let Some((rank, new_id)) = merges.get(&new_pair) { queue.push(Merge { pos: current.prev as usize, rank: *rank, new_id: *new_id, }); } } // Insert the new pair formed with the next symbol let next = current.next as usize; if next < self.symbols.len() { let next_symbol = self.symbols[next]; let new_pair = (current.c, next_symbol.c); if let Some((rank, new_id)) = merges.get(&new_pair) { queue.push(Merge { pos: top.pos, rank: *rank, new_id: *new_id, }); } } } } // Filter out the removed symbols self.symbols.retain(|s| s.len != 0); } pub(super) fn get_chars(&self) -> Vec<u32> { self.symbols.iter().map(|s| s.c).collect() } pub(super) fn get_chars_iter(&self) -> impl Iterator<Item = u32> + '_ { self.symbols.iter().map(|s| s.c) } pub(super) fn get_offsets_iter(&self) -> impl Iterator<Item = (usize, usize)> + '_ { let mut pos = 0; self.symbols.iter().map(move |symbol| { let new_pos = pos + symbol.len; let offset = (pos, new_pos); pos = new_pos; offset }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { // Let's say we have the word 'hello' and a word-to-id vocab that looks // like this: {'h': 0, 'e': 1, 'l': 2, 'o': 3}. let mut word = Word::new(); word.add(0, 1); // 'h' word.add(1, 1); // 'e' word.add(2, 1); // 'l' word.add(2, 1); // 'l' word.add(3, 1); // 'o' // We're going to perform a merge on the pair ('l', 'l') ~= (2, 2). Let's // say that 'll' has the ID of 4 in the updated word-to-id vocab. let changes = word.merge(2, 2, 4, usize::MAX); // So the word should now look like this: assert_eq!( word.get_chars(), &[ 0u32, // 'h' 1u32, // 'e' 4u32, // 'll' 3u32, // 'o' ] ); // The return value `changes` will be used to update the pair counts during // training. This merge affects the counts for the pairs // ('e', 'l') ~= (1, 2), // ('e', 'll') ~= (1, 4), // ('l', 'o') ~= (2, 3), and // ('ll', 'o') ~= (4, 3). // So the changes should reflect that: assert_eq!( changes, &[ ((1u32, 2u32), -1i32), // count for ('e', 'l') should be decreased by 1. ((1u32, 4u32), 1i32), // count for ('e', 'll') should be increased by 1. ((2u32, 3u32), -1i32), // count for ('l', 'o') should be decreased by 1. ((4u32, 3u32), 1i32), // count for ('ll', 'o') should be increased by 1. ] ); } #[test] fn test_merge_max_length() { // Let's say we have the word 'hello' and a word-to-id vocab that looks // like this: {'h': 0, 'e': 1, 'l': 2, 'o': 3}. let mut word = Word::new(); word.add(0, 1); // 'h' word.add(1, 1); // 'e' word.add(2, 1); // 'l' word.add(2, 1); // 'l' word.add(3, 1); // 'o' // We're going to perform a merge on the pair ('l', 'l') ~= (2, 2). Let's // say that 'll' has the ID of 4 in the updated word-to-id vocab. let changes = word.merge(2, 2, 4, 2); assert_eq!( word.get_chars(), &[ 0u32, // 'h' 1u32, // 'e' 4u32, // 'll' 3u32, // 'o' ] ); assert_eq!( changes, &[ ((1u32, 2u32), -1i32), // count for ('e', 'l') should be decreased by 1. // ((1u32, 4u32), 1i32), Missing since this would be larger than 2 ((2u32, 3u32), -1i32), // count for ('l', 'o') should be decreased by 1. // ((4u32, 3u32), 1i32), Missing since this would be larger than 2 ] ); } }
tokenizers/tokenizers/src/models/bpe/word.rs/0
{ "file_path": "tokenizers/tokenizers/src/models/bpe/word.rs", "repo_id": "tokenizers", "token_count": 6448 }
339
pub mod bert; pub mod byte_level; pub mod precompiled; pub mod prepend; pub mod replace; pub mod strip; pub mod unicode; pub mod utils; pub use crate::normalizers::bert::BertNormalizer; pub use crate::normalizers::byte_level::ByteLevel; pub use crate::normalizers::precompiled::Precompiled; pub use crate::normalizers::prepend::Prepend; pub use crate::normalizers::replace::Replace; pub use crate::normalizers::strip::{Strip, StripAccents}; pub use crate::normalizers::unicode::{Nmt, NFC, NFD, NFKC, NFKD}; pub use crate::normalizers::utils::{Lowercase, Sequence}; use serde::{Deserialize, Deserializer, Serialize}; use crate::{NormalizedString, Normalizer}; /// Wrapper for known Normalizers. #[derive(Clone, Debug, Serialize)] #[serde(untagged)] pub enum NormalizerWrapper { BertNormalizer(BertNormalizer), StripNormalizer(Strip), StripAccents(StripAccents), NFC(NFC), NFD(NFD), NFKC(NFKC), NFKD(NFKD), Sequence(Sequence), Lowercase(Lowercase), Nmt(Nmt), Precompiled(Precompiled), Replace(Replace), Prepend(Prepend), ByteLevel(ByteLevel), } impl<'de> Deserialize<'de> for NormalizerWrapper { fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Debug, Deserialize)] pub struct Tagged { #[serde(rename = "type")] variant: EnumType, #[serde(flatten)] rest: serde_json::Value, } #[derive(Debug, Serialize, Deserialize)] pub enum EnumType { Bert, Strip, StripAccents, NFC, NFD, NFKC, NFKD, Sequence, Lowercase, Nmt, Precompiled, Replace, Prepend, ByteLevel, } #[derive(Deserialize)] #[serde(untagged)] pub enum NormalizerHelper { Tagged(Tagged), Legacy(serde_json::Value), } #[derive(Deserialize)] #[serde(untagged)] pub enum NormalizerUntagged { BertNormalizer(BertNormalizer), StripNormalizer(Strip), StripAccents(StripAccents), NFC(NFC), NFD(NFD), NFKC(NFKC), NFKD(NFKD), Sequence(Sequence), Lowercase(Lowercase), Nmt(Nmt), Precompiled(Precompiled), Replace(Replace), Prepend(Prepend), ByteLevel(ByteLevel), } let helper = NormalizerHelper::deserialize(deserializer)?; Ok(match helper { NormalizerHelper::Tagged(model) => { let mut values: serde_json::Map<String, serde_json::Value> = serde_json::from_value(model.rest).expect("Parsed values"); values.insert( "type".to_string(), serde_json::to_value(&model.variant).expect("Reinsert"), ); let values = serde_json::Value::Object(values); match model.variant { EnumType::Bert => NormalizerWrapper::BertNormalizer( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::Strip => NormalizerWrapper::StripNormalizer( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::StripAccents => NormalizerWrapper::StripAccents( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::NFC => NormalizerWrapper::NFC( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::NFD => NormalizerWrapper::NFD( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::NFKC => NormalizerWrapper::NFKC( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::NFKD => NormalizerWrapper::NFKD( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::Sequence => NormalizerWrapper::Sequence( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::Lowercase => NormalizerWrapper::Lowercase( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::Nmt => NormalizerWrapper::Nmt( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::Precompiled => NormalizerWrapper::Precompiled( serde_json::from_str( &serde_json::to_string(&values).expect("Can reserialize precompiled"), ) // .map_err(serde::de::Error::custom) .expect("Precompiled"), ), EnumType::Replace => NormalizerWrapper::Replace( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::Prepend => NormalizerWrapper::Prepend( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), EnumType::ByteLevel => NormalizerWrapper::ByteLevel( serde_json::from_value(values).map_err(serde::de::Error::custom)?, ), } } NormalizerHelper::Legacy(value) => { let untagged = serde_json::from_value(value).map_err(serde::de::Error::custom)?; match untagged { NormalizerUntagged::BertNormalizer(bpe) => { NormalizerWrapper::BertNormalizer(bpe) } NormalizerUntagged::StripNormalizer(bpe) => { NormalizerWrapper::StripNormalizer(bpe) } NormalizerUntagged::StripAccents(bpe) => NormalizerWrapper::StripAccents(bpe), NormalizerUntagged::NFC(bpe) => NormalizerWrapper::NFC(bpe), NormalizerUntagged::NFD(bpe) => NormalizerWrapper::NFD(bpe), NormalizerUntagged::NFKC(bpe) => NormalizerWrapper::NFKC(bpe), NormalizerUntagged::NFKD(bpe) => NormalizerWrapper::NFKD(bpe), NormalizerUntagged::Sequence(seq) => NormalizerWrapper::Sequence(seq), NormalizerUntagged::Lowercase(bpe) => NormalizerWrapper::Lowercase(bpe), NormalizerUntagged::Nmt(bpe) => NormalizerWrapper::Nmt(bpe), NormalizerUntagged::Precompiled(bpe) => NormalizerWrapper::Precompiled(bpe), NormalizerUntagged::Replace(bpe) => NormalizerWrapper::Replace(bpe), NormalizerUntagged::Prepend(bpe) => NormalizerWrapper::Prepend(bpe), NormalizerUntagged::ByteLevel(bpe) => NormalizerWrapper::ByteLevel(bpe), } } }) } } impl Normalizer for NormalizerWrapper { fn normalize(&self, normalized: &mut NormalizedString) -> crate::Result<()> { match self { Self::BertNormalizer(bn) => bn.normalize(normalized), Self::StripNormalizer(sn) => sn.normalize(normalized), Self::StripAccents(sn) => sn.normalize(normalized), Self::NFC(nfc) => nfc.normalize(normalized), Self::NFD(nfd) => nfd.normalize(normalized), Self::NFKC(nfkc) => nfkc.normalize(normalized), Self::NFKD(nfkd) => nfkd.normalize(normalized), Self::Sequence(sequence) => sequence.normalize(normalized), Self::Lowercase(lc) => lc.normalize(normalized), Self::Nmt(lc) => lc.normalize(normalized), Self::Precompiled(lc) => lc.normalize(normalized), Self::Replace(lc) => lc.normalize(normalized), Self::Prepend(lc) => lc.normalize(normalized), Self::ByteLevel(lc) => lc.normalize(normalized), } } } impl_enum_from!(BertNormalizer, NormalizerWrapper, BertNormalizer); impl_enum_from!(NFKD, NormalizerWrapper, NFKD); impl_enum_from!(NFKC, NormalizerWrapper, NFKC); impl_enum_from!(NFC, NormalizerWrapper, NFC); impl_enum_from!(NFD, NormalizerWrapper, NFD); impl_enum_from!(Strip, NormalizerWrapper, StripNormalizer); impl_enum_from!(StripAccents, NormalizerWrapper, StripAccents); impl_enum_from!(Sequence, NormalizerWrapper, Sequence); impl_enum_from!(Lowercase, NormalizerWrapper, Lowercase); impl_enum_from!(Nmt, NormalizerWrapper, Nmt); impl_enum_from!(Precompiled, NormalizerWrapper, Precompiled); impl_enum_from!(Replace, NormalizerWrapper, Replace); impl_enum_from!(Prepend, NormalizerWrapper, Prepend); impl_enum_from!(ByteLevel, NormalizerWrapper, ByteLevel); #[cfg(test)] mod tests { use super::*; #[test] fn post_processor_deserialization_no_type() { let json = r#"{"strip_left":false, "strip_right":true}"#; let reconstructed = serde_json::from_str::<NormalizerWrapper>(json); assert!(matches!( reconstructed.unwrap(), NormalizerWrapper::StripNormalizer(_) )); let json = r#"{"trim_offsets":true, "add_prefix_space":true}"#; let reconstructed = serde_json::from_str::<NormalizerWrapper>(json); match reconstructed { Err(err) => assert_eq!( err.to_string(), "data did not match any variant of untagged enum NormalizerUntagged" ), _ => panic!("Expected an error here"), } let json = r#"{"prepend":"a"}"#; let reconstructed = serde_json::from_str::<NormalizerWrapper>(json); assert!(matches!( reconstructed.unwrap(), NormalizerWrapper::Prepend(_) )); } #[test] fn normalizer_serialization() { let json = r#"{"type":"Sequence","normalizers":[]}"#; assert!(serde_json::from_str::<NormalizerWrapper>(json).is_ok()); let json = r#"{"type":"Sequence","normalizers":[{}]}"#; let parse = serde_json::from_str::<NormalizerWrapper>(json); match parse { Err(err) => assert_eq!( format!("{err}"), "data did not match any variant of untagged enum NormalizerUntagged" ), _ => panic!("Expected error"), } let json = r#"{"replacement":"▁","prepend_scheme":"always"}"#; let parse = serde_json::from_str::<NormalizerWrapper>(json); match parse { Err(err) => assert_eq!( format!("{err}"), "data did not match any variant of untagged enum NormalizerUntagged" ), _ => panic!("Expected error"), } let json = r#"{"type":"Sequence","prepend_scheme":"always"}"#; let parse = serde_json::from_str::<NormalizerWrapper>(json); match parse { Err(err) => assert_eq!(format!("{err}"), "missing field `normalizers`"), _ => panic!("Expected error"), } } }
tokenizers/tokenizers/src/normalizers/mod.rs/0
{ "file_path": "tokenizers/tokenizers/src/normalizers/mod.rs", "repo_id": "tokenizers", "token_count": 5898 }
340
use crate::utils::SysRegex; use serde::{Deserialize, Deserializer, Serialize}; use crate::tokenizer::{ pattern::Invert, PreTokenizedString, PreTokenizer, Result, SplitDelimiterBehavior, }; /// Represents the different patterns that `Split` can use #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq)] pub enum SplitPattern { String(String), Regex(String), } impl From<String> for SplitPattern { fn from(v: String) -> Self { Self::String(v) } } impl From<&str> for SplitPattern { fn from(v: &str) -> Self { Self::String(v.to_owned()) } } #[derive(Debug, Serialize)] #[serde(tag = "type")] pub struct Split { pub pattern: SplitPattern, #[serde(skip)] pub regex: SysRegex, pub behavior: SplitDelimiterBehavior, pub invert: bool, } impl<'de> Deserialize<'de> for Split { fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] enum Type { Split, } #[derive(Deserialize)] pub struct SplitHelper { #[serde(rename = "type")] _type: Type, pattern: SplitPattern, behavior: SplitDelimiterBehavior, invert: bool, } let helper = SplitHelper::deserialize(deserializer)?; Self::new(helper.pattern, helper.behavior, helper.invert).map_err(serde::de::Error::custom) } } impl Clone for Split { fn clone(&self) -> Self { Self::new(self.pattern.clone(), self.behavior, self.invert).unwrap() } } impl PartialEq for Split { fn eq(&self, other: &Self) -> bool { self.pattern == other.pattern && self.behavior == other.behavior && self.invert == other.invert } } impl Split { pub fn new<I: Into<SplitPattern>>( pattern: I, behavior: SplitDelimiterBehavior, invert: bool, ) -> Result<Self> { let pattern: SplitPattern = pattern.into(); let regex = match &pattern { SplitPattern::String(s) => SysRegex::new(&regex::escape(s))?, SplitPattern::Regex(r) => SysRegex::new(r)?, }; Ok(Self { pattern, regex, behavior, invert, }) } } impl PreTokenizer for Split { fn pre_tokenize(&self, pretokenized: &mut PreTokenizedString) -> Result<()> { if self.invert { pretokenized.split(|_, normalized| normalized.split(Invert(&self.regex), self.behavior)) } else { pretokenized.split(|_, normalized| normalized.split(&self.regex, self.behavior)) } } } #[cfg(test)] mod tests { use super::*; use crate::{OffsetReferential, OffsetType, PreTokenizer}; use SplitDelimiterBehavior::*; #[test] fn basic() { let tests = vec![ ( Removed, "How are you doing?", vec![ ("How", (0, 3)), ("are", (4, 7)), ("you", (8, 11)), ("doing", (12, 17)), ("?", (17, 18)), ], ), ( Isolated, "How are you doing?", vec![ ("How", (0, 3)), (" ", (3, 4)), ("are", (4, 7)), (" ", (7, 8)), ("you", (8, 11)), (" ", (11, 12)), ("doing", (12, 17)), ("?", (17, 18)), ], ), ( MergedWithPrevious, "How are you doing?", vec![ ("How ", (0, 4)), ("are ", (4, 8)), ("you ", (8, 12)), ("doing", (12, 17)), ("?", (17, 18)), ], ), ( MergedWithNext, "How are you doing?", vec![ ("How", (0, 3)), (" are", (3, 7)), (" you", (7, 11)), (" doing", (11, 17)), ("?", (17, 18)), ], ), ( Contiguous, "How are you doing?", vec![ ("How", (0, 3)), (" ", (3, 4)), ("are", (4, 7)), (" ", (7, 8)), ("you", (8, 11)), (" ", (11, 12)), ("doing?", (12, 18)), ], ), ]; // use whitespace regex let regex = SplitPattern::Regex(r"\w+|[^\w\s]+".into()); for (behavior, s, res) in tests { let mut pretokenized = PreTokenizedString::from(s); let pretok = Split::new(regex.clone(), behavior, true).unwrap(); pretok.pre_tokenize(&mut pretokenized).unwrap(); assert_eq!( pretokenized .get_splits(OffsetReferential::Original, OffsetType::Byte) .into_iter() .map(|(s, o, _)| (s, o)) .collect::<Vec<_>>(), res ); } } #[test] fn regex_string() { let mut pretok_str_for_regex = PreTokenizedString::from("Hey, man!"); let mut pretok_str_for_string = pretok_str_for_regex.clone(); // pre-tokenizer splits on " " - one from Regex, one from string let pretokenizer_regex = Split::new( SplitPattern::Regex(r"\s+".into()), SplitDelimiterBehavior::Removed, false, ) .unwrap(); let pretokenizer_string = Split::new(" ", SplitDelimiterBehavior::Removed, false).unwrap(); pretokenizer_regex .pre_tokenize(&mut pretok_str_for_regex) .unwrap(); pretokenizer_string .pre_tokenize(&mut pretok_str_for_string) .unwrap(); assert_eq!(pretok_str_for_regex, pretok_str_for_string); } #[test] fn invert() { let mut pretok_str = PreTokenizedString::from("Hello Hello Hello"); let mut pretok_str_for_invert = pretok_str.clone(); // one pre-tokenizer splits on " " - one splits inverted on "Hello" let pretokenizer = Split::new(" ", SplitDelimiterBehavior::Removed, false).unwrap(); let pretokenizer_invert = Split::new("Hello", SplitDelimiterBehavior::Removed, true).unwrap(); pretokenizer.pre_tokenize(&mut pretok_str).unwrap(); pretokenizer_invert .pre_tokenize(&mut pretok_str_for_invert) .unwrap(); assert_eq!(pretok_str, pretok_str_for_invert); } #[test] fn serialization() { use SplitDelimiterBehavior::*; let split = Split::new("Hello", Removed, true).unwrap(); let split_s = r#"{"type":"Split","pattern":{"String":"Hello"},"behavior":"Removed","invert":true}"#; assert_eq!(serde_json::to_string(&split).unwrap(), split_s); assert_eq!(serde_json::from_str::<Split>(split_s).unwrap(), split); let split = Split::new(SplitPattern::Regex(r"\s+".into()), Isolated, false).unwrap(); let split_s = r#"{"type":"Split","pattern":{"Regex":"\\s+"},"behavior":"Isolated","invert":false}"#; assert_eq!(serde_json::to_string(&split).unwrap(), split_s); assert_eq!(serde_json::from_str::<Split>(split_s).unwrap(), split); } }
tokenizers/tokenizers/src/pre_tokenizers/split.rs/0
{ "file_path": "tokenizers/tokenizers/src/pre_tokenizers/split.rs", "repo_id": "tokenizers", "token_count": 4042 }
341
use std::marker::PhantomData; use serde::{ self, de::{Error, MapAccess, Visitor}, ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer, }; use super::{added_vocabulary::AddedTokenWithId, TokenizerImpl}; use crate::{Decoder, Model, Normalizer, PostProcessor, PreTokenizer, TokenizerBuilder}; static SERIALIZATION_VERSION: &str = "1.0"; impl<M, N, PT, PP, D> Serialize for TokenizerImpl<M, N, PT, PP, D> where M: Serialize, N: Serialize, PT: Serialize, PP: Serialize, D: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut tokenizer = serializer.serialize_struct("Tokenizer", 9)?; // Start by adding the current version tokenizer.serialize_field("version", SERIALIZATION_VERSION)?; // Params tokenizer.serialize_field("truncation", &self.truncation)?; tokenizer.serialize_field("padding", &self.padding)?; // Added tokens tokenizer.serialize_field("added_tokens", &self.added_vocabulary)?; // Then add our parts tokenizer.serialize_field("normalizer", &self.normalizer)?; tokenizer.serialize_field("pre_tokenizer", &self.pre_tokenizer)?; tokenizer.serialize_field("post_processor", &self.post_processor)?; tokenizer.serialize_field("decoder", &self.decoder)?; tokenizer.serialize_field("model", &self.model)?; tokenizer.end() } } impl<'de, M, N, PT, PP, D> Deserialize<'de> for TokenizerImpl<M, N, PT, PP, D> where M: Deserialize<'de> + Model, N: Deserialize<'de> + Normalizer, PT: Deserialize<'de> + PreTokenizer, PP: Deserialize<'de> + PostProcessor, D: Deserialize<'de> + Decoder, { fn deserialize<De>(deserializer: De) -> Result<Self, De::Error> where De: Deserializer<'de>, { deserializer.deserialize_struct( "Tokenizer", &[ "version", "truncation", "padding", "added_tokens", "normalizer", "pre_tokenizer", "post_processor", "decoder", "model", ], TokenizerVisitor( PhantomData, PhantomData, PhantomData, PhantomData, PhantomData, ), ) } } struct TokenizerVisitor<M, N, PT, PP, D>( PhantomData<M>, PhantomData<N>, PhantomData<PT>, PhantomData<PP>, PhantomData<D>, ); impl<'de, M, N, PT, PP, D> Visitor<'de> for TokenizerVisitor<M, N, PT, PP, D> where M: Deserialize<'de> + Model, N: Deserialize<'de> + Normalizer, PT: Deserialize<'de> + PreTokenizer, PP: Deserialize<'de> + PostProcessor, D: Deserialize<'de> + Decoder, { type Value = TokenizerImpl<M, N, PT, PP, D>; fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { write!(fmt, "struct Tokenizer") } fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de>, { let mut builder = TokenizerBuilder::new(); let mut tokens: Vec<AddedTokenWithId> = vec![]; while let Some(key) = map.next_key::<String>()? { match key.as_ref() { "version" => { let v: String = map.next_value()?; if &v != "1.0" { return Err(Error::custom(format!("Unknown tokenizer version '{v}'"))); } } "truncation" => { builder = builder.with_truncation(map.next_value()?); } "padding" => { builder = builder.with_padding(map.next_value()?); } "added_tokens" => { tokens = map.next_value()?; } "normalizer" => { builder = builder.with_normalizer(map.next_value()?); } "pre_tokenizer" => { builder = builder.with_pre_tokenizer(map.next_value()?); } "model" => { builder = builder.with_model(map.next_value()?); } "decoder" => { builder = builder.with_decoder(map.next_value()?); } "post_processor" => { builder = builder.with_post_processor(map.next_value()?); } _ => {} }; } let mut tokenizer = builder .build() .map_err(|e| V::Error::custom(e.to_string()))?; // We take care of deserializing the added_tokens (instead of `AddedVocabulary` directly // because it let us check that associated IDs are still good, and warn the user otherwise for token in &tokens { // Warn the user if the id is different than expected let received_id = tokenizer.token_to_id(&token.token.content); if let Some(rid) = received_id { if rid != token.id { warn!( "Warning: Token '{}' was expected to have ID '{}' but was given ID '{}'", token.token.content, token.id, rid ); } } } let added_tokens: Vec<_> = tokens.into_iter().map(|token| token.token).collect(); tokenizer.add_tokens(&added_tokens[..]); Ok(tokenizer) } } #[cfg(test)] mod tests { use crate::tokenizer::Tokenizer; use std::str::FromStr; #[test] fn test_deserialization_serialization_invariant() { let tok_json = r#"{ "version": "1.0", "truncation": null, "padding": null, "added_tokens": [ { "id": 0, "content": "[SPECIAL_0]", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true }, { "id": 1, "content": "[SPECIAL_1]", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": false }, { "id": 2, "content": "[SPECIAL_2]", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true } ], "normalizer": null, "pre_tokenizer": null, "post_processor": null, "decoder": null, "model": { "type": "WordPiece", "unk_token": "[UNK]", "continuing_subword_prefix": "", "max_input_chars_per_word": 100, "vocab": {} } }"#; let tokenizer = Tokenizer::from_str(tok_json).unwrap(); let tok_str = serde_json::to_string_pretty(&tokenizer).unwrap(); // It should be exactly the same as above assert_eq!(tok_str, tok_json); } #[cfg(feature = "http")] #[test] fn test_from_pretrained() { tracing_subscriber::fmt() .with_max_level(tracing::Level::DEBUG) .with_target(false) .init(); let _ = Tokenizer::from_pretrained("Qwen/Qwen2-7B-Instruct", None); warn!("This should be the first warning"); } }
tokenizers/tokenizers/src/tokenizer/serialization.rs/0
{ "file_path": "tokenizers/tokenizers/src/tokenizer/serialization.rs", "repo_id": "tokenizers", "token_count": 3685 }
342
mod common; use common::*; use tokenizers::decoders::byte_level::ByteLevel; use tokenizers::decoders::DecoderWrapper; use tokenizers::models::bpe::BPE; use tokenizers::models::wordlevel::WordLevel; use tokenizers::models::wordpiece::WordPiece; use tokenizers::models::ModelWrapper; use tokenizers::normalizers::bert::BertNormalizer; use tokenizers::normalizers::unicode::{NFC, NFKC}; use tokenizers::normalizers::NormalizerWrapper; use tokenizers::pre_tokenizers::bert::BertPreTokenizer; use tokenizers::pre_tokenizers::delimiter::CharDelimiterSplit; use tokenizers::pre_tokenizers::split::{Split, SplitPattern}; use tokenizers::pre_tokenizers::whitespace::Whitespace; use tokenizers::pre_tokenizers::PreTokenizerWrapper; use tokenizers::processors::bert::BertProcessing; use tokenizers::processors::PostProcessorWrapper; use tokenizers::{SplitDelimiterBehavior, Tokenizer, TokenizerImpl}; #[test] fn bpe_serde() { let bpe = get_byte_level_bpe(); let ser = serde_json::to_string(&bpe).unwrap(); let de = serde_json::from_str(&ser).unwrap(); assert_eq!(bpe, de); } #[test] fn wordpiece_serde() { let wordpiece = get_bert_wordpiece(); let ser = serde_json::to_string(&wordpiece).unwrap(); let de = serde_json::from_str(&ser).unwrap(); assert_eq!(wordpiece, de); } #[test] fn wordlevel_serde() { let wordlevel = WordLevel::from_file("data/gpt2-vocab.json", "<unk>".into()).unwrap(); let ser = serde_json::to_string(&wordlevel).unwrap(); let de = serde_json::from_str(&ser).unwrap(); assert_eq!(wordlevel, de); } #[test] fn normalizers() { // Test unit struct let nfc = NFC; let nfc_ser = serde_json::to_string(&nfc).unwrap(); assert_eq!(nfc_ser, r#"{"type":"NFC"}"#); // empty struct can deserialize from self serde_json::from_str::<NFC>(&nfc_ser).unwrap(); let err: Result<NFKC, _> = serde_json::from_str(&nfc_ser); assert!(err.is_err(), "NFKC shouldn't be deserializable from NFC"); // wrapper can can deserialize from inner let nfc_wrapped: NormalizerWrapper = serde_json::from_str(&nfc_ser).unwrap(); match &nfc_wrapped { NormalizerWrapper::NFC(_) => (), _ => panic!("NFC wrapped with incorrect variant"), } let ser_wrapped = serde_json::to_string(&nfc_wrapped).unwrap(); assert_eq!(ser_wrapped, nfc_ser); // Test non-empty roundtrip let bert = BertNormalizer::default(); let bert_ser = serde_json::to_string(&bert).unwrap(); assert_eq!( bert_ser, r#"{"type":"BertNormalizer","clean_text":true,"handle_chinese_chars":true,"strip_accents":null,"lowercase":true}"# ); // make sure we can deserialize to self serde_json::from_str::<BertNormalizer>(&bert_ser).unwrap(); // wrapper can deserialize from inner serialization let bert_wrapped: NormalizerWrapper = serde_json::from_str(&bert_ser).unwrap(); match &bert_wrapped { NormalizerWrapper::BertNormalizer(_) => (), _ => panic!("BertNormalizer wrapped with incorrect variant"), } // wrapped serializes same way as inner let ser_wrapped = serde_json::to_string(&bert_wrapped).unwrap(); assert_eq!(ser_wrapped, bert_ser); } #[test] fn processors() { let bert = BertProcessing::new(("SEP".into(), 0), ("CLS".into(), 0)); let bert_ser = serde_json::to_string(&bert).unwrap(); assert_eq!( bert_ser, r#"{"type":"BertProcessing","sep":["SEP",0],"cls":["CLS",0]}"# ); serde_json::from_str::<BertProcessing>(&bert_ser).unwrap(); let bert_wrapped: PostProcessorWrapper = serde_json::from_str(&bert_ser).unwrap(); match &bert_wrapped { PostProcessorWrapper::Bert(_) => (), _ => panic!("Bert wrapped with incorrect variant"), } let ser_wrapped = serde_json::to_string(&bert_wrapped).unwrap(); assert_eq!(ser_wrapped, bert_ser); } #[test] fn pretoks() { // Test unit struct let bert = BertPreTokenizer; let bert_ser = serde_json::to_string(&bert).unwrap(); assert_eq!(bert_ser, r#"{"type":"BertPreTokenizer"}"#); // empty struct can deserialize from self serde_json::from_str::<BertPreTokenizer>(&bert_ser).unwrap(); let err: Result<Whitespace, _> = serde_json::from_str(&bert_ser); assert!( err.is_err(), "Whitespace shouldn't be deserializable from BertPreTokenizer" ); // wrapper can can deserialize from inner let bert_wrapped: PreTokenizerWrapper = serde_json::from_str(&bert_ser).unwrap(); match &bert_wrapped { PreTokenizerWrapper::BertPreTokenizer(_) => (), _ => panic!("Bert wrapped with incorrect variant"), } let ser_wrapped = serde_json::to_string(&bert_wrapped).unwrap(); assert_eq!(ser_wrapped, bert_ser); // Test non-empty roundtrip let ch = CharDelimiterSplit::new(' '); let ch_ser = serde_json::to_string(&ch).unwrap(); assert_eq!(ch_ser, r#"{"type":"CharDelimiterSplit","delimiter":" "}"#); // make sure we can deserialize to self serde_json::from_str::<CharDelimiterSplit>(&ch_ser).unwrap(); // wrapper can deserialize from inner serialization let ch_wrapped: PreTokenizerWrapper = serde_json::from_str(&ch_ser).unwrap(); match &ch_wrapped { PreTokenizerWrapper::Delimiter(_) => (), _ => panic!("CharDelimiterSplit wrapped with incorrect variant"), } // wrapped serializes same way as inner let ser_wrapped = serde_json::to_string(&ch_wrapped).unwrap(); assert_eq!(ser_wrapped, ch_ser); let wsp = Whitespace {}; let wsp_ser = serde_json::to_string(&wsp).unwrap(); assert_eq!(wsp_ser, r#"{"type":"Whitespace"}"#); serde_json::from_str::<Whitespace>(&wsp_ser).unwrap(); let err: Result<BertPreTokenizer, _> = serde_json::from_str(&wsp_ser); assert!( err.is_err(), "BertPreTokenizer shouldn't be deserializable from Whitespace" ); let pattern: SplitPattern = "[SEP]".into(); let pretok = Split::new(pattern, SplitDelimiterBehavior::Isolated, false).unwrap(); let pretok_str = serde_json::to_string(&pretok).unwrap(); assert_eq!( pretok_str, r#"{"type":"Split","pattern":{"String":"[SEP]"},"behavior":"Isolated","invert":false}"# ); assert_eq!(serde_json::from_str::<Split>(&pretok_str).unwrap(), pretok); let pattern = SplitPattern::Regex("[SEP]".to_string()); let pretok = Split::new(pattern, SplitDelimiterBehavior::Isolated, false).unwrap(); let pretok_str = serde_json::to_string(&pretok).unwrap(); assert_eq!( pretok_str, r#"{"type":"Split","pattern":{"Regex":"[SEP]"},"behavior":"Isolated","invert":false}"# ); assert_eq!(serde_json::from_str::<Split>(&pretok_str).unwrap(), pretok); } #[test] fn decoders() { let byte_level = ByteLevel::default(); let byte_level_ser = serde_json::to_string(&byte_level).unwrap(); assert_eq!( byte_level_ser, r#"{"type":"ByteLevel","add_prefix_space":true,"trim_offsets":true,"use_regex":true}"# ); serde_json::from_str::<ByteLevel>(&byte_level_ser).unwrap(); let byte_level_wrapper: DecoderWrapper = serde_json::from_str(&byte_level_ser).unwrap(); match &byte_level_wrapper { DecoderWrapper::ByteLevel(_) => (), _ => panic!("ByteLevel wrapped with incorrect variant"), } let ser_wrapped = serde_json::to_string(&byte_level_wrapper).unwrap(); assert_eq!(ser_wrapped, byte_level_ser); } #[test] fn models() { let bpe = BPE::default(); let bpe_ser = serde_json::to_string(&bpe).unwrap(); serde_json::from_str::<BPE>(&bpe_ser).unwrap(); let bpe_wrapper: ModelWrapper = serde_json::from_str(&bpe_ser).unwrap(); match &bpe_wrapper { ModelWrapper::BPE(_) => (), _ => panic!("BPE wrapped with incorrect variant"), } let ser_wrapped = serde_json::to_string(&bpe_wrapper).unwrap(); assert_eq!(ser_wrapped, bpe_ser); } #[test] fn tokenizer() { let wordpiece = WordPiece::default(); let mut tokenizer = Tokenizer::new(wordpiece); tokenizer.with_normalizer(Some(NFC)); let ser = serde_json::to_string(&tokenizer).unwrap(); let _: Tokenizer = serde_json::from_str(&ser).unwrap(); let unwrapped_nfc_tok: TokenizerImpl< WordPiece, NFC, PreTokenizerWrapper, PostProcessorWrapper, DecoderWrapper, > = serde_json::from_str(&ser).unwrap(); assert_eq!(serde_json::to_string(&unwrapped_nfc_tok).unwrap(), ser); let err: Result< TokenizerImpl<WordPiece, NFKC, PreTokenizerWrapper, PostProcessorWrapper, DecoderWrapper>, _, > = serde_json::from_str(&ser); assert!(err.is_err(), "NFKC shouldn't be deserializable from NFC"); let de: TokenizerImpl< WordPiece, NormalizerWrapper, PreTokenizerWrapper, PostProcessorWrapper, DecoderWrapper, > = serde_json::from_str(&ser).unwrap(); assert_eq!(serde_json::to_string(&de).unwrap(), ser); } #[test] fn bpe_with_dropout_serde() { let mut bpe = BPE::default(); bpe.dropout = Some(0.1); let ser = serde_json::to_string(&bpe).unwrap(); let de = serde_json::from_str(&ser).unwrap(); assert_eq!(bpe, de); // set dropout to 0.0 (which is analogous to None) and reserialize bpe.dropout = Some(0.0); let ser = serde_json::to_string(&bpe).unwrap(); let de = serde_json::from_str(&ser).unwrap(); assert_eq!(bpe, de); } #[test] fn test_deserialize_long_file() { let _tokenizer = Tokenizer::from_file("data/albert-base-v1-tokenizer.json").unwrap(); }
tokenizers/tokenizers/tests/serialization.rs/0
{ "file_path": "tokenizers/tokenizers/tests/serialization.rs", "repo_id": "tokenizers", "token_count": 3890 }
343
# Using quantized models (dtypes) Before Transformers.js v3, we used the `quantized` option to specify whether to use a quantized (q8) or full-precision (fp32) variant of the model by setting `quantized` to `true` or `false`, respectively. Now, we've added the ability to select from a much larger list with the `dtype` parameter. The list of available quantizations depends on the model, but some common ones are: full-precision (`"fp32"`), half-precision (`"fp16"`), 8-bit (`"q8"`, `"int8"`, `"uint8"`), and 4-bit (`"q4"`, `"bnb4"`, `"q4f16"`). <p align="center"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/transformersjs-v3/dtypes-dark.jpg" style="max-width: 100%;"> <source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/transformersjs-v3/dtypes-light.jpg" style="max-width: 100%;"> <img alt="Available dtypes for mixedbread-ai/mxbai-embed-xsmall-v1" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/transformersjs-v3/dtypes-dark.jpg" style="max-width: 100%;"> </picture> <a href="https://huggingface.co/mixedbread-ai/mxbai-embed-xsmall-v1/tree/main/onnx">(e.g., mixedbread-ai/mxbai-embed-xsmall-v1)</a> </p> ## Basic usage **Example:** Run Qwen2.5-0.5B-Instruct in 4-bit quantization ([demo](https://v2.scrimba.com/s0dlcpv0ci)) ```js import { pipeline } from "@huggingface/transformers"; // Create a text generation pipeline const generator = await pipeline( "text-generation", "onnx-community/Qwen2.5-0.5B-Instruct", { dtype: "q4", device: "webgpu" }, ); // Define the list of messages const messages = [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Tell me a funny joke." }, ]; // Generate a response const output = await generator(messages, { max_new_tokens: 128 }); console.log(output[0].generated_text.at(-1).content); ``` ## Per-module dtypes Some encoder-decoder models, like Whisper or Florence-2, are extremely sensitive to quantization settings: especially of the encoder. For this reason, we added the ability to select per-module dtypes, which can be done by providing a mapping from module name to dtype. **Example:** Run Florence-2 on WebGPU ([demo](https://v2.scrimba.com/s0pdm485fo)) ```js import { Florence2ForConditionalGeneration } from "@huggingface/transformers"; const model = await Florence2ForConditionalGeneration.from_pretrained( "onnx-community/Florence-2-base-ft", { dtype: { embed_tokens: "fp16", vision_encoder: "fp16", encoder_model: "q4", decoder_model_merged: "q4", }, device: "webgpu", }, ); ``` <p align="middle"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/transformersjs-v3/florence-2-webgpu.gif" alt="Florence-2 running on WebGPU" /> </p> <details> <summary> See full code example </summary> ```js import { Florence2ForConditionalGeneration, AutoProcessor, AutoTokenizer, RawImage, } from "@huggingface/transformers"; // Load model, processor, and tokenizer const model_id = "onnx-community/Florence-2-base-ft"; const model = await Florence2ForConditionalGeneration.from_pretrained( model_id, { dtype: { embed_tokens: "fp16", vision_encoder: "fp16", encoder_model: "q4", decoder_model_merged: "q4", }, device: "webgpu", }, ); const processor = await AutoProcessor.from_pretrained(model_id); const tokenizer = await AutoTokenizer.from_pretrained(model_id); // Load image and prepare vision inputs const url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg"; const image = await RawImage.fromURL(url); const vision_inputs = await processor(image); // Specify task and prepare text inputs const task = "<MORE_DETAILED_CAPTION>"; const prompts = processor.construct_prompts(task); const text_inputs = tokenizer(prompts); // Generate text const generated_ids = await model.generate({ ...text_inputs, ...vision_inputs, max_new_tokens: 100, }); // Decode generated text const generated_text = tokenizer.batch_decode(generated_ids, { skip_special_tokens: false, })[0]; // Post-process the generated text const result = processor.post_process_generation( generated_text, task, image.size, ); console.log(result); // { '<MORE_DETAILED_CAPTION>': 'A green car is parked in front of a tan building. The building has a brown door and two brown windows. The car is a two door and the door is closed. The green car has black tires.' } ``` </details>
transformers.js/docs/source/guides/dtypes.md/0
{ "file_path": "transformers.js/docs/source/guides/dtypes.md", "repo_id": "transformers.js", "token_count": 1698 }
344
.sidebar { background-color: #181818; color: #CCCCCC; } body{ background-color: #1F1F1F; color: white; } .progress-container { position: relative; font-size: 16px; color: white; /* background-color: #e9ecef; */ border-radius: 8px; text-align: left; overflow: hidden; } .progress-bar { padding: 2px 4px; z-index: 0; top: 0; width: 1%; height: 100%; overflow: hidden; background-color: #007bff; white-space: nowrap; } .progress-text { z-index: 2; }
transformers.js/examples/code-completion/src/App.css/0
{ "file_path": "transformers.js/examples/code-completion/src/App.css", "repo_id": "transformers.js", "token_count": 208 }
345
import { useState, useRef, useEffect, useCallback } from 'react' import './App.css' const PLACEHOLDER_TEXTS = [ "'To Kill a Mockingbird' is a novel by Harper Lee published in 1960. It was immediately successful, winning the Pulitzer Prize, and has become a classic of modern American literature.", "The novel 'Moby-Dick' was written by Herman Melville and first published in 1851. It is considered a masterpiece of American literature and deals with complex themes of obsession, revenge, and the conflict between good and evil.", "Harper Lee, an American novelist widely known for her novel 'To Kill a Mockingbird', was born in 1926 in Monroeville, Alabama. She received the Pulitzer Prize for Fiction in 1961.", "Jane Austen was an English novelist known primarily for her six major novels, which interpret, critique and comment upon the British landed gentry at the end of the 18th century.", "The 'Harry Potter' series, which consists of seven fantasy novels written by British author J.K. Rowling, is among the most popular and critically acclaimed books of the modern era.", "'The Great Gatsby', a novel written by American author F. Scott Fitzgerald, was published in 1925. The story is set in the Jazz Age and follows the life of millionaire Jay Gatsby and his pursuit of Daisy Buchanan." ].sort(() => Math.random() - 0.5); function App() { const [status, setStatus] = useState('idle'); const [query, setQuery] = useState(`Who wrote 'To Kill a Mockingbird'?`); const [documents, setDocuments] = useState(PLACEHOLDER_TEXTS.join('\n')); const [results, setResults] = useState([]); // Create a reference to the worker object. const worker = useRef(null); // We use the `useEffect` hook to setup the worker as soon as the `App` component is mounted. useEffect(() => { if (!worker.current) { // Create the worker if it does not yet exist. worker.current = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }); } // Create a callback function for messages from the worker thread. const onMessageReceived = (e) => { const status = e.data.status; if (e.data.file?.endsWith('.onnx')) { if (status === 'initiate') { setStatus('loading'); } else if (status === 'done') { setStatus('ready'); } } else if (status === 'complete') { setResults(e.data.output); setStatus('idle'); } }; // Attach the callback function as an event listener. worker.current.addEventListener('message', onMessageReceived); // Define a cleanup function for when the component is unmounted. return () => worker.current.removeEventListener('message', onMessageReceived); }, []); const run = useCallback(() => { setStatus('processing'); worker.current.postMessage({ query, documents, }); }, [query, documents]) const busy = status !== 'idle'; return ( <div className='flex flex-col h-full'> <h1 className='text-2xl md:text-4xl font-bold text-center mb-1'>Reranking w/ The Crispy mixedbread Rerank Models</h1> <p className='text-lg md:text-xl font-medium text-center mb-2'>Powered by <a href='https://huggingface.co/mixedbread-ai/mxbai-rerank-xsmall-v1' target='_blank' rel='noreferrer'>mxbai-rerank-xsmall-v1</a> and <a href='http://huggingface.co/docs/transformers.js' target='_blank' rel='noreferrer'>🤗 Transformers.js</a></p> <div className='flex-grow flex flex-wrap p-4'> <div className='flex flex-col items-center gap-y-1 w-full md:w-1/2'> <label className='text-lg font-medium'>Query</label> <textarea placeholder='Enter query.' className='border w-full p-1 resize-none overflow-hidden h-10' value={query} onChange={e => { setQuery(e.target.value); setResults([]); }} ></textarea> <label className='text-lg font-medium mt-1'>Documents</label> <textarea placeholder='Enter documents to compare with the query. One sentence per line.' className='border w-full p-1 h-full resize-none' value={documents} onChange={e => { setDocuments(e.target.value); setResults([]); }} ></textarea> <button className='border py-1 px-2 bg-green-400 rounded text-white text-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed' disabled={busy} onClick={run}>{ !busy ? 'Rerank' : status === 'loading' ? 'Model loading...' : 'Processing' }</button> </div> <div className='flex flex-col items-center w-full md:w-1/2 gap-y-1'> {results.length > 0 && (<> <div className='w-full flex flex-col gap-y-1'> <label className='text-lg font-medium text-center'>Results</label> <div className='flex flex-col gap-y-1'> {results.map((result, i) => ( <div key={i} className='flex gap-x-2 border mx-2 p-1'> <span className='font-bold'>{result.score.toFixed(3)}</span> <span>{result.text}</span> </div> ))} </div> </div> </>) } </div> </div> </div> ) } export default App
transformers.js/examples/cross-encoder/src/App.jsx/0
{ "file_path": "transformers.js/examples/cross-encoder/src/App.jsx", "repo_id": "transformers.js", "token_count": 2232 }
346
# Transformers.js - Sample browser extension An example project to show how to run 🤗 Transformers in a browser extension. Although we only provide instructions for running in Chrome, it should be similar for other browsers. ## Getting Started 1. Clone the repo and enter the project directory: ```bash git clone https://github.com/huggingface/transformers.js.git cd transformers.js/examples/extension/ ``` 1. Install the necessary dependencies: ```bash npm install ``` 1. Build the project: ```bash npm run build ``` 1. Add the extension to your browser. To do this, go to `chrome://extensions/`, enable developer mode (top right), and click "Load unpacked". Select the `build` directory from the dialog which appears and click "Select Folder". 1. That's it! You should now be able to open the extension's popup and use the model in your browser! ## Editing the template We recommend running `npm run dev` while editing the template as it will rebuild the project when changes are made. All source code can be found in the `./src/` directory: - `background.js` ([service worker](https://developer.chrome.com/docs/extensions/mv3/service_workers/)) - handles all the requests from the UI, does processing in the background, then returns the result. You will need to reload the extension (by visiting `chrome://extensions/` and clicking the refresh button) after editing this file for changes to be visible in the extension. - `content.js` ([content script](https://developer.chrome.com/docs/extensions/mv3/content_scripts/)) - contains the code which is injected into every page the user visits. You can use the `sendMessage` api to make requests to the background script. Similarly, you will need to reload the extension after editing this file for changes to be visible in the extension. - `popup.html`, `popup.css`, `popup.js` ([toolbar action](https://developer.chrome.com/docs/extensions/reference/action/)) - contains the code for the popup which is visible to the user when they click the extension's icon from the extensions bar. For development, we recommend opening the `popup.html` file in its own tab by visiting `chrome-extension://<ext_id>/popup.html` (remember to replace `<ext_id>` with the extension's ID). You will need to refresh the page while you develop to see the changes you make.
transformers.js/examples/extension/README.md/0
{ "file_path": "transformers.js/examples/extension/README.md", "repo_id": "transformers.js", "token_count": 624 }
347
import { useEffect, useState, useRef } from 'react'; import { AutoTokenizer, MusicgenForConditionalGeneration, BaseStreamer } from '@xenova/transformers'; import { encodeWAV, share } from './utils.js'; import './App.css'; const MODEL_ID = 'Xenova/musicgen-small'; // Adapted from https://huggingface.co/spaces/facebook/MusicGen const EXAMPLES = [ '80s pop track with bassy drums and synth', '90s rock song with loud guitars and heavy drums', 'a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions bpm: 130', 'A cheerful country song with acoustic guitars', 'lofi slow bpm electro chill with organic samples', ]; // Enable sharing if running on Hugging Face Spaces const SHARING_ENABLED = window.location.host.endsWith('.hf.space'); // Streamer to update progress class CallbackStreamer extends BaseStreamer { constructor(callback_fn) { super(); this.callback_fn = callback_fn; } put(value) { return this.callback_fn(value); } end() { return this.callback_fn(); } } // Main App component const App = () => { // Input/output state const [textInput, setTextInput] = useState(EXAMPLES[0]); const [progress, setProgress] = useState(0); const [loadProgress, setLoadProgress] = useState({}); const [statusText, setStatusText] = useState('Loading model (656MB)...'); const [result, setResult] = useState(null); const audioRef = useRef(null); // Model and tokenizer references const modelPromise = useRef(null); const tokenizerPromise = useRef(null); // Generation parameters const [guidance_scale, setGuidanceScale] = useState(3); const [temperature, setTemperature] = useState(1); const [duration, setDuration] = useState(10); // Load model and tokenizer on first render useEffect(() => { modelPromise.current ??= MusicgenForConditionalGeneration.from_pretrained(MODEL_ID, { progress_callback: (data) => { if (data.status !== 'progress') return; setLoadProgress(prev => ({ ...prev, [data.file]: data })) }, dtype: { text_encoder: 'q8', decoder_model_merged: 'q8', encodec_decode: 'fp32', }, device: 'wasm', }); tokenizerPromise.current ??= AutoTokenizer.from_pretrained(MODEL_ID); }, []); // Update progress bar based on load progress useEffect(() => { const items = Object.values(loadProgress); if (items.length !== 5) return; // 5 files to load let loaded = 0; let total = 0; for (const data of Object.values(loadProgress)) { loaded += data.loaded; total += data.total; } const progress = loaded / total; setProgress(progress); setStatusText(progress === 1 ? 'Ready!' : `Loading model (${(progress * 100).toFixed()}% of 656MB)...` ); }, [loadProgress]); // Function to handle generating music const generateMusic = async () => { // Reset audio player and result audioRef.current.src = ''; setResult(null); // Get model and tokenizer const tokenizer = await tokenizerPromise.current; const model = await modelPromise.current; // Get number of tokens to match user-specified duration (more intuitive for user) // 503 tokens -> 10 seconds generated => ~50 tokens per second // https://huggingface.co/docs/transformers/model_doc/musicgen#generation const max_length = Math.min( Math.max(Math.floor(duration * 50), 1) + 4, model.generation_config.max_length ?? 1500, ); // Create a streamer to update progress let num_tokens = 0; const streamer = new CallbackStreamer((value) => { const percent = value === undefined ? 1 : ++num_tokens / max_length; setStatusText(`Generating (${(percent * 100).toFixed()}%)...`); setProgress(percent); }); // Tokenize input text const inputs = tokenizer(textInput); // Generate music const audio_values = await model.generate({ // Inputs ...inputs, // Generation parameters max_length, guidance_scale, temperature, // Outputs streamer, }); setStatusText('Encoding audio...'); // Encode audio values to WAV const sampling_rate = model.config.audio_encoder.sampling_rate; const wav = encodeWAV(audio_values.data, sampling_rate); const blob = new Blob([wav], { type: 'audio/wav' }); setResult(blob); audioRef.current.src = URL.createObjectURL(blob); setStatusText('Done!'); }; return ( <div className="container mx-auto p-8"> <h1 className="text-5xl font-bold mb-2">MusicGen Web</h1> <h2 className="text-2xl font-semibold mb-4">In-browser text-to-music w/ <a className="underline" href="https://github.com/huggingface/transformers.js">🤗 Transformers.js!</a> </h2> {/* Text input for user */} <input type="text" placeholder="Describe the music to generate..." value={textInput} onChange={(e) => setTextInput(e.target.value)} className="border border-gray-300 p-2 mb-4 w-full rounded" /> {/* Example buttons */} <div className="mb-4 flex gap-2 justify-center text-sm"> {EXAMPLES.map((example, i) => ( <button key={i} className="bg-blue-500 hover:bg-blue-400 transition-colors duration-100 text-white px-2 py-2 rounded" onClick={(e) => setTextInput(e.target.innerText)}>{example}</button> ))} </div> {/* Generation parameters */} <div className="flex mb-4 justify-center gap-2"> {/* Duration */} <div> <label className="block text-sm font-semibold mb-1">Duration</label> <input type="range" min={1} max={30} value={duration} onChange={(e) => setDuration(e.target.value)} /> <p className="text-sm text-center">{`${duration} second${duration > 1 ? 's' : ''}`}</p> </div> {/* Guidance Scale */} <div className="mr-4"> <label className="block text-sm font-semibold mb-1">Guidance Scale</label> <input type="range" min={1} max={10} value={guidance_scale} onChange={(e) => setGuidanceScale(e.target.value)} /> <p className="text-sm text-center">{guidance_scale}</p> </div> {/* Temperature */} <div> <label className="block text-sm font-semibold mb-1">Temperature</label> <input type="range" min={0.1} max={2} step={0.1} value={temperature} onChange={(e) => setTemperature(e.target.value)} /> <p className="text-sm text-center">{temperature}</p> </div> </div> {/* Button to generate music */} <button className="mb-4 bg-green-500 hover:bg-green-400 transition-colors duration-100 text-white px-4 py-3 rounded-lg font-semibold" onClick={generateMusic}>Generate Music</button> {/* Progress bar */} <div className="mb-4"> <div className="bg-gray-200 h-4 w-full rounded-full"> <div className="bg-blue-500 h-4 rounded-full" style={{ width: `${100 * progress}%` }}></div> </div> <p className="text-sm text-center mt-1">{statusText}</p> </div> {/* Audio player */} {<div className="flex justify-center flex-col items-center"> <audio ref={audioRef} controls type="audio/wav" /> {SHARING_ENABLED && result && <button className="bg-red-500 hover:bg-red-400 transition-colors duration-100 text-white px-2 py-1 my-2 rounded-lg text-sm" onClick={async (e) => { e.target.disabled = true; e.target.innerText = 'Uploading...'; await share(result, { prompt: textInput, duration, guidance_scale, temperature, }); e.target.disabled = false; e.target.innerText = 'Share'; } }>Share</button> } </div>} </div> ); }; export default App;
transformers.js/examples/musicgen-web/src/App.jsx/0
{ "file_path": "transformers.js/examples/musicgen-web/src/App.jsx", "repo_id": "transformers.js", "token_count": 3165 }
348
{ "extends": "next/core-web-vitals" }
transformers.js/examples/semantic-image-search-client/.eslintrc.json/0
{ "file_path": "transformers.js/examples/semantic-image-search-client/.eslintrc.json", "repo_id": "transformers.js", "token_count": 20 }
349
'use client' import { useState, useEffect, useCallback, useRef } from 'react' import { Modal } from './components/Modal'; import { SearchBar } from './components/SearchBar'; import { ImageGrid } from './components/ImageGrid'; export default function Home() { // Application state const [ready, setReady] = useState(null); const [images, setImages] = useState(null); const [currentImage, setCurrentImage] = useState(null); // Create a reference to the worker object. const worker = useRef(null); // We use the `useEffect` hook to set up the worker as soon as the `App` component is mounted. useEffect(() => { if (!worker.current) { // Create the worker if it does not yet exist. worker.current = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }); } const onMessageReceived = (e) => { switch (e.data.status) { case 'initiate': setReady(false); break; case 'ready': setReady(true); break; case 'complete': setImages(e.data.output); break; } }; // Attach the callback function as an event listener. worker.current.addEventListener('message', onMessageReceived); // Define a cleanup function for when the component is unmounted. return () => worker.current.removeEventListener('message', onMessageReceived); }); const search = useCallback((text) => { if (worker.current) { worker.current.postMessage({ text }); } }, []); return ( <main className="mx-auto max-w-[1960px] p-4 relative"> <Modal currentImage={currentImage} setCurrentImage={setCurrentImage} /> <SearchBar search={search} /> {ready === false && ( <div className="z-10 fixed top-0 left-0 w-full h-full bg-black bg-opacity-50 flex items-center justify-center"> <div className="text-white text-2xl font-bold">Loading model and database...</div> </div> )} <ImageGrid images={images} setCurrentImage={setCurrentImage} /> </main> ) }
transformers.js/examples/semantic-image-search-client/src/app/page.js/0
{ "file_path": "transformers.js/examples/semantic-image-search-client/src/app/page.js", "repo_id": "transformers.js", "token_count": 772 }
350
// Helper script to update the database with image embeddings import { AutoProcessor, RawImage, CLIPVisionModelWithProjection } from '@xenova/transformers'; import { createClient } from '@supabase/supabase-js' if (!process.env.SUPABASE_SECRET_KEY) { throw new Error('Missing `SUPABASE_SECRET_KEY` environment variable.') } // Create a single supabase client for interacting with your database const supabase = createClient( process.env.SUPABASE_URL, process.env.SUPABASE_SECRET_KEY, ) let { data, error } = await supabase .from('images') .select('*') .neq('ignore', true) .is('image_embedding', null); if (error) { throw error; } // Load processor and vision model const model_id = 'Xenova/clip-vit-base-patch16'; const processor = await AutoProcessor.from_pretrained(model_id); const vision_model = await CLIPVisionModelWithProjection.from_pretrained(model_id, { quantized: false, }); for (const image_data of data) { let image; try { image = await RawImage.read(image_data.photo_image_url); } catch (e) { // Unable to load image, so we ignore it console.warn('Ignoring image due to error', e) await supabase .from('images') .update({ ignore: true }) .eq('photo_id', image_data.photo_id) .select() continue; } // Read image and run processor let image_inputs = await processor(image); // Compute embeddings const { image_embeds } = await vision_model(image_inputs); const embed_as_list = image_embeds.tolist()[0]; // https://supabase.com/docs/guides/ai/vector-columns#storing-a-vector--embedding const { data, error } = await supabase .from('images') .update({ image_embedding: embed_as_list }) .eq('photo_id', image_data.photo_id) .select() if (error) { console.error('error', error) } else { console.log('success', image_data.photo_id) } }
transformers.js/examples/semantic-image-search/scripts/update-database.mjs/0
{ "file_path": "transformers.js/examples/semantic-image-search/scripts/update-database.mjs", "repo_id": "transformers.js", "token_count": 778 }
351
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Transformers.js | Real-time object detection</title> </head> <body> <h1> Real-time object detection w/ <a href="https://github.com/huggingface/transformers.js" target="_blank">🤗 Transformers.js</a> </h1> <h4> Runs locally in your browser, powered by <a href="https://github.com/WongKinYiu/yolov9" target="_blank">YOLOv9</a> </h4> <div id="container"> <video id="video" autoplay muted playsinline></video> <canvas id="canvas" width="360" height="240"></canvas> <div id="overlay"></div> </div> <div id="controls"> <div> <label>Image size</label> (<label id="size-value">128</label>) <br> <input id="size" type="range" min="64" max="256" step="32" value="128" disabled> </div> <div> <label>Threshold</label> (<label id="threshold-value">0.25</label>) <br> <input id="threshold" type="range" min="0.01" max="1" step="0.01" value="0.25" disabled> </div> <div> <label>Image scale</label> (<label id="scale-value">0.5</label>) <br> <input id="scale" type="range" min="0" max="1" step="0.01" value="0.5" disabled> </div> </div> <label id="status"></label> <script type="module" src="/main.js"></script> </body> </html>
transformers.js/examples/video-object-detection/index.html/0
{ "file_path": "transformers.js/examples/video-object-detection/index.html", "repo_id": "transformers.js", "token_count": 608 }
352
* { box-sizing: border-box; padding: 0; margin: 0; font-family: sans-serif; } html, body { height: 100%; } body { padding: 16px 32px; } body, #container { display: flex; flex-direction: column; justify-content: center; align-items: center; } #controls { display: flex; padding: 1rem; gap: 1rem; } #controls>div { text-align: center; } h1, h3 { text-align: center; } h3 { margin-top: 0.5rem; } #container { display: flex; flex-direction: row; position: relative; max-width: 100%; max-height: 100%; border: 2px dashed #D1D5DB; border-radius: 0.75rem; overflow: hidden; margin-top: 1rem; background-size: 100% 100%; background-position: center; background-repeat: no-repeat; } #video, #output-canvas { width: 504px; height: 504px; } canvas { width: 100%; height: 100%; } #status { min-height: 16px; margin: 8px 0; }
transformers.js/examples/webgpu-video-depth-estimation/style.css/0
{ "file_path": "transformers.js/examples/webgpu-video-depth-estimation/style.css", "repo_id": "transformers.js", "token_count": 372 }
353
export default function CrossIcon(props) { return ( <svg {...props} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" > <path d="m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /> </svg> ) }
transformers.js/examples/webgpu-vlm/src/components/icons/CrossIcon.jsx/0
{ "file_path": "transformers.js/examples/webgpu-vlm/src/components/icons/CrossIcon.jsx", "repo_id": "transformers.js", "token_count": 304 }
354
import { useEffect, useState, useRef, useCallback } from 'react'; import Progress from './components/Progress'; import MediaInput from './components/MediaInput'; import Transcript from './components/Transcript'; import LanguageSelector from './components/LanguageSelector'; async function hasWebGPU() { if (!navigator.gpu) { return false; } try { const adapter = await navigator.gpu.requestAdapter(); return !!adapter; } catch (e) { return false; } } function App() { // Create a reference to the worker object. const worker = useRef(null); // Model loading and progress const [status, setStatus] = useState(null); const [loadingMessage, setLoadingMessage] = useState(''); const [progressItems, setProgressItems] = useState([]); const mediaInputRef = useRef(null); const [audio, setAudio] = useState(null); const [language, setLanguage] = useState('en'); const [result, setResult] = useState(null); const [time, setTime] = useState(null); const [currentTime, setCurrentTime] = useState(0); const [device, setDevice] = useState('webgpu'); // Try use WebGPU first const [modelSize, setModelSize] = useState('gpu' in navigator ? 196 : 77); // WebGPU=196MB, WebAssembly=77MB useEffect(() => { hasWebGPU().then((result) => { setModelSize(result ? 196 : 77); setDevice(result ? 'webgpu' : 'wasm'); }); }, []); // We use the `useEffect` hook to setup the worker as soon as the `App` component is mounted. useEffect(() => { if (!worker.current) { // Create the worker if it does not yet exist. worker.current = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }); } // Create a callback function for messages from the worker thread. const onMessageReceived = (e) => { switch (e.data.status) { case 'loading': // Model file start load: add a new progress item to the list. setStatus('loading'); setLoadingMessage(e.data.data); break; case 'initiate': setProgressItems(prev => [...prev, e.data]); break; case 'progress': // Model file progress: update one of the progress items. setProgressItems( prev => prev.map(item => { if (item.file === e.data.file) { return { ...item, ...e.data } } return item; }) ); break; case 'done': // Model file loaded: remove the progress item from the list. setProgressItems( prev => prev.filter(item => item.file !== e.data.file) ); break; case 'ready': // Pipeline ready: the worker is ready to accept messages. setStatus('ready'); break; case 'complete': setResult(e.data.result); setTime(e.data.time); setStatus('ready'); break; } }; // Attach the callback function as an event listener. worker.current.addEventListener('message', onMessageReceived); // Define a cleanup function for when the component is unmounted. return () => { worker.current.removeEventListener('message', onMessageReceived); }; }, []); const handleClick = useCallback(() => { setResult(null); setTime(null); if (status === null) { setStatus('loading'); worker.current.postMessage({ type: 'load', data: { device } }); } else { setStatus('running'); worker.current.postMessage({ type: 'run', data: { audio, language } }); } }, [status, audio, language, device]); return ( <div className="flex flex-col h-screen mx-auto items justify-end text-gray-800 dark:text-gray-200 bg-white dark:bg-gray-900 max-w-[560px]"> {status === 'loading' && ( <div className="flex justify-center items-center fixed w-screen h-screen bg-black z-10 bg-opacity-[92%] top-0 left-0"> <div className="w-[500px]"> <p className="text-center mb-1 text-white text-md">{loadingMessage}</p> {progressItems.map(({ file, progress, total }, i) => ( <Progress key={i} text={file} percentage={progress} total={total} /> ))} </div> </div> )} <div className="h-full flex justify-center items-center flex-col relative"> <div className="flex flex-col items-center mb-1 text-center"> <h1 className="text-5xl font-bold mb-2">Whisper Timestamped</h1> <h2 className="text-xl font-semibold">In-browser speech recognition w/ word-level timestamps</h2> </div> <div className="w-full min-h-[220px] flex flex-col justify-center items-center p-2"> { !audio && ( <p className="mb-2"> You are about to download <a href="https://huggingface.co/onnx-community/whisper-base_timestamped" target="_blank" rel="noreferrer" className="font-medium underline">whisper-base (timestamped)</a>, a 73 million parameter speech recognition model with the ability to generate word-level timestamps across 100 different languages. Once loaded, the model ({modelSize}&nbsp;MB) will be cached and reused when you revisit the page.<br /> <br /> Everything runs locally in your browser using <a href="https://huggingface.co/docs/transformers.js" target="_blank" rel="noreferrer" className="underline">🤗&nbsp;Transformers.js</a> and ONNX Runtime Web, meaning no API calls are made to a server for inference. You can even disconnect from the internet after the model has loaded! </p> ) } <div className="flex flex-col w-full m-3"> <span className="text-sm mb-0.5">Input audio/video</span> <MediaInput ref={mediaInputRef} className="flex items-center border rounded-md cursor-pointer min-h-[100px] max-h-[500px] overflow-hidden" onInputChange={(result) => setAudio(result)} onTimeUpdate={(time) => setCurrentTime(time)} /> </div> <div className="relative w-full flex justify-center items-center"> <button className="border px-4 py-2 rounded-lg bg-blue-400 text-white hover:bg-blue-500 disabled:bg-blue-100 disabled:cursor-not-allowed select-none" onClick={handleClick} disabled={status === 'running' || (status !== null && audio === null)} > {status === null ? 'Load model' : status === 'running' ? 'Running...' : 'Run model' } </button> {status !== null && <div className='absolute right-0 bottom-0'> <span className="text-xs">Language:</span> <br /> <LanguageSelector className="border rounded-lg p-1 max-w-[100px]" language={language} setLanguage={setLanguage} /> </div> } </div> { result && time && ( <> <div className="w-full mt-4 border rounded-md"> <Transcript className="p-2 max-h-[200px] overflow-y-auto scrollbar-thin select-none" transcript={result} currentTime={currentTime} setCurrentTime={(time) => { setCurrentTime(time); mediaInputRef.current.setMediaTime(time); }} /> </div> <p className="text-sm text-gray-600 text-end p-1">Generation time: <span className="text-gray-800 font-semibold">{time.toFixed(2)}ms</span></p> </> ) } </div> </div> </div > ) } export default App
transformers.js/examples/whisper-word-timestamps/src/App.jsx/0
{ "file_path": "transformers.js/examples/whisper-word-timestamps/src/App.jsx", "repo_id": "transformers.js", "token_count": 3492 }
355
# Support exporting vision and text models separately: # Adapted from https://github.com/huggingface/optimum/issues/1186#issuecomment-1637641760 from optimum.exporters.onnx.model_configs import SiglipTextOnnxConfig, ViTOnnxConfig from typing import Dict class SiglipVisionOnnxConfig(ViTOnnxConfig): pass class SiglipTextModelOnnxConfig(SiglipTextOnnxConfig): @property def outputs(self) -> Dict[str, Dict[int, str]]: return { "last_hidden_state": {0: "batch_size", 1: "sequence_length"}, "pooler_output": {0: "batch_size"}, } def generate_dummy_inputs(self, framework: str = "pt", **kwargs): dummy_inputs = super().generate_dummy_inputs(framework=framework, **kwargs) if framework == "pt": import torch dummy_inputs["input_ids"] = dummy_inputs["input_ids"].to(dtype=torch.int64) return dummy_inputs class SiglipVisionModelOnnxConfig(SiglipVisionOnnxConfig): @property def outputs(self) -> Dict[str, Dict[int, str]]: return { "last_hidden_state": {0: "batch_size"}, "pooler_output": {0: "batch_size"}, }
transformers.js/scripts/extra/siglip.py/0
{ "file_path": "transformers.js/scripts/extra/siglip.py", "repo_id": "transformers.js", "token_count": 496 }
356
/** * @module generation/logits_process */ import { Callable } from "../utils/generic.js"; import { Tensor } from "../utils/tensor.js"; import { max, log_softmax } from "../utils/maths.js"; /** * Abstract base class for all logit processors that can be applied during generation. */ export class LogitsProcessor extends Callable { /** * Apply the processor to the input logits. * * @abstract * @param {bigint[][]} input_ids The input ids. * @param {Tensor} logits The logits to process. * @throws {Error} Throws an error if `_call` is not implemented in the subclass. */ _call(input_ids, logits) { throw Error("`_call` should be implemented in a subclass") } } /** * Abstract base class for all logit warpers that can be applied during generation with multinomial sampling. */ export class LogitsWarper extends Callable { /** * Apply the processor to the input logits. * * @abstract * @param {bigint[][]} input_ids The input ids. * @param {Tensor} logits The logits to process. * @throws {Error} Throws an error if `_call` is not implemented in the subclass. */ _call(input_ids, logits) { throw Error("`_call` should be implemented in a subclass") } } /** * A class representing a list of logits processors. A logits processor is a function that modifies the logits * output of a language model. This class provides methods for adding new processors and applying all processors to a * batch of logits. */ export class LogitsProcessorList extends Callable { /** * Constructs a new instance of `LogitsProcessorList`. */ constructor() { super(); this.processors = []; } /** * Adds a new logits processor to the list. * * @param {LogitsProcessor} item The logits processor function to add. */ push(item) { this.processors.push(item); } /** * Adds multiple logits processors to the list. * * @param {LogitsProcessor[]} items The logits processor functions to add. */ extend(items) { this.processors.push(...items); } /** * Applies all logits processors in the list to a batch of logits, modifying them in-place. * * @param {bigint[][]} input_ids The input IDs for the language model. * @param {Tensor} logits */ _call(input_ids, logits) { let toReturn = logits; // NOTE: Most processors modify logits inplace for (const processor of this.processors) { toReturn = processor(input_ids, toReturn); } return toReturn; } [Symbol.iterator]() { return this.processors.values(); } } // DEPRECATED: https://github.com/huggingface/transformers/pull/29485 // /** // * A logits processor that forces a specific token to be generated by the decoder. // */ // export class ForceTokensLogitsProcessor extends LogitsProcessor { // /** // * Constructs a new instance of `ForceTokensLogitsProcessor`. // * // * @param {[number, number][]} forced_decoder_ids The ids of tokens that should be forced. // */ // constructor(forced_decoder_ids) { // super(); // // TODO: convert to `new Map(forced_decoder_ids)` // this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []); // } // /** // * Apply the processor to the input logits. // * // * @param {bigint[][]} input_ids The input ids. // * @param {Tensor} logits The logits to process. // * @returns {Tensor} The processed logits. // */ // _call(input_ids, logits) { // console.log('this.force_token_map', this.force_token_map) // console.log('call ForceTokensLogitsProcessor', input_ids, logits) // console.log('input_ids.length', input_ids.length) // let map = this.force_token_map[input_ids.length]; // if (map) { // There exists a mapping // logits.data.fill(-Infinity) // logits.data[map] = 0; // } // console.log('map', map) // // throw Error("Not implemented") // return logits; // } // } /** * A LogitsProcessor that forces a BOS token at the beginning of the generated sequence. */ export class ForcedBOSTokenLogitsProcessor extends LogitsProcessor { /** * Create a ForcedBOSTokenLogitsProcessor. * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced. */ constructor(bos_token_id) { super(); this.bos_token_id = bos_token_id; } /** * Apply the BOS token forcing to the logits. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The logits with BOS token forcing. */ _call(input_ids, logits) { for (let i = 0; i < input_ids.length; ++i) { if (input_ids[i].length === 1) { const batch_logits_data = /** @type {Float32Array} */(logits[i].data); batch_logits_data.fill(-Infinity); batch_logits_data[this.bos_token_id] = 0; } } return logits; } } /** * A logits processor that enforces the specified token as the last generated token when `max_length` is reached. */ export class ForcedEOSTokenLogitsProcessor extends LogitsProcessor { /** * Create a ForcedEOSTokenLogitsProcessor. * @param {number} max_length The maximum length of the sequence to be generated. * @param {number|number[]} eos_token_id The id(s) of the *end-of-sequence* token. */ constructor(max_length, eos_token_id) { super(); this.max_length = max_length; this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; } /** * Apply the processor to input_ids and logits. * * @param {bigint[][]} input_ids The input ids. * @param {Tensor} logits The logits tensor. */ _call(input_ids, logits) { for (let i = 0; i < input_ids.length; ++i) { if (input_ids[i].length === this.max_length - 1) { const batch_logits_data = /** @type {Float32Array} */(logits[i].data); batch_logits_data.fill(-Infinity); for (const eos_token of this.eos_token_id) { batch_logits_data[eos_token] = 0; } } } return logits; } } /** * A LogitsProcessor that suppresses a list of tokens as soon as the `generate` function starts * generating using `begin_index` tokens. This should ensure that the tokens defined by * `begin_suppress_tokens` at not sampled at the begining of the generation. */ export class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor { /** * Create a SuppressTokensAtBeginLogitsProcessor. * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress. * @param {number} begin_index The number of tokens to generate before suppressing tokens. */ constructor(begin_suppress_tokens, begin_index) { super(); this.begin_suppress_tokens = begin_suppress_tokens; this.begin_index = begin_index; } /** * Apply the BOS token forcing to the logits. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The logits with BOS token forcing. */ _call(input_ids, logits) { for (let i = 0; i < input_ids.length; ++i) { if (input_ids[i].length === this.begin_index) { const batch_logits_data = /** @type {Float32Array} */(logits[i].data); for (const token_id of this.begin_suppress_tokens) { batch_logits_data[token_id] = -Infinity; } } } return logits; } } /** * A LogitsProcessor that handles adding timestamps to generated text. */ export class WhisperTimeStampLogitsProcessor extends LogitsProcessor { /** * Constructs a new WhisperTimeStampLogitsProcessor. * @param {import('../models/whisper/generation_whisper.js').WhisperGenerationConfig} generate_config The config object passed to the `generate()` method of a transformer model. * @param {number[]} init_tokens The initial tokens of the input sequence. */ constructor(generate_config, init_tokens) { super(); this.eos_token_id = Array.isArray(generate_config.eos_token_id) ? generate_config.eos_token_id[0] : generate_config.eos_token_id; this.no_timestamps_token_id = generate_config.no_timestamps_token_id; this.timestamp_begin = this.no_timestamps_token_id + 1; this.begin_index = init_tokens.length; if (init_tokens.at(-1) === this.no_timestamps_token_id) { this.begin_index -= 1; } this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index; } /** * Modify the logits to handle timestamp tokens. * @param {bigint[][]} input_ids The input sequence of tokens. * @param {Tensor} logits The logits output by the model. * @returns {Tensor} The modified logits. */ _call(input_ids, logits) { for (let i = 0; i < input_ids.length; ++i) { const batch_logits_data = /** @type {Float32Array} */(logits[i].data); // suppress <|notimestamps|> which is handled by without_timestamps batch_logits_data[this.no_timestamps_token_id] = -Infinity; if (input_ids[i].length === this.begin_index - 1) { batch_logits_data.fill(-Infinity); batch_logits_data[this.timestamp_begin] = 0; continue; } // timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly const seq = input_ids[i].slice(this.begin_index); const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin; const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin; if (last_was_timestamp) { if (penultimate_was_timestamp) { // has to be non-timestamp batch_logits_data.subarray(this.timestamp_begin).fill(-Infinity); } else { // cannot be normal text tokens batch_logits_data.subarray(0, this.eos_token_id).fill(-Infinity); } } // apply the `max_initial_timestamp` option if (input_ids[i].length === this.begin_index && this.max_initial_timestamp_index !== null) { const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index; batch_logits_data.subarray(last_allowed + 1).fill(-Infinity); } // if sum of probability over timestamps is above any other token, sample timestamp const logprobs = log_softmax(batch_logits_data); const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b)); const max_text_token_logprob = max(logprobs.subarray(0, this.timestamp_begin))[0]; if (timestamp_logprob > max_text_token_logprob) { batch_logits_data.subarray(0, this.timestamp_begin).fill(-Infinity); } } return logits; } } /** * A logits processor that disallows ngrams of a certain size to be repeated. */ export class NoRepeatNGramLogitsProcessor extends LogitsProcessor { /** * Create a NoRepeatNGramLogitsProcessor. * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once. */ constructor(no_repeat_ngram_size) { super(); this.no_repeat_ngram_size = no_repeat_ngram_size; } /** * Generate n-grams from a sequence of token ids. * @param {bigint[]} prevInputIds List of previous input ids * @returns {Map<string, number[]>} Map of generated n-grams */ getNgrams(prevInputIds) { const curLen = prevInputIds.length; /**@type {number[][]} */ const ngrams = []; for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) { const ngram = []; for (let k = 0; k < this.no_repeat_ngram_size; ++k) { ngram.push(prevInputIds[j + k]); } ngrams.push(ngram.map(Number)); } /** @type {Map<string, number[]>} */ const generatedNgram = new Map(); for (const ngram of ngrams) { const prevNgram = ngram.slice(0, ngram.length - 1); const prevNgramKey = JSON.stringify(prevNgram); const prevNgramValue = generatedNgram.get(prevNgramKey) ?? []; prevNgramValue.push(ngram[ngram.length - 1]); generatedNgram.set(prevNgramKey, prevNgramValue); } return generatedNgram; } /** * Generate n-grams from a sequence of token ids. * @param {Map<string, number[]>} bannedNgrams Map of banned n-grams * @param {bigint[]} prevInputIds List of previous input ids * @returns {number[]} Map of generated n-grams */ getGeneratedNgrams(bannedNgrams, prevInputIds) { const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length); const banned = bannedNgrams.get(JSON.stringify(ngramIdx.map(Number))) ?? []; return banned; } /** * Calculate banned n-gram tokens * @param {bigint[]} prevInputIds List of previous input ids * @returns {number[]} Map of generated n-grams */ calcBannedNgramTokens(prevInputIds) { const bannedTokens = []; if (prevInputIds.length + 1 < this.no_repeat_ngram_size) { // return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet return bannedTokens; } else { const generatedNgrams = this.getNgrams(prevInputIds); const bannedTokens = this.getGeneratedNgrams(generatedNgrams, prevInputIds); return bannedTokens; } } /** * Apply the no-repeat-ngram processor to the logits. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The logits with no-repeat-ngram processing. */ _call(input_ids, logits) { for (let i = 0; i < input_ids.length; ++i) { const batch_logits_data = /** @type {Float32Array} */(logits[i].data); const bannedTokens = this.calcBannedNgramTokens(input_ids[i]); for (const token of bannedTokens) { batch_logits_data[token] = -Infinity; } } return logits; } } /** * A logits processor that prevents the repetition of previous tokens through a penalty. * This penalty is applied at most once per token. Note that, for decoder-only models like most LLMs, * the considered tokens include the prompt. * * In the original [paper](https://huggingface.co/papers/1909.05858), the authors suggest the use of a * penalty of around 1.2 to achieve a good balance between truthful generation and lack of repetition. * To penalize and reduce repetition, use `penalty` values above 1.0, where a higher value penalizes * more strongly. To reward and encourage repetition, use `penalty` values between 0.0 and 1.0, where * a lower value rewards more strongly. */ export class RepetitionPenaltyLogitsProcessor extends LogitsProcessor { /** * Create a RepetitionPenaltyLogitsProcessor. * @param {number} penalty The parameter for repetition penalty. * - 1.0 means no penalty. Above 1.0 penalizes previously generated tokens. * - Between 0.0 and 1.0 rewards previously generated tokens. */ constructor(penalty) { super(); this.penalty = penalty; } /** * Apply the repetition penalty to the logits. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The logits with repetition penalty processing. */ _call(input_ids, logits) { for (let i = 0; i < input_ids.length; ++i) { const batch_logits_data = /** @type {Float32Array} */(logits[i].data); for (const input_id of new Set(input_ids[i])) { const token = Number(input_id); if (batch_logits_data[token] < 0) { batch_logits_data[token] *= this.penalty; } else { batch_logits_data[token] /= this.penalty; } } } return logits } } /** * A logits processor that enforces a minimum number of tokens. */ export class MinLengthLogitsProcessor extends LogitsProcessor { /** * Create a MinLengthLogitsProcessor. * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity. * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. */ constructor(min_length, eos_token_id) { super(); this.min_length = min_length; this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; } /** * Apply logit processor. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The processed logits. */ _call(input_ids, logits) { for (let i = 0; i < input_ids.length; ++i) { if (input_ids[i].length < this.min_length) { const batch_logits_data = /** @type {Float32Array} */(logits[i].data); for (const eos_token of this.eos_token_id) { batch_logits_data[eos_token] = -Infinity; } } } return logits } } /** * A logits processor that enforces a minimum number of new tokens. */ export class MinNewTokensLengthLogitsProcessor extends LogitsProcessor { /** * Create a MinNewTokensLengthLogitsProcessor. * @param {number} prompt_length_to_skip The input tokens length. * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity. * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. */ constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) { super(); this.prompt_length_to_skip = prompt_length_to_skip; this.min_new_tokens = min_new_tokens; this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; } /** * Apply logit processor. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The processed logits. */ _call(input_ids, logits) { for (let i = 0; i < input_ids.length; ++i) { const new_tokens_length = input_ids[i].length - this.prompt_length_to_skip; if (new_tokens_length < this.min_new_tokens) { const batch_logits_data = /** @type {Float32Array} */(logits[i].data); for (const eos_token of this.eos_token_id) { batch_logits_data[eos_token] = -Infinity; } } } return logits } } export class NoBadWordsLogitsProcessor extends LogitsProcessor { /** * Create a `NoBadWordsLogitsProcessor`. * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated. * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. */ constructor(bad_words_ids, eos_token_id) { super(); this.bad_words_ids = bad_words_ids; this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; } /** * Apply logit processor. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The processed logits. */ _call(input_ids, logits) { for (let i = 0; i < input_ids.length; ++i) { const batch_logits_data = /** @type {Float32Array} */(logits[i].data); const ids = input_ids[i]; for (const bad_word_ids of this.bad_words_ids) { // There aren't enough tokens to match the banned sequence if (ids.length < bad_word_ids.length - 1) continue; // Whether to modify the logits of the last token in the bad word id sequence let mark = true; // For each bad word in the list, if the current sequence of input ids ends with this sequence (excluding the last), // then we set the logits of the last bad word id to -Infinity. for (let j = 1; j <= bad_word_ids.length - 1; ++j) { // NOTE: We use != instead of !== to compare bigint and number // @ts-ignore if (bad_word_ids.at(-j - 1) != ids.at(-j)) { // We have found a mismatch mark = false; break; } } if (mark) { batch_logits_data[bad_word_ids.at(-1)] = -Infinity; } } } return logits } } /** * [`LogitsProcessor`] for classifier free guidance (CFG). The scores are split over the batch dimension, * where the first half correspond to the conditional logits (predicted from the input prompt) and the second half * correspond to the unconditional logits (predicted from an empty or 'null' prompt). The processor computes a * weighted average across the conditional and unconditional logits, parameterised by the `guidance_scale`. * * See [the paper](https://huggingface.co/papers/2306.05284) for more information. */ export class ClassifierFreeGuidanceLogitsProcessor extends LogitsProcessor { /** * Create a `ClassifierFreeGuidanceLogitsProcessor`. * @param {number} guidance_scale The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`. * Higher guidance scale encourages the model to generate samples that are more closely linked to the input * prompt, usually at the expense of poorer quality. */ constructor(guidance_scale) { super(); if (guidance_scale <= 1) { throw new Error( `Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${guidance_scale}.` ) } this.guidance_scale = guidance_scale; } /** * Apply logit processor. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The processed logits. */ _call(input_ids, logits) { if (logits.dims[0] !== 2 * input_ids.length) { throw new Error( `Logits should have twice the batch size of the input ids, the first half of batches corresponding to ` + `the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got ` + `batch size ${logits.dims[0]} for the logits and ${input_ids.length} for the input ids.` ) } const unguided_bsz = input_ids.length; const cond_logits = logits.slice([0, unguided_bsz], null); const uncond_logits = logits.slice([unguided_bsz, logits.dims[0]], null); // Merge into uncond_logits (to save memory). This is equivalent to the following: // scores = uncond_logits + (cond_logits - uncond_logits) * guidance_scale for (let i = 0; i < uncond_logits.data.length; ++i) { uncond_logits.data[i] += (cond_logits.data[i] - uncond_logits.data[i]) * this.guidance_scale; } return uncond_logits; } } /** * [`LogitsWarper`] for temperature (exponential scaling output probability distribution), which effectively means * that it can control the randomness of the predicted tokens. Often used together with [`TopPLogitsWarper`] and [`TopKLogitsWarper`]. */ export class TemperatureLogitsWarper extends LogitsWarper { /** * Create a `TemperatureLogitsWarper`. * @param {number} temperature Strictly positive float value used to modulate the logits distribution. * A value smaller than `1` decreases randomness (and vice versa), with `0` being equivalent to shifting * all probability mass to the most likely token. */ constructor(temperature) { super(); if (typeof temperature !== 'number' || temperature <= 0) { let errorMessage = `\`temperature\` (=${temperature}) must be a strictly positive float, otherwise your next token scores will be invalid.`; if (temperature === 0) { errorMessage += " If you're looking for greedy decoding strategies, set `do_sample=false`." } } this.temperature = temperature; } /** * Apply logit warper. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The processed logits. */ _call(input_ids, logits) { const batch_logits_data = /** @type {Float32Array} */(logits.data); for (let i = 0; i < batch_logits_data.length; ++i) { batch_logits_data[i] /= this.temperature; } return logits; } } /** * [`LogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off. * Often used together with [`TemperatureLogitsWarper`] and [`TopKLogitsWarper`]. */ export class TopPLogitsWarper extends LogitsWarper { /** * Create a `TopPLogitsWarper`. * @param {number} top_p If set to < 1, only the smallest set of most probable tokens with * probabilities that add up to `top_p` or higher are kept for generation. * @param {Object} options Additional options for the top-p sampling. * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value. * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered. */ constructor(top_p, { filter_value = -Infinity, min_tokens_to_keep = 1, } = {}) { super(); if (top_p < 0 || top_p > 1.0) { throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${top_p}`) } if (!Number.isInteger(min_tokens_to_keep) || min_tokens_to_keep < 1) { throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${min_tokens_to_keep}`) } this.top_p = top_p this.filter_value = filter_value this.min_tokens_to_keep = min_tokens_to_keep } } /** * [`LogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements. * Often used together with [`TemperatureLogitsWarper`] and [`TopPLogitsWarper`]. */ export class TopKLogitsWarper extends LogitsWarper { /** * Create a `TopKLogitsWarper`. * @param {number} top_k If set to > 0, only the top `top_k` tokens are kept for generation. * @param {Object} options Additional options for the top-k sampling. * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value. * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered. */ constructor(top_k, { filter_value = -Infinity, min_tokens_to_keep = 1, } = {}) { super(); if (!Number.isInteger(top_k) || top_k < 0) { throw new Error(`\`top_k\` must be a positive integer, but is ${top_k}`) } this.top_k = Math.max(top_k, min_tokens_to_keep) this.filter_value = filter_value } }
transformers.js/src/generation/logits_process.js/0
{ "file_path": "transformers.js/src/generation/logits_process.js", "repo_id": "transformers.js", "token_count": 11828 }
357
import { EncodecFeatureExtractor } from '../encodec/feature_extraction_encodec.js'; export class DacFeatureExtractor extends EncodecFeatureExtractor { }
transformers.js/src/models/dac/feature_extraction_dac.js/0
{ "file_path": "transformers.js/src/models/dac/feature_extraction_dac.js", "repo_id": "transformers.js", "token_count": 46 }
358
import { Processor } from "../../base/processing_utils.js"; import { AutoImageProcessor } from "../auto/image_processing_auto.js"; import { AutoTokenizer } from "../../tokenizers.js"; import { RawImage } from "../../utils/image.js"; import { count } from "../../utils/core.js"; /** * Prompt with expanded image tokens for when the image is split into patches. * @private */ function _prompt_split_image(image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token) { let text_split_images = ""; for (let n_h = 0; n_h < image_rows; ++n_h) { for (let n_w = 0; n_w < image_cols; ++n_w) { text_split_images += ( fake_token_around_image + `<row_${n_h + 1}_col_${n_w + 1}>` + image_token.repeat(image_seq_len) ); } text_split_images += "\n"; } text_split_images += ( `\n${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_seq_len) + `${fake_token_around_image}` ); return text_split_images; } /** * Prompt with expanded image tokens for a single image. * @private */ function _prompt_single_image(image_seq_len, fake_token_around_image, image_token, global_img_token) { return ( `${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_seq_len) + `${fake_token_around_image}` ); } function get_image_prompt_string(image_rows, image_cols, image_seq_len, fake_token_around_image, image_token, global_img_token) { if (image_rows === 0 && image_cols === 0) { return _prompt_single_image( image_seq_len, fake_token_around_image, image_token, global_img_token ); } return _prompt_split_image( image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token ); } export class Idefics3Processor extends Processor { static image_processor_class = AutoImageProcessor static tokenizer_class = AutoTokenizer static uses_processor_config = true; fake_image_token = "<fake_token_around_image>"; image_token = "<image>"; global_img_token = "<global-img>"; /** * * @param {string|string[]} text * @param {RawImage|RawImage[]|RawImage[][]} images * @returns {Promise<any>} */ async _call(text, images = null, options = {}) { options.return_row_col_info ??= true; let image_inputs; if (images) { image_inputs = await this.image_processor(images, options); } // NOTE: We assume text is present if (!Array.isArray(text)) { text = [text]; } const image_rows = image_inputs.rows ?? [new Array(text.length).fill(0)]; const image_cols = image_inputs.cols ?? [new Array(text.length).fill(0)]; const image_seq_len = this.config.image_seq_len; const n_images_in_text = [] const prompt_strings = []; for (let i = 0; i < text.length; ++i) { const sample = text[i]; const sample_rows = image_rows[i]; const sample_cols = image_cols[i]; n_images_in_text.push(count(sample, this.image_token)); // Replace the image token with fake tokens around the expanded image token sequence of length `image_seq_len` const image_prompt_strings = sample_rows.map( (n_rows, j) => get_image_prompt_string( n_rows, sample_cols[j], image_seq_len, this.fake_image_token, this.image_token, this.global_img_token, ) ); const split_sample = sample.split(this.image_token); if (split_sample.length === 0) { throw new Error("The image token should be present in the text."); } // Place in the image prompt strings where the image tokens are let new_sample = split_sample[0]; for (let j = 0; j < image_prompt_strings.length; ++j) { new_sample += image_prompt_strings[j] + split_sample[j + 1]; } prompt_strings.push(new_sample); } const text_inputs = this.tokenizer(prompt_strings); return { ...text_inputs, ...image_inputs, } } }
transformers.js/src/models/idefics3/processing_idefics3.js/0
{ "file_path": "transformers.js/src/models/idefics3/processing_idefics3.js", "repo_id": "transformers.js", "token_count": 2081 }
359
import { FeatureExtractor, validate_audio_inputs } from '../../base/feature_extraction_utils.js'; import { Tensor } from '../../utils/tensor.js'; export class MoonshineFeatureExtractor extends FeatureExtractor { /** * Asynchronously extracts input values from a given audio using the provided configuration. * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. * @returns {Promise<{ input_values: Tensor; }>} The extracted input values. */ async _call(audio) { validate_audio_inputs(audio, 'MoonshineFeatureExtractor'); if (audio instanceof Float64Array) { audio = new Float32Array(audio); } const shape = [ 1, /* batch_size */ audio.length, /* num_samples */ ]; return { input_values: new Tensor('float32', audio, shape), }; } }
transformers.js/src/models/moonshine/feature_extraction_moonshine.js/0
{ "file_path": "transformers.js/src/models/moonshine/feature_extraction_moonshine.js", "repo_id": "transformers.js", "token_count": 364 }
360
import { ImageProcessor, } from "../../base/image_processors_utils.js"; import { calculateDimensions } from "../../utils/core.js"; import { interpolate_4d, Tensor, } from "../../utils/tensor.js"; /** * @typedef {object} SamImageProcessorResult * @property {Tensor} pixel_values * @property {import("../../base/image_processors_utils.js").HeightWidth[]} original_sizes * @property {import("../../base/image_processors_utils.js").HeightWidth[]} reshaped_input_sizes * @property {Tensor} [input_points] * @property {Tensor} [input_labels] * @property {Tensor} [input_boxes] */ export class SamImageProcessor extends ImageProcessor { /** * * @param {any} input_points * @param {import("../../base/image_processors_utils.js").HeightWidth[]} original_sizes * @param {import("../../base/image_processors_utils.js").HeightWidth[]} reshaped_input_sizes * @returns {Tensor} */ reshape_input_points(input_points, original_sizes, reshaped_input_sizes, is_bounding_box = false) { // Make deep copy to avoid altering user's input input_points = structuredClone(input_points); let shape = calculateDimensions(input_points); // TODO: add support for 2D input_points if (shape.length === 3) { // Correct user's input if (!is_bounding_box) { shape = [1, ...shape]; } input_points = [input_points]; } else if (shape.length !== 4) { throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.") } // Reshape input points for (let i = 0; i < input_points.length; ++i) { // batch_size let originalImageSize = original_sizes[i]; let reshapedImageSize = reshaped_input_sizes[i]; let resizeFactors = [ reshapedImageSize[0] / originalImageSize[0], reshapedImageSize[1] / originalImageSize[1] ] for (let j = 0; j < input_points[i].length; ++j) { // point_batch_size for (let k = 0; k < input_points[i][j].length; ++k) { // nb_points_per_image for (let w = 0; w < input_points[i][j][k].length; ++w) { // 2 or 4 input_points[i][j][k][w] *= resizeFactors[w % 2]; } } } } return new Tensor( 'float32', Float32Array.from(input_points.flat(Infinity)), shape ) } /** * * @param {any} input_labels * @param {Tensor} input_points * @returns {Tensor} */ add_input_labels(input_labels, input_points) { let shape = calculateDimensions(input_labels); if (shape.length === 2) { // Correct user's input shape = [1, ...shape]; input_labels = [input_labels]; } else if (shape.length !== 3) { throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.") } if (shape.some((x, i) => x !== input_points.dims[i])) { throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`) } return new Tensor( 'int64', input_labels.flat(Infinity).map(BigInt), shape, ) } /** * @param {any[]} images The URL(s) of the image(s) to extract features from. * @param {Object} [options] Additional options for the processor. * @param {any} [options.input_points=null] A 3D or 4D array, representing the input points provided by the user. * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1. * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`. * @param {any} [options.input_labels=null] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt. * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1. * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`. * @param {number[][][]} [options.input_boxes=null] A 3D array of shape `(batch_size, num_boxes, 4)`, representing the input boxes provided by the user. * This is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks. * The processor will generate a tensor, with each dimension corresponding respectively to the image batch size, * the number of boxes per image and the coordinates of the top left and botton right point of the box. * In the order (`x1`, `y1`, `x2`, `y2`): * - `x1`: the x coordinate of the top left point of the input box * - `y1`: the y coordinate of the top left point of the input box * - `x2`: the x coordinate of the bottom right point of the input box * - `y2`: the y coordinate of the bottom right point of the input box * @returns {Promise<SamImageProcessorResult>} */ async _call(images, { input_points = null, input_labels = null, input_boxes = null } = {}) { // TODO allow user to use preprocessed images /** @type {SamImageProcessorResult} */ const processed = await super._call(images); if (input_points) { processed.input_points = this.reshape_input_points( input_points, processed.original_sizes, processed.reshaped_input_sizes ); } if (input_labels) { if (!processed.input_points) { throw Error("`input_points` must be provided if `input_labels` are provided.") } processed.input_labels = this.add_input_labels(input_labels, processed.input_points); } if (input_boxes) { processed.input_boxes = this.reshape_input_points( input_boxes, processed.original_sizes, processed.reshaped_input_sizes, true, ); } return processed; } /** * Remove padding and upscale masks to the original image size. * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format. * @param {[number, number][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format. * @param {[number, number][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding. * @param {Object} options Optional parameters for post-processing. * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks. * @param {boolean} [options.binarize] Whether to binarize the masks. * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`. * @param {number} [options.pad_size.height] The height the images were padded to. * @param {number} [options.pad_size.width] The width the images were padded to. * @returns {Promise<Tensor[]>} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size. */ async post_process_masks(masks, original_sizes, reshaped_input_sizes, { mask_threshold = 0.0, binarize = true, pad_size = null, } = {}) { // masks: [1, 1, 3, 256, 256] const output_masks = []; pad_size = pad_size ?? this.pad_size; /** @type {[number, number]} */ const target_image_size = [pad_size.height, pad_size.width]; for (let i = 0; i < original_sizes.length; ++i) { const original_size = original_sizes[i]; const reshaped_input_size = reshaped_input_sizes[i]; // Upscale mask to padded size let interpolated_mask = (await interpolate_4d( masks[i], { mode: 'bilinear', size: target_image_size } )); // Crop mask interpolated_mask = interpolated_mask.slice(null, null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]); // Downscale mask interpolated_mask = (await interpolate_4d( interpolated_mask, { mode: 'bilinear', size: original_size } )); if (binarize) { const data = interpolated_mask.data; const binarizedMaskData = new Uint8Array(data.length); for (let i = 0; i < data.length; ++i) { if (data[i] > mask_threshold) { binarizedMaskData[i] = 1; } } interpolated_mask = new Tensor( 'bool', binarizedMaskData, interpolated_mask.dims ) } output_masks.push(interpolated_mask); } return output_masks; } /** * Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer. * @param {import("../../utils/image.js").RawImage} image Input original image * @param {number} target_size Target size of the resized image * @param {Object} options Options for generating crop boxes * @param {number} [options.crop_n_layers] If >0, mask prediction will be run again on crops of the image. * Sets the number of layers to run, where each layer has 2**i_layer number of image crops. * @param {number} [options.overlap_ratio] Sets the degree to which crops overlap. In the first crop layer, * crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. * @param {number} [options.points_per_crop] Number of points to sample from each crop. * @param {number} [options.crop_n_points_downscale_factor] The number of points-per-side sampled in layer n is * scaled down by crop_n_points_downscale_factor**n. * @returns {Object} An object containing the crop boxes, number of points per crop, cropped images, and input labels. */ generate_crop_boxes(image, target_size, { crop_n_layers = 0, overlap_ratio = 512 / 1500, points_per_crop = 32, crop_n_points_downscale_factor = 1, } = {}) { // TODO: Implement // return { crop_boxes, points_per_crop, cropped_images, input_labels } } }
transformers.js/src/models/sam/image_processing_sam.js/0
{ "file_path": "transformers.js/src/models/sam/image_processing_sam.js", "repo_id": "transformers.js", "token_count": 4498 }
361
import { AutoFeatureExtractor } from "../auto/feature_extraction_auto.js" import { AutoTokenizer } from "../../tokenizers.js" import { Processor } from "../../base/processing_utils.js" import { cat } from "../../utils/tensor.js"; const AUDIO_TOKEN = "[AUDIO]"; const BEGIN_AUDIO_TOKEN = "[BEGIN_AUDIO]"; const NUM_AUDIO_TOKENS = 375; /** * Helper function to split audio into non-overlapping chunks of n_samples * @param {Float32Array} audio * @param {number} n_samples * @returns {Float32Array[]} */ function chunk(audio, n_samples) { const chunks = []; for (let i = 0; i < audio.length; i += n_samples) { chunks.push(audio.subarray(i, Math.min(i + n_samples, audio.length))); } return chunks; } /** * Represents a VoxtralProcessor that extracts features from an audio input. */ export class VoxtralProcessor extends Processor { static tokenizer_class = AutoTokenizer static feature_extractor_class = AutoFeatureExtractor static uses_processor_config = false; /** * @param {string} text The text input to process. * @param {Float32Array|Float32Array[]} audio The audio input(s) to process. */ async _call(text, audio = null, kwargs = {}) { if (Array.isArray(text)) { throw new Error("Batched inputs are not supported yet."); } const audio_inputs = {}; if (audio) { if (!text.includes(AUDIO_TOKEN)) { throw new Error(`The input text does not contain the audio token ${AUDIO_TOKEN}.`); } if (!Array.isArray(audio)) { audio = [audio]; } const text_parts = text.split(AUDIO_TOKEN); const num_audio_tokens = text_parts.length - 1; if (num_audio_tokens !== audio.length) { throw new Error(`The number of audio inputs (${audio.length}) does not match the number of audio tokens in the text (${num_audio_tokens}).`); } const n_samples = this.feature_extractor.config.n_samples; // Split each audio input into chunks and keep track of chunk counts const audio_chunks = audio.map(a => chunk(a, n_samples)); const chunk_counts = audio_chunks.map(chunks => chunks.length); // Flatten all chunks for feature extraction const all_chunks = audio_chunks.flat(); const features = (await Promise.all( all_chunks.map((audio_input) => this.feature_extractor(audio_input, kwargs)) )).map(x => x.input_features); audio_inputs["audio_values"] = features.length > 1 ? cat(features, 0) : features[0]; // Replace text tokens for each audio input, expanding for chunk count let new_text = text_parts[0]; for (let i = 0; i < chunk_counts.length; ++i) { new_text += BEGIN_AUDIO_TOKEN; for (let j = 0; j < chunk_counts[i]; ++j) { new_text += AUDIO_TOKEN.repeat(NUM_AUDIO_TOKENS); } new_text += text_parts[i + 1]; } text = new_text; } const text_inputs = this.tokenizer(text, { add_special_tokens: false, ...kwargs, }); return { ...text_inputs, ...audio_inputs, } } }
transformers.js/src/models/voxtral/processing_voxtral.js/0
{ "file_path": "transformers.js/src/models/voxtral/processing_voxtral.js", "repo_id": "transformers.js", "token_count": 1488 }
362