组件库介绍

November 12, 2024 · View on GitHub

1.基础组件

类名功能说明示例
MLP多层感知机可定制激活函数、initializer、Dropout、BN等案例1
Highway类似残差链接可用来对预训练embedding做增量微调highway network
Gate门控多个输入的加权求和Cross Decoupling Network
PeriodicEmbedding周期激活函数数值特征Embedding案例5
AutoDisEmbedding自动离散化数值特征Embeddingdlrm_on_criteo_with_autodis.config
NaryDisEmbeddingN进制编码数值特征Embeddingdlrm_on_criteo_with_narydis.config
TextCNN文本卷积提取文本序列的特征text_cnn_on_movielens.config

备注:Gate组件的第一个输入是权重向量,后面的输入拼凑成一个列表,权重向量的长度应等于列表的长度

2.特征交叉组件

类名功能说明示例
FM二阶交叉DeepFM模型的组件案例2
DotInteraction二阶内积交叉DLRM模型的组件案例4
Crossbit-wise交叉DCN v2模型的组件案例3
BiLinear双线性FiBiNet模型的组件fibinet_on_movielens.config
FiBiNetSENet & BiLinearFiBiNet模型fibinet_on_movielens.config

3.特征重要度学习组件

类名功能说明示例
SENet建模特征重要度FiBiNet模型的组件MMoE
MaskBlock建模特征重要度MaskNet模型的组件Cross Decoupling Network
MaskNet多个串行或并行的MaskBlockMaskNet模型DBMTL
PPNet参数个性化网络PPNet模型PPNet

4. 序列特征编码组件

类名功能说明示例
DINtarget attentionDIN模型的组件DIN_backbone.config
BSTtransformerBST模型的组件BST_backbone.config
SeqAugment序列数据增强crop, mask, reorderCL4SRec
AttentionDot-product attentionTransformer模型的组件
MultiHeadAttentionMulti-head attentionTransformer模型的组件
TransformerBlockTransformer layerTransformer模型的组件
TransformerEncoderTransformer encoderTransformer模型的组件
TextEncoderBERT 模型类似BERT模型

5. 多目标学习组件

类名功能说明示例
MMoEMultiple Mixture of ExpertsMMoE模型的组件案例8
AITMTowerAITM模型的一个towerAITM模型的组件AITM

6. 辅助损失函数组件

类名功能说明示例
AuxiliaryLoss用来计算辅助损失函数常用在自监督学习中案例7

组件详细参数

1.基础组件

  • MLP (多层感知机)
参数类型默认值说明
hidden_unitslist各隐层单元数
dropout_ratiolist各隐层dropout rate
activationstrrelu每层的激活函数
use_bnbooltrue是否使用batch normalization
use_final_bnbooltrue最后一层是否使用batch normalization
use_biasboolfalse是否使用偏置项
use_final_biasboolfalse最后一层是否使用偏置项
final_activationstrrelu最后一层的激活函数
initializerstrhe_uniform权重初始化方法,参考keras Dense layer
use_bn_after_activationboolfalse是否在激活函数之后做batch norm
  • HighWay
参数类型默认值说明
emb_sizeuint32Noneembedding维度
activationstrgelu激活函数
dropout_ratefloat0dropout rate
init_gate_biasfloat-3.0门控网络的bias初始值
num_layersint1网络层数
  • PeriodicEmbedding
参数类型默认值说明
embedding_dimuint32embedding维度
sigmafloat初始化自定义参数时的标准差,效果敏感、小心调参
add_linear_layerbooltrue是否在embedding之后添加额外的层
linear_activationstrrelu额外添加的层的激活函数
output_tensor_listboolfalse是否同时输出embedding列表
output_3d_tensorboolfalse是否同时输出3d tensor, output_tensor_list=true时该参数不生效
  • AutoDisEmbedding
参数类型默认值说明
embedding_dimuint32embedding维度
num_binsuint32虚拟分桶数量
keep_probfloat0.8残差链接的权重
temperaturefloatsoftmax函数的温度系数
output_tensor_listboolfalse是否同时输出embedding列表
output_3d_tensorboolfalse是否同时输出3d tensor, output_tensor_list=true时该参数不生效
  • NaryDisEmbedding
参数类型默认值说明
embedding_dimuint32embedding维度
carrieslistN-ary 数值特征需要编码的进制列表
multiplierfloat1.0针对float类型的特征,放大multiplier倍再取整后进行进制编码
intra_ary_poolingstringsum同一进制的不同位的数字embedding如何聚合成最终的embedding, 可选:sum, mean
num_replicasuint321每个特征输出多少个embedding表征
output_tensor_listboolfalse是否同时输出embedding列表
output_3d_tensorboolfalse是否同时输出3d tensor, output_tensor_list=true时该参数不生效

备注:该组件依赖自定义Tensorflow OP,可能在某些版本的TF上无法使用

  • TextCNN
参数类型默认值说明
num_filterslist卷积核个数列表
filter_sizeslist卷积核步长列表
activationstringrelu卷积操作的激活函数
pad_sequence_lengthuint32序列补齐或截断的长度
mlpMLPprotobuf message

备注:pad_sequence_length 参数必须要配置,否则模型predict的分数可能不稳定

2.特征交叉组件

  • FM
参数类型默认值说明
use_variantboolfalse是否使用FM的变体:所有二阶交叉项直接输出,而不求和
  • DotInteraction
参数类型默认值说明
self_interactionboolfalse是否运行特征自己与自己交叉
skip_gatherboolfalse一个优化开关,设置为true,可以提高运行速度,但需要占用更多的内存空间
  • Cross
参数类型默认值说明
projection_dimuint32None使用矩阵分解降低计算开销,把大的权重矩阵分解为两个小的矩阵相乘,projection_dim是第一个小矩阵的列数,也是第二个小矩阵的行数
diag_scalefloat0used to increase the diagonal of the kernel W by diag_scale, that is, W + diag_scale * I, where I is an identity matrix
use_biasbooltruewhether to add a bias term for this layer.
kernel_initializerstringtruncated_normalInitializer to use on the kernel matrix
bias_initializerstringzerosInitializer to use on the bias vector
kernel_regularizerstringNoneRegularizer to use on the kernel matrix
bias_regularizerstringNoneRegularizer to use on bias vector
  • Bilinear
参数类型默认值说明
typestringinteraction双线性类型
use_plusbooltrue是否使用plus版本
num_output_unitsuint32输出size
  • FiBiNet
参数类型默认值说明
bilinearBilinearprotobuf message
senetSENetprotobuf message
mlpMLPprotobuf message

3.特征重要度学习组件

  • SENet
参数类型默认值说明
reduction_ratiouint324隐层单元数量缩减倍数
num_squeeze_groupuint322压缩分组数量
use_skip_connectionbooltrue是否使用残差连接
use_output_layer_normbooltrue是否在输出层使用layer norm
  • MaskBlock
参数类型默认值说明
output_sizeuint32输出层单元数
reduction_factorfloat隐层单元数缩减因子
aggregation_sizeuint32隐层单元数
input_layer_normbooltrue输入是否需要做layer norm
projection_dimuint32用两个小矩阵相乘代替原来的输入-隐层权重矩阵,配置小矩阵的维数
  • MaskNet
参数类型默认值说明
mask_blockslistMaskBlock结构列表
use_parallelbooltrue是否使用并行模式
mlpMLP可选顶部mlp
  • PPNet
参数类型默认值说明
mlpMLPmlp 配置
gate_paramsGateNN参数个性化Gate网络的配置
modestringeager配置参数个性化是作用在MLP的每个layer的输入上还是输出上,可选:[eager, lazy]
full_gate_inputbooltrue是否需要添加stop_gradient之后的mlp的输入作为gate网络的输入

其中,GateNN的参数如下:

参数类型默认值说明
output_dimuint32mlp前一层的输出units数Gate网络的输出维度,eager模式下必须要配置为mlp第一层的输入units数
hidden_dimuint32output_dim隐层单元数
dropout_ratefloat0.0隐层dropout rate
activationstrrelu隐层的激活函数
use_bnbooltrue隐层是否使用batch normalization

4. 序列特征编码组件

  • SeqAugment (序列数据增强)
参数类型默认值说明
mask_ratefloat0.6被mask掉的token比率
crop_ratefloat0.2裁剪保留的token比率
reorder_ratefloat0.6shuffle的子序列长度占比
  • DIN
参数类型默认值说明
attention_dnnMLPattention unit mlp
need_target_featurebooltrue是否返回target item embedding
attention_normalizerstringsoftmaxsoftmax or sigmoid
  • BST
参数类型默认值说明
hidden_sizeinttransformer 编码层单元数
num_hidden_layersinttransformer层数
num_attention_headsinttransformer head数
intermediate_sizeinttransformer中间层单元数
hidden_actstringgelu隐藏层激活函数
hidden_dropout_probfloat0.1隐藏层dropout rate
attention_probs_dropout_probfloat0.1attention层dropout rate
max_position_embeddingsint512序列最大长度
use_position_embeddingsbooltrue是否使用位置编码
initializer_rangefloat0.2权重参数初始值的区间范围
output_all_token_embeddingsbooltrue是否输出所有token embedding
target_item_positionstringheadtarget item的插入位置,可选:head, tail, ignore
reserve_target_positionbooltrue是否为target item保留一个位置
  • Attention

Dot-product attention layer, a.k.a. Luong-style attention.

The calculation follows the steps:

  1. Calculate attention scores using query and key with shape (batch_size, Tq, Tv).
  2. Use scores to calculate a softmax distribution with shape (batch_size, Tq, Tv).
  3. Use the softmax distribution to create a linear combination of value with shape (batch_size, Tq, dim).
参数类型默认值说明
use_scaleboolFalseIf True, will create a scalar variable to scale the attention scores.
scale_by_dimboolFaslewhether to scale by dimension
score_modestringdotFunction to use to compute attention scores, one of {"dot", "concat"}. "dot" refers to the dot product between the query and key vectors. "concat" refers to the hyperbolic tangent of the concatenation of the query and key vectors.
dropoutfloat0.0Float between 0 and 1. Fraction of the units to drop for the attention scores.
seedintNoneA Python integer to use as random seed incase of dropout.
return_attention_scoresboolFalseif True, returns the attention scores (after masking and softmax) as an additional output argument.
use_causal_maskboolFalseSet to True for decoder self-attention. Adds a mask such that position i cannot attend to positions j > i. This prevents the flow of information from the future towards the past.
  • inputs: List of the following tensors: - query: Query tensor of shape (batch_size, Tq, dim). - value: Value tensor of shape (batch_size, Tv, dim). - key: Optional key tensor of shape (batch_size, Tv, dim). If not given, will use value for both key and value, which is the most common case.
  • output: - Attention outputs of shape (batch_size, Tq, dim). - (Optional) Attention scores after masking and softmax with shape (batch_size, Tq, Tv).
  • MultiHeadAttention
参数类型默认值说明
num_headsuint32Number of attention heads.
key_dimuint32Size of each attention head for query and key.
value_dimuint32Size of each attention head for value.
dropoutfloat0.0Dropout probability.
use_biasbooltruewhether the dense layers use bias vectors/matrices.
return_attention_scoresboolfalsewhether the output should be (attention_output, attention_scores)
use_causal_maskboolfalsewhether to apply a causal mask to prevent tokens from attending to future tokens (e.g., used in a decoder Transformer).
output_shapeuint32The expected shape of an output tensor, besides the batch and sequence dims. If not specified, projects back to the query feature dim (the query input's last dimension).
kernel_initializerstringInitializer for dense layer kernels.
bias_initializerstringInitializer for dense layer biases.
  • TransformerBlock

Transformer encoder 的其中一个layer。

参数类型默认值说明
hidden_sizeinttransformer 编码层单元数
num_attention_headsinttransformer head数
intermediate_sizeinttransformer中间层单元数
hidden_actstringrelu隐藏层激活函数
hidden_dropout_probfloat0.1隐藏层dropout rate
attention_probs_dropout_probfloat0.0attention层的dropout rate
  • TransformerEncoder
参数类型默认值说明
vocab_sizeuint32词汇表大小
hidden_sizeuint32transformer 编码层单元数
num_hidden_layersuint32transformer层数
num_attention_headsuint32transformer head数
intermediate_sizeuint32transformer中间层单元数
hidden_actstringrelu隐藏层激活函数
hidden_dropout_probfloat0.1隐藏层dropout rate
attention_probs_dropout_probfloat0.0attention层的dropout rate
max_position_embeddingsuint32512序列最大长度
output_all_token_embeddingsbooltrue是否输出所有token embedding
  • TextEncoder

BERT模型结构

参数类型默认值说明
transformerTransformerEncodertransformer 子组件的配置
separatorstring' '文本分隔符
vocab_filestring词汇表文件路径,不设置时使用hash获得token id
default_token_idint320Out of vocabulary 的token的默认id

5. 多任务学习组件

  • MMoE
参数类型默认值说明
num_taskuint32任务数
num_expertuint320expert数量
expert_mlpMLP可选expert的mlp参数
  • AITMTower
参数类型默认值说明
project_dimuint32可选attention Query, Key, Value的维度
stop_gradientboolTrue是否需要停用对依赖的输入的梯度
transfer_mlpMLPtransfer的mlp参数

6. 计算辅助损失函数的组件

  • AuxiliaryLoss
参数类型默认值说明
loss_typestring损失函数类型,包括:l2_loss, nce_loss, info_nce
loss_weightfloat1.0损失函数权重
temperaturefloat0.1info_nce & nec loss 的参数
其他根据loss_type决定