Grok-1 源码中语法 @dataclass 变量名称:变量类型
flyfish
model.py
@dataclass
class Transformer(hk.Module):"""A transformer stack."""num_q_heads: intnum_kv_heads: intkey_size: intwidening_factor: floatinit_scale: floatmesh: Anyattn_output_multiplier: floatshard_activations: boolnum_layers: int# MoEnum_experts: intnum_selected_experts: intname: Optional[str] = None# Used for activation shardingdata_axis: Union[str, Tuple[str, ...]] = "data"model_axis: Union[str, Tuple[str, ...]] = "model"
模拟代码
使用dataclasses ,变量名称:变量类型 这种方式
from dataclasses import dataclass@dataclass
class employee:name: stremp_id: strage: int# initialization the object
emp1 = employee("xiaoming", "1", 21)
emp2 = employee("xiaohong", "2", 28)
emp3 = employee("xiaoming", "1", 21)print("employee object are :")
print(emp1)
print(emp2)
print(emp3)# printing new line
print()# 检查两个对象是否相等
print("Data in emp1 and emp2 are same? ", emp1 == emp2)
print("Data in emp1 and emp3 are same? ", emp1 == emp3)
如果不使用dataclasses
代码如下
class employee:# init method or constructordef __init__(self, name, emp_id, age):# Instance Variableself.name = nameself.emp_id = emp_idself.age = age# magic function to return class objectdef __repr__(self):return ("employee (name={}, emp_id={}, age={} )".format(self.name, self.emp_id, self.age))# magic function to return booleandef __eq__(self, check):return ((self.name, self.emp_id, self.age) ==((check.name, check.emp_id, check.age)))
使用了使用dataclasses 之后自动生成了
__init__, __repr__, __eq__
这些函数
即 dataclasses 数据类模块提供了一个装饰器和一些函数,用于向类中自动添加生成的 special method 例如 __init__() 和 __repr__()。
参考
https://docs.python.org/zh-cn/3/library/dataclasses.html#module-dataclasses