
金融科技科学计算【免费下载链接】tf-quant-financeHigh-performance TensorFlow library for quantitative finance.项目地址https://gitcode.com/gh_mirrors/tf/tf-quant-finance点击查看免费下载tf_quant_finance.utils是 tf-quant-finance 中承上启下的基础工具模块它提供了一组张量形状shape处理函数、一个让普通 Python 类能够作为tf.function输入/输出与tf.while_loop循环变量使用的dataclass装饰器以及一个嵌套字典的深度优先遍历器。读懂这 6 个公开函数get_shape、common_shape、broadcast_tensors、broadcast_common_batch_shape、dataclass、iterate_nested就掌握了库内部做批量定价、校准和数值算法时的两条通用约定——批量形状 事件形状的张量布局与可微控制流中的结构化数据传递下文逐函数给出用法、源码实现证据与项目内的真实调用场景。模块入口六个公开函数与三个内部子库tf_quant_finance/utils/__init__.py用remove_undocumented将公开 API 严格限定为 6 个符号即 API 文档 api_docs/tf_quant_finance/utils.md 中列出的全部函数公开函数定义位置职责broadcast_common_batch_shape(*args, event_ranksNone, nameNone)tf_quant_finance/utils/shape_utils.py将各张量的 batch 形状广播到公共 batch 形状事件event维度保持不变broadcast_tensors(*args, nameNone)tf_quant_finance/utils/shape_utils.py将多个张量整体广播到公共形状common_shape(*args, nameNone)tf_quant_finance/utils/shape_utils.py求一序列张量可广播到的最小公共形状dataclass(cls)tf_quant_finance/utils/dataclass.py把带类型注解的类改造为tf.function兼容的数据类get_shape(x, nameNone)tf_quant_finance/utils/shape_utils.py静态形状完整时返回静态形状否则返回动态tf.shapeiterate_nested(nd, previous_keysNone)tf_quant_finance/utils/tf_functions.py按深度优先顺序产出嵌套字典每个叶子节点的(键路径, 值)从源码结构看__init__.py仅做再导出真正的实现分布在三个子库中shape_utils4 个形状函数、dataclass装饰器、tf_functions嵌套遍历。构建文件 tf_quant_finance/utils/BUILD 也把这三组py_library分别声明为shape_utils、dataclass、tf_functions并以//tf_quant_finance:__subpackages__的可见性供包内所有模块依赖——这解释了为什么models、math、rates等模块都能直接使用tff.utils。形状工具形状查询与两级广播get_shape静态优先、动态兜底get_shape(x, nameNone)的完整实现只有几行shape_utils.py#L30-L60def get_shape(x, nameNone): name get_shape if name is None else name with tf.name_scope(name): x tf.convert_to_tensor(x) is_fully_defined x.shape.is_fully_defined() if is_fully_defined: return x.shape # 静态返回 TensorShape return tf.shape(x) # 动态返回 1-D int64 Tensor其语义是能静态拿就静态拿拿不到就退回图内动态形状。当x的形状在 trace 期完全已知例如tf.zeros([5, 2])返回TensorShape([5, 2])当x带有None维度典型如tf.function的input_signature声明了tf.TensorSpec([1, None], ...)x.shape.is_fully_defined()为False此时返回tf.shape(x)张量保证后续按元素运算如切片shape[:-d]仍然合法。测试文件 tf_quant_finance/utils/shape_utils_test.py 中的test_prefer_static_shape与test_prefer_static_shape_dynamic分别覆盖了这两种路径前者断言静态形状[2, 1]后者用input_signature[tf.TensorSpec(shape, ...)]注入部分未知/完全未知的形状并验证动态结果。common_shape 与 broadcast_tensors整体广播common_shape(*args, nameNone)返回所有输入张量可广播到的最小 rank 形状shape_utils.py#L63-L114。API 文档给出的示例是import tensorflow as tf import tf_quant_finance as tff args [tf.ones([1, 2], dtypetf.float64), tf.constant([[True], [False]])] tff.utils.common_shape(*args) # Expected: [2, 2]从源码结构看它内部走的是与get_shape相同的双路径先检查所有输入是否形状完全已知若已知则用tf.broadcast_static_shape逐个折叠任何一步不可广播就抛出ValueError(Shapes of ... are incompatible)否则用tf.broadcast_dynamic_shape在图内逐步求公共形状。broadcast_tensors(*args, nameNone)则是在common_shape之上的一步封装——先求公共形状再对每个参数调用tf.broadcast_to返回一个保持各输入dtype的元组def broadcast_tensors(*args, nameNone): name broadcast_tensors if name is None else name with tf.name_scope(name): output_shape common_shape(*args) return tuple(tf.broadcast_to(arg, output_shape) for arg in args)对应的行为由 shape_utils_test.py 中的test_broadcast_tensors_shapes验证[1, 2]的 float64、[2, 1]的 bool、[1]的 float32 三个张量经广播后均为[2, 2]且各自dtype保持不变test_broadcast_tensors_shapes_incompatible则确认[1, 2]与[3, 3]组合会抛出ValueError。broadcast_common_batch_shape金融定价的默认张量布局这是utils模块中最具领域特色的函数。金融库中的张量几乎都遵循batch 维度在前、事件维度在后的约定例如GeometricBrownianMotion的样本形状是[num_paths, path_length]利率曲线的折线形状是[num_curves, num_points]。broadcast_common_batch_shape正是在这一约定下做对齐def broadcast_common_batch_shape(*args, event_ranksNone, nameNone): ... if event_ranks is None: event_ranks [1] * len(args) if len(event_ranks) ! len(args): raise ValueError(...) dummies [tf.zeros(get_shape(arg)[:-d]) for arg, d in zip(args, event_ranks)] common_batch_shape common_shape(*dummies) return tuple(tf.broadcast_to(x, tf.concat( [common_batch_shape, get_shape(x)[-d:]], axis0)) for x, d in zip(args, event_ranks))参数与语义与 API 文档 一致*args一序列形状兼容、dtype任意的张量event_ranks与args等长的整数序列指定每个张量的event_shape秩默认None表示除最后一维外全部是 batch 维即每个张量event_rank 1长度不一致时抛ValueErrornamename_scope名称默认broadcast_common_batch_shape返回值元组每个张量被广播为common_batch_shape event_shape_idtype与输入一致异常ValueErroraevent_ranks长度与args不一致bbatch 形状不可广播。API 文档中的示例 1两个张量形状分别为[2, 3]和[2]默认规则下 batch 形状是[2]和[]公共 batch 形状为[2]广播结果是[2, 3]与[2, 1]# Two Tensors of shapes [2, 3] and [2]. The batch shape of the 1st Tensor is # [2] and for the second is []. The common batch shape is [2] args [tf.ones([2, 3], dtypetf.float64), tf.constant([True, False])] tff.utils.broadcast_common_batch_shape(*args) # Expected: (array([[1., 1., 1.], [1., 1., 1.]]), # array([[True, True], [False, False]])示例 2 展示显式指定event_ranks的用法把第二个标量张量视作纯 batch、第一个张量的最后一维视作事件维度等场景。实现上有两个值得注意的细节。其一公共 batch 形状是通过构造tf.zeros(get_shape(arg)[:-d])的哑张量只含 batch 维再交给common_shape求得的——由于get_shape的静态/动态自适应这条路径在tf.function图模式下也能成立。其二最终广播目标用tf.concat([common_batch_shape, get_shape(x)[-d:], axis0)拼接而成batch 部分与事件部分各自独立处理。测试用例印证了这一点def test_broadcast_common_batch_shape(self): x tf.zeros([3, 4]) y tf.zeros([2, 1, 3, 10]) z tf.zeros([]) x, y, z tff.utils.broadcast_common_batch_shape(x, y, z) # x - [2, 1, 3, 4]y 保持 [2, 1, 3, 10]z - [2, 1, 3]以及动态形状场景test_broadcast_common_batch_shape_dynamic在input_signature[tf.TensorSpec([2, 3, None]), tf.TensorSpec([None, 5])]的tf.function内[2, 3, 10]与[1, 5]被对齐为[2, 3, 10]与[2, 3, 5]。event_ranks[1, 2, 0]的非默认场景同样有测试覆盖test_broadcast_common_batch_shape_different_ranks其中event_rank0的标量张量会完整广播到公共 batch 形状。dataclass 装饰器让类进入 tf.function 与 tf.while_loop 的世界原生 Python dataclass 不能直接作为tf.function的输入/输出也不能充当tf.while_loop的循环变量。tff.utils.dataclasstf_quant_finance/utils/dataclass.py解决的就是这个问题def dataclass(cls): # Wrap the class with attr.s to ensure that the class can be an input/output # to a tf.function cls attr.s(cls, auto_attribsTrue) # Define __iter__ and __len__ method to ensure tf.while_loop compatibility def __iter__(self): for item in self.__attrs_attrs__: name item.name yield getattr(self, name) def __len__(self): return len(self.__attrs_attrs__) cls.__len__ __len__ cls.__iter__ __iter__ return cls从源码结构看机制分两层attr.s(cls, auto_attribsTrue)借助 attrs 为带类型注解的类生成__init__、__eq__等。attrs 生成的对象实现了__iter__/__len__协议这正是 TensorFlow 将结构化对象分解flattening为CompositeTensor所要求的接口——tf.function据此知道如何把类实例拆成张量列表、又如何还原。手写__iter__/__len__兜底按__attrs_attrs__的声明顺序迭代字段值并给出字段计数使类实例可直接放入tf.while_loop的loop_vars元组中。装饰器文档明确要求被装饰类只写类型注解、不要自定义__init__字段按定义顺序排序无类型注解的字段被忽略attr.s不会丢弃类 docstring测试test_docstring_preservation专门验证了Coords.__doc__在装饰后仍然等于A coordinate grid.。API 文档给出的标准示例同时也是 dataclass_test.py 中test_docstring_example的用例断言结果x 10、y 20import tensorflow as tf import tf_quant_finance as tff tff.utils.dataclass class Coords: x: tf.Tensor y: tf.Tensor tf.function def fn(start_coords: Coords) - Coords: def cond(it, _): return it 10 def body(it, coords): return it 1, Coords(xcoords.x 1, ycoords.y 2) return tf.while_loop(cond, body, loop_vars(0, start_coords))[1] start_coords Coords(xtf.constant(0), ytf.constant(0)) fn(start_coords) # Expected Coords(x10, y20)关键在于tf.while_loop的 body 返回新的Coords实例作为循环变量装饰器保证该实例在符号执行与图模式下都能被正确展开/重建。项目内的真实用法这个装饰器不是摆设从源码结构看它是全库结构化结果对象的统一载体根搜索tf_quant_finance/math/root_search/brent.py#L34-L86 中BrentResultsestimated_root、objective_at_estimated_root、num_iterations、converged四个字段是brentq的公开返回类型内部的_BrentSearchConstants、_BrentSearchState、_BrentSearchParams也全部用它定义——其中_BrentSearchState正是迭代过程中被反复更新的循环状态利率产品tf_quant_finance/experimental/instruments/rates_common.py 中的InterestRateMarket引用曲线、贴现曲线、volatility cube 等字段、FixedCouponSpecs、FloatCouponSpecs、CMSCouponSpecs均标注tff_utils.dataclass让利率曲线拟合与校准的tf.function能够整体传递市场与票息规格数值与随机数tf_quant_finance/math/optimizer/conjugate_gradient.py的收敛参数/结果、tf_quant_finance/math/random_ops/halton/halton_impl.py的 Halton 采样器参数、tf_quant_finance/models/heston/approximations/calibration.py的 Heston 校准结果等都是同一模式。iterate_nested嵌套字典与 dataclass 的深度优先遍历iterate_nested(nd, previous_keysNone)定义在 tf_quant_finance/utils/tf_functions.py#L35-L77按深度优先顺序产出每个叶子节点的(键路径列表, 值)二元组文档明确指出同级键的遍历顺序不作保证与字典键相同。nested_dict {a: 1, b: [2, 3, 4], c: {d: 8}} for k, v in tff.utils.iterate_nested(nested_dict): print(_.join(k), v) # Prints out: # a 1 # b [2, 3, 4] # c_d 8实现要点源码 tf_functions.py#L75-L77def _is_nested(x): Returns whether a value is nested. return isinstance(x, dict) or dataclasses.is_dataclass(x)即只有dict与标准库dataclasses的 dataclass 会被继续展开其余一切标量、Tensor、list等一律视为叶子遇到 dataclass 时先用dataclasses.asdict(v)转成字典再递归。previous_keys参数用于拼接外层键路径递归中每次keys previous_keys [k]。测试文件 tf_quant_finance/utils/tf_functions_test.py 覆盖了四条路径非嵌套字典、空字典迭代器为空、列表值视为叶子、嵌套字典以及一个混合了标准库 dataclass 的复合场景dataclasses.dataclass class TestDataclass: simple_field: int dict_field: Dict[str, int] d { a: {b: {c: 5.1}}, data: TestDataclass(simple_field42, dict_field{a: 6, z: 10}) } # 期望键路径: a_b_c, data_simple_field, data_dict_field_a, data_dict_field_z可见它对tff.utils.dataclass与标准库 dataclass 的对象都天然兼容适合在调试或日志场景中把任意嵌套结果对象摊平成扁平键 - 值的映射。项目内调用链谁在用这些工具从源码搜索看形状工具是库内模块间对齐张量布局的标准动作tff_utils.broadcast_common_batch_shape直接出现在这些位置插值tf_quant_finance/math/interpolation/cubic/cubic_interpolation.py#L154 中x_data, y_data tff_utils.broadcast_common_batch_shape(x_data, y_data)先把插值节点的坐标与函数值对齐到公共 batch 形状再求样条系数线性插值tf_quant_finance/math/interpolation/linear/linear_interpolation.py同理PDE 求解器tf_quant_finance/math/pde/fd_solvers.py 与tf_quant_finance/math/pde/steppers/multidim_parabolic_equation_stepper.py用它对齐网格、边界条件与解张量形状/遍历工具同样被广泛引用tff.utils.get_shape出现在tf_quant_finance/models/heston/heston_model.py、tf_quant_finance/rates/swap_curve_bootstrap.py等数十个文件中前文 33 个匹配文件列表可证tff.utils.dataclass则贯穿models、rates、math三大模块。使用建议基于上述源码事实当你为 tf-quant-finance 编写自定义定价/校准逻辑时凡是需要把不同 rank 的输入标量 strike、批量标的价格、[batch, n]的折线点喂进同一个可微函数应优先用broadcast_common_batch_shape对齐 batch 维而非手动tf.broadcast_to整张张量需要把多字段结果根、迭代次数、收敛标志带回tf.function边界时用tff.utils.dataclass定义结果类。文件与文档速查内容路径模块入口再导出 6 个符号tf_quant_finance/utils/init.py形状工具实现tf_quant_finance/utils/shape_utils.py形状工具测试tf_quant_finance/utils/shape_utils_test.pydataclass 装饰器tf_quant_finance/utils/dataclass.pydataclass 测试tf_quant_finance/utils/dataclass_test.py嵌套遍历实现tf_quant_finance/utils/tf_functions.py嵌套遍历测试tf_quant_finance/utils/tf_functions_test.py构建规则tf_quant_finance/utils/BUILD各函数 API 文档utils.md、get_shape.md、common_shape.md、broadcast_tensors.md、broadcast_common_batch_shape.md、dataclass.md、iterate_nested.md以上函数均以Stable路径发布见各 API 文档页头部 meta 的path: Stable行为以当前仓库源码与测试为准dataclass装饰器文档亦已声明不保证对任意类都有效使用时应限定于带类型注解的简单类定义。赞分享金融科技科学计算【免费下载链接】tf-quant-financeHigh-performance TensorFlow library for quantitative finance.项目地址https://gitcode.com/gh_mirrors/tf/tf-quant-finance点击查看免费下载相关推荐什么是无审查模型HauhauCS Qwen3.8-27B Uncensored 与 Aggressive 变体科普入门指南什么是无审查模型HauhauCS Qwen3.8 27B Uncensored 与 Aggressive 变体科普入门指南 无审查模型Uncensored微信聊天记录导出零门槛免费开源工具 WeChatMsg 完整备份指南微信聊天记录导出零门槛免费开源工具 WeChatMsg 完整备份指南 如果你正在搜微信聊天记录导出聊天记录备份开源工具 WeChatMsg留痕值tf-quant-finance 中 QMC 采样的形状解析基石tf_quant_finance.math.qmc.utils.get_shape 深度解析tf quant finance 中 QMC 采样的形状解析基石tf_quant_finance.math.qmc.utils.get_shape 深度解析金融科技科学计算上一篇如何使用TRIBE v2预测大脑fMRI响应从视频音频到文本的完整指南下一篇Qwen3.6-35B-A3B-TQ3_4S多模态能力实战图像文本处理完全指南 创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考