spikingjelly.activation_based.ann2snn package#
Overview#
spikingjelly.activation_based.ann2snn is organized around two conversion
paths:
FX graph conversion for recipes that trace and rewrite a
torch.fx.GraphModule.Direct
nn.Moduletree conversion for recipes that replace modules without FX tracing.
Most users start by choosing a converter, then a conversion recipe. Lower-level operators, rules, factories, threshold utilities, and helper functions are documented after the public conversion APIs.
Converters#
ANN2SNN exposes two explicit conversion executors:
FXConverterconverts through atorch.fx.GraphModule. The historical public namesConverterandConversionRecipeare compatibility aliases forFXConverterandFXConversionRecipe.ModuleConverterconverts a plainnn.Moduletree without FX tracing. It accepts onlyModuleConversionRecipeinstances. This is the path used by module-tree conversions such as SpikeZIP QANN-to-SNN.
There is no automatic cross-path dispatch. Passing a module-tree recipe to
Converter / FXConverter or an FX recipe to ModuleConverter raises a
TypeError.
- class spikingjelly.activation_based.ann2snn.converter.FXConverter(recipe, device=None)[源代码]#
基类:
object
中文
FXConverter是 FX graph 路径的 ANN2SNN 转换框架执行器。 兼容名Converter等价于FXConverter。它只负责 device 解析、 FX tracing 和固定转换模板调度;具体算法参数与图变换由recipe定义。- 参数:
recipe (str or FXConversionRecipe) -- 转换 recipe。传入
FXConversionRecipe实例(或兼容名ConversionRecipe),或稳定的内置 recipe 字符串。 目前字符串别名仅支持"transformer_td_equivalent"。 Rate-coding、STA Transformer 需要显式传入带参数的 recipe 对象。 SpikeZIP QANN 等 module-tree recipe 使用ModuleConverter。device (device or str or None) -- 转换目标 device。若为
None,从模型参数推断;无参数 模型使用 CPU。
English
FXConverteris the FX graph ANN2SNN conversion framework executor. The compatibility nameConverteris equivalent toFXConverter. It only owns device resolution, FX tracing and fixed template orchestration; algorithm parameters and graph transforms are defined byrecipe.- 参数:
recipe (str or FXConversionRecipe) -- Conversion recipe. Pass a
FXConversionRecipeinstance (or the compatibility nameConversionRecipe), or a stable built-in recipe string. Currently, the only supported string alias is"transformer_td_equivalent". Rate-coding and STA Transformer conversion must pass explicit recipe objects. Module-tree recipes such as SpikeZIP QANN useModuleConverterinstead.device (device or str or None) -- Target conversion device. If
None, infer it from the model parameters; parameterless models use CPU.
- convert(ann)[源代码]#
-
中文
按当前
recipe执行完整 FX ANN2SNN 转换模板。FXConverter只负责 device 解析、FX tracing 和步骤调度;recipe 定义每一步的算法行为。validate在每次转换开始时调用一次,before_trace在 FX tracing 前运行。
English
Execute the full FX ANN2SNN conversion template with the current
recipe.FXConverteronly owns device resolution, FX tracing and step orchestration; the recipe defines the algorithm behavior of each step.validateis called once at the beginning of each conversion, andbefore_traceruns before FX tracing.
- class spikingjelly.activation_based.ann2snn.converter.ModuleConverter(recipe, device=None)[源代码]#
基类:
object
中文
ModuleConverter是直接nn.Moduletree 路径的 ANN2SNN 转换 执行器。它不执行 FX tracing,也不是Converter的自动分发分支。 固定生命周期为 device 解析、保存原始 training 状态、在torch.no_grad()中调用recipe.validate(self)与recipe.convert_module(self, ann),再把转换产物移动到目标 device。- 参数:
recipe (ModuleConversionRecipe) -- module-tree 转换 recipe。
device (device or str or None) -- 转换目标 device。若为
None,从模型参数推断;无参数 模型使用 CPU。
- 抛出:
TypeError --
recipe不是ModuleConversionRecipe,或传入了 FX recipe。
English
ModuleConverteris the ANN2SNN executor for directnn.Moduletree conversion. It does not run FX tracing and is not an automatic dispatch branch ofConverter. Its fixed lifecycle resolves the target device, saves original training states, callsrecipe.validate(self)andrecipe.convert_module(self, ann)undertorch.no_grad(), and moves the converted model to the target device.- 参数:
recipe (ModuleConversionRecipe) -- Module-tree conversion recipe.
device (device or str or None) -- Target conversion device. If
None, infer it from the model parameters; parameterless models use CPU.
- 抛出:
TypeError -- If
recipeis not aModuleConversionRecipeor an FX recipe is passed.
- spikingjelly.activation_based.ann2snn.converter.Converter#
FXConverter的别名
Conversion Recipes#
Recipes describe the conversion algorithm. The built-in recipes fall into three groups:
CNN and rate-coding conversion:
RateCodingRecipeandLocalThresholdBalancingRecipe.Transformer FX conversion:
TransformerTDEquivalentRecipeandSTATransformerRecipe.Module-tree QANN-to-SNN conversion:
SpikeZIPTFQANNRecipe.
FX recipes subclass FXConversionRecipe and are executed by
FXConverter / Converter. Module-tree recipes subclass
ModuleConversionRecipe and are executed by ModuleConverter. The
historical name ConversionRecipe is a compatibility alias for
FXConversionRecipe.
- spikingjelly.activation_based.ann2snn.recipes.ConversionRecipe#
- class spikingjelly.activation_based.ann2snn.recipes.FXConversionRecipe[源代码]#
基类:
object
中文
FX graph 路径的 ANN2SNN 转换 recipe 基类。兼容名
ConversionRecipe等价于FXConversionRecipe。Recipe 是策略对象, 只定义FXConverter在固定 FX 转换模板中每一步应该做什么;Recipe 本身不提供convert、run或__call__执行入口。子类可以覆盖
validate()、before_trace()、after_trace()、insert_observers()、calibrate()、replace()和finalize()。before_trace接收原始 ANN; 图步骤接收同一个FXConverter和当前fx.GraphModule。步骤可以 原地修改对象,也必须返回下一步要继续使用的对象。
English
Base class for FX graph ANN2SNN conversion recipes. The compatibility name
ConversionRecipeis equivalent toFXConversionRecipe. A recipe is a strategy object that defines what each step in the fixedFXConverterpipeline should do; the recipe itself does not expose aconvert,runor__call__execution entrypoint.Subclasses can override
validate(),before_trace(),after_trace(),insert_observers(),calibrate(),replace()andfinalize().before_tracereceives the original ANN. Graph steps receive the sameFXConverterand the currentfx.GraphModule. They may mutate the object in-place, and must return the object that the next step should use.- after_trace(converter, fx_model)[源代码]#
-
中文
FX tracing 和 device 转移之后运行的步骤。默认直接返回
fx_model。子类可在此执行 Conv-BN 融合或做其他 tracing 后预处理; 影响 FX tracing 的训练/推理模式应在before_trace()中设置。- 参数:
converter (FXConverter) -- 执行当前 recipe 的转换器。
fx_model (GraphModule) -- 已 trace 并移动到目标 device 的
GraphModule。
- 返回:
后续步骤使用的
GraphModule。- 返回类型:
English
Step executed after FX tracing and device transfer. The default implementation returns
fx_modelunchanged. Subclasses can fuse Conv-BN modules or perform other post-tracing preprocessing here; training/eval mode that affects FX tracing should be set inbefore_trace().- 参数:
converter (FXConverter) -- Converter that executes this recipe.
fx_model (GraphModule) --
GraphModuleafter tracing and device transfer.
- 返回:
GraphModuleused by later steps.- 返回类型:
- before_trace(converter, ann)[源代码]#
-
中文
FX tracing 之前运行的步骤。默认直接返回
ann。子类可在此设置 训练/推理模式,或执行必须发生在 tracing 前的模型准备。- 参数:
converter (FXConverter) -- 执行当前 recipe 的转换器。
ann (Module) -- 待 trace 的原始 ANN。
- 返回:
后续 tracing 使用的 ANN。
- 返回类型:
English
Step executed before FX tracing. The default implementation returns
annunchanged. Subclasses can set training/eval mode or perform model preparation that must happen before tracing.- 参数:
converter (FXConverter) -- Converter that executes this recipe.
ann (Module) -- Original ANN to be traced.
- 返回:
ANN used by FX tracing.
- 返回类型:
- calibrate(converter, fx_model)[源代码]#
-
中文
运行校准数据的步骤。默认不运行 dataloader 并直接返回
fx_model。 需要校准的子类应自行决定是否使用torch.no_grad()、如何解析 batch, 以及如何更新已插入的 observer / hook。- 参数:
converter (FXConverter) -- 执行当前 recipe 的转换器。
fx_model (GraphModule) -- 当前
GraphModule。
- 返回:
后续步骤使用的
GraphModule。- 返回类型:
English
Run calibration data. The default implementation does not iterate over the dataloader and returns
fx_modelunchanged. Subclasses that need calibration should decide whether to usetorch.no_grad(), how to parse batches, and how to update inserted observers or hooks.- 参数:
converter (FXConverter) -- Converter that executes this recipe.
fx_model (GraphModule) -- Current
GraphModule.
- 返回:
GraphModuleused by later steps.- 返回类型:
- finalize(converter, fx_model)[源代码]#
-
中文
转换结束前的收尾步骤。默认直接返回
fx_model。子类可在此做最终 graph lint、清理临时模块、恢复状态,或包装最终返回的torch.nn.Module。- 参数:
converter (FXConverter) -- 执行当前 recipe 的转换器。
fx_model (GraphModule) -- 当前
GraphModule。
- 返回:
最终转换结果。
- 返回类型:
English
Final step before returning the converted model. The default implementation returns
fx_modelunchanged. Subclasses can perform final graph linting, clean temporary modules, restore state, or wrap the final returnedtorch.nn.Module.- 参数:
converter (FXConverter) -- Converter that executes this recipe.
fx_model (GraphModule) -- Current
GraphModule.
- 返回:
Final converted model.
- 返回类型:
- insert_observers(converter, fx_model)[源代码]#
-
中文
插入校准 observer / hook 的步骤。默认不插入任何模块并直接返回
fx_model。需要校准数据的 recipe 可在此修改 FX 图。- 参数:
converter (FXConverter) -- 执行当前 recipe 的转换器。
fx_model (GraphModule) -- 当前
GraphModule。
- 返回:
后续步骤使用的
GraphModule。- 返回类型:
English
Insert calibration observers or hooks. The default implementation inserts nothing and returns
fx_modelunchanged. Recipes that need calibration data can mutate the FX graph here.- 参数:
converter (FXConverter) -- Converter that executes this recipe.
fx_model (GraphModule) -- Current
GraphModule.
- 返回:
GraphModuleused by later steps.- 返回类型:
- replace(converter, fx_model)[源代码]#
-
中文
执行核心替换的步骤,例如将 activation 替换为 spiking neuron,或将 ANN module 替换为 TD operator。默认直接返回
fx_model。- 参数:
converter (FXConverter) -- 执行当前 recipe 的转换器。
fx_model (GraphModule) -- 当前
GraphModule。
- 返回:
替换后的
GraphModule。- 返回类型:
English
Perform the core replacement step, such as replacing activations with spiking neurons or replacing ANN modules with TD operators. The default implementation returns
fx_modelunchanged.- 参数:
converter (FXConverter) -- Converter that executes this recipe.
fx_model (GraphModule) -- Current
GraphModule.
- 返回:
Replaced
GraphModule.- 返回类型:
- validate(converter)[源代码]#
-
中文
校验当前 recipe 的前置条件。默认实现不做任何检查。该方法由
FXConverter/Converter在每次转换开始时调用一次,子类不应 在这里执行图转换。- 参数:
converter (FXConverter) -- 执行当前 recipe 的转换器。
- 返回类型:
None
English
Validate this recipe's prerequisites. The default implementation checks nothing.
FXConverter/Convertercalls this method once at the beginning of each conversion; subclasses should not perform graph conversion here.- 参数:
converter (FXConverter) -- Converter that executes this recipe.
- 返回类型:
None
- class spikingjelly.activation_based.ann2snn.recipes.ModuleConversionRecipe[源代码]#
基类:
object
中文
直接
nn.Moduletree 转换 recipe 基类。该路径不执行 FX tracing, 只由ModuleConverter调用validate()和convert_module()。适用于 SpikeZIP 这类 需要按 module tree 替换子模块、但不改写 FX graph 的转换。该基类没有before_trace、after_trace、insert_observers、calibrate、replace或finalize生命周期。
English
Base class for direct
nn.Moduletree conversion recipes. This path does not run FX tracing.ModuleConverteronly callsvalidate()andconvert_module(). It is intended for conversions such as SpikeZIP that replace submodules in a module tree without rewriting an FX graph. This base class has nobefore_trace,after_trace,insert_observers,calibrate,replaceorfinalizelifecycle.- convert_module(converter, ann)[源代码]#
-
中文
执行直接 module-tree 转换。默认直接返回
ann。实现必须返回torch.nn.Module实例。- 参数:
converter (ModuleConverter) -- 执行当前 recipe 的 module converter。
ann (Module) -- 待转换的原始 ANN 或 QANN。
- 返回:
转换后的模型。
- 返回类型:
English
Execute direct module-tree conversion. The default implementation returns
annunchanged. Implementations must return atorch.nn.Moduleinstance.- 参数:
converter (ModuleConverter) -- Module converter that executes this recipe.
ann (Module) -- Original ANN or QANN to convert.
- 返回:
Converted model.
- 返回类型:
- validate(converter)[源代码]#
-
中文
校验 module-tree recipe 的前置条件。默认实现不做任何检查。
- 参数:
converter (ModuleConverter) -- 执行当前 recipe 的 module converter。
- 返回类型:
None
English
Validate prerequisites for a module-tree recipe. The default implementation checks nothing.
- 参数:
converter (ModuleConverter) -- Module converter that executes this recipe.
- 返回类型:
None
- class spikingjelly.activation_based.ann2snn.recipes.LocalThresholdBalancingRecipe(dataloader, time_steps=64, mode='99.9%', channel_dim=1, threshold_candidates=(0.5, 0.75, 1.0, 1.25, 1.5), fuse_flag=True, eps=1e-06)[源代码]#
-
中文
构造 training-free local-threshold-balancing ANN2SNN 转换 recipe。该 recipe 只使用校准数据在 SNN 侧为 ReLU 输出选择 channel-wise 阈值,不训练 或修改输入 ANN 参数。
参考文献:Bu T, Li M, Yu Z. Inference-Scale Complexity in ANN-SNN Conversion for High-Performance and Low-Power Applications. arXiv:2409.03368, 2024. Accepted by CVPR 2025.
- 参数:
English
Construct a training-free local-threshold-balancing ANN2SNN conversion recipe. It uses calibration data only to choose channel-wise thresholds on the SNN side for ReLU outputs, without training or mutating the input ANN parameters.
Reference: Bu T, Li M, Yu Z. Inference-Scale Complexity in ANN-SNN Conversion for High-Performance and Low-Power Applications. arXiv:2409.03368, 2024. Accepted by CVPR 2025.
- 参数:
dataloader (Iterable) -- Calibration dataloader.
time_steps (int) -- SNN simulation steps, retained as recipe configuration metadata.
mode (str or float) -- Retained for configuration validation in the style of RateCodingRecipe.
channel_dim (int) -- Channel dimension of ReLU outputs.
threshold_candidates (Tuple[float, ...]) -- Retained for compatibility with earlier experimental APIs. The implementation follows the original LTB per-batch threshold-balancing update.
fuse_flag (bool) -- Whether to fuse Conv-BN modules.
eps (float) -- Numeric lower bound.
- after_trace(converter, fx_model)[源代码]#
- 参数:
converter (Converter)
fx_model (fx.GraphModule)
- 返回类型:
fx.GraphModule
- calibrate(converter, fx_model)[源代码]#
- 参数:
converter (Converter)
fx_model (fx.GraphModule)
- 返回类型:
fx.GraphModule
- insert_observers(converter, fx_model)[源代码]#
- 参数:
converter (Converter)
fx_model (fx.GraphModule)
- 返回类型:
fx.GraphModule
- class spikingjelly.activation_based.ann2snn.recipes.RateCodingRecipe(dataloader, mode='Max', momentum=0.1, fuse_flag=True, channel_wise=False, channel_dim=1, pre_spike_maxpool=False, half_threshold=False, eps=1e-06, rules=None, neuron_factory=None, threshold_optimizer=None)[源代码]#
-
中文
构造传统 rate-coding ReLU→IFNode 转换 recipe。该 recipe 拥有 rate-coding 算法参数,并执行 Conv-BN 融合、VoltageHook 校准和 neuron replacement。
- 参数:
dataloader (Iterable) -- 校准数据加载器。每个 batch 可为单输入 tensor、
(input, target)风格的 tuple/list,或包含"input"/"image"/"images"等输入键的 dict。默认 recipe 只支持 单输入校准;多输入模型应通过自定义 recipe 扩展。mode (str or float) -- VoltageHook 统计模式,支持
"Max"、百分位字符串和0 < mode <= 1的浮点缩放。momentum (float) -- VoltageHook 动量。
fuse_flag (bool) -- 是否执行 Conv-BN 融合。
channel_wise (bool) -- 是否按通道统计 robust 激活尺度并使用 channel-wise threshold。默认
False以保持原有 layer-wise 行为。channel_dim (int) --
channel_wise=True时的通道维。pre_spike_maxpool (bool) --
channel_wise=True时,若匹配到ReLU -> MaxPool2d,是否把 MaxPool2d 放到脉冲神经元之前。half_threshold (bool) --
channel_wise=True时,是否使用半阈值膜电位初始化。eps (float) --
channel_wise=True时的阈值数值下界。rules (Optional[List[ActivationRule]]) -- 激活转换规则。默认
[ReLURule()]。neuron_factory (Optional[NeuronFactory]) -- 脉冲神经元工厂。
threshold_optimizer (Optional[ThresholdOptimizer]) -- 阈值优化器。
English
Construct a traditional rate-coding ReLU-to-IFNode conversion recipe. This recipe owns rate-coding algorithm parameters and performs Conv-BN fusion, VoltageHook calibration and neuron replacement.
- 参数:
dataloader (Iterable) -- Calibration dataloader. Each batch can be a single-input tensor, a
(input, target)-style tuple/list, or a dict with input-like keys such as"input","image", or"images". The default recipe only supports single-input calibration; multi-input models should extend a custom recipe.mode (str or float) -- VoltageHook statistics mode. Supports
"Max", percentile strings, and float scaling with0 < mode <= 1.momentum (float) -- VoltageHook momentum.
fuse_flag (bool) -- Whether to fuse Conv-BN modules.
channel_wise (bool) -- If
True, collect robust activation scales per channel and use channel-wise thresholds. Defaults toFalseto preserve the original layer-wise behaviour.channel_dim (int) -- Channel dimension used when
channel_wise=True.pre_spike_maxpool (bool) -- When
channel_wise=Trueand aReLU -> MaxPool2dpattern is matched, place MaxPool2d before the spiking neuron.half_threshold (bool) -- When
channel_wise=True, initialize membrane potential at half threshold.eps (float) -- Numeric lower bound for thresholds when
channel_wise=True.rules (Optional[List[ActivationRule]]) -- Activation conversion rules. Defaults to
[ReLURule()].neuron_factory (Optional[NeuronFactory]) -- Spiking-neuron factory.
threshold_optimizer (Optional[ThresholdOptimizer]) -- Threshold optimizer.
- after_trace(converter, fx_model)[源代码]#
- 参数:
converter (Converter)
fx_model (fx.GraphModule)
- 返回类型:
fx.GraphModule
- calibrate(converter, fx_model)[源代码]#
- 参数:
converter (Converter)
fx_model (fx.GraphModule)
- 返回类型:
fx.GraphModule
- insert_observers(converter, fx_model)[源代码]#
- 参数:
converter (Converter)
fx_model (fx.GraphModule)
- 返回类型:
fx.GraphModule
- replace(converter, fx_model)[源代码]#
-
中文
将已校准的 activation-hook 节点对替换为 rate-coding SNN 子图,并将 结果移动到当前转换 device。
- 参数:
converter (Converter) -- 执行当前 recipe 的转换器。
fx_model (GraphModule) -- 已插入并校准
VoltageHook的GraphModule。
- 返回:
替换后的
GraphModule。- 返回类型:
English
Replace calibrated activation-hook node pairs with rate-coding SNN subgraphs, and move the result to the current conversion device.
- 参数:
converter (Converter) -- Converter that executes this recipe.
fx_model (GraphModule) --
GraphModulewith inserted and calibratedVoltageHookmodules.
- 返回:
Replaced
GraphModule.- 返回类型:
- class spikingjelly.activation_based.ann2snn.recipes.SpikeZIPTFQANNRecipe(time_steps=200, model_family='roberta', strict=True)[源代码]#
-
中文
SpikeZIP-TF QANN-to-SNN recipe。该 recipe 不执行 ANN 量化或后训练, 只把已经兼容 SpikeZIP 的 QANN 原位替换为透明 SNN module。当前版本支持
"roberta"与"vit"两类已量化模型。RoBERTa-style self-attention module 需要暴露query、key、valuelinear layers,num_attention_heads、attention_head_size、all_head_size、dropout,以及带有s、sym、pos_max、neg_min、level属性的query_quan、key_quan、value_quan、attn_quan、after_attn_quanquantizers。ViT-style attention module 需要暴露qkv、proj、quan_q、quan_k、quan_v、attn_quan、after_attn_quan、quan_proj、num_heads、head_dim、scale、attn_drop与proj_drop。RoBERTa attention mask 仅在第一个时间步加入,随后由 temporal-difference softmax 的累计状态传播该静态 mask 影响。 若 quantizer 未显式暴露level,则按pos_max - neg_min + 1推断。- 参数:
English
SpikeZIP-TF QANN-to-SNN recipe. This recipe does not quantize or post-train an ANN; it only converts an already SpikeZIP-compatible QANN into transparent SNN modules. The current version supports
"roberta"and"vit"quantized models. RoBERTa-style self-attention modules must exposequery,keyandvaluelinear layers,num_attention_heads,attention_head_size,all_head_sizeanddropout, plusquery_quan,key_quan,value_quan,attn_quanandafter_attn_quanquantizers withs,sym,pos_max,neg_minandlevelattributes. ViT-style attention modules must exposeqkv,proj,quan_q,quan_k,quan_v,attn_quan,after_attn_quan,quan_proj,num_heads,head_dim,scale,attn_dropandproj_drop. RoBERTa attention masks are added only at the first timestep; the temporal-difference softmax state carries the static mask effect afterwards. If a quantizer does not exposelevelexplicitly, the recipe infers it aspos_max - neg_min + 1.- 参数:
time_steps (int) -- Timestep metadata stored on the converted model. Users still explicitly construct single-step loops or multi-step input sequences; the recipe does not encode inputs or control
step_modeinternally. It should be no smaller than the QANN quantizationlevel; otherwise some bias terms or residual membrane charge may not be fully emitted.model_family (str) -- Model family. Supported values are
"roberta"and"vit".strict (bool) -- Must be
True. The parameter is reserved for future explicit boundary relaxation.
- convert_module(converter, ann)[源代码]#
- 参数:
converter (ModuleConverter)
ann (nn.Module)
- 返回类型:
nn.Module
- validate(converter)[源代码]#
- 参数:
converter (ModuleConverter)
- 返回类型:
None
- class spikingjelly.activation_based.ann2snn.recipes.STATransformerRecipe(dataloader=None, time_steps=32, mode='equivalent', threshold_mode='mse', threshold_scale=1.0, spike_linear=None, spike_conv2d=None, spike_classifier=False, momentum=0.1, num_calibration_batches=None, show_progress=False, eps=1e-06)[源代码]#
-
中文
实现基于 Spatio-Temporal Approximation (STA) [1] 思路的 training-free Transformer 转换 recipe。该 recipe 将 Transformer 中的 Linear、Conv2d、LayerNorm、GELU、
MultiheadAttention等算子替换为 支持 STA 差分时间传播的 step-mode 模块。 转换过程中会以eval模式 trace 和校准原 ANN;Converter会在 转换结束后恢复原 ANN 的training标志。mode="equivalent"是默认的在线累计-差分基线:Linear、Conv2d、 LayerNorm、GELU、MultiheadAttention和 FX tensor 常量都按时间步 保持与原 ANN 的累计输出等价。该模式用于建立 Transformer 图形态和 模型级接受基线,不宣称 fully spike-driven。mode="spiking_encoder"会在 LayerNorm、GELU 和MultiheadAttention输出侧插入校准后的有状态 spike encoder,同时 保持主干 affine 在线等价。mode="spiking_affine"会为选中的 Linear/Conv2d 统计阈值并替换为有状态 bipolar IF / burst affine 模块; LayerNorm、GELU 和MultiheadAttention仍使用在线累计-差分浮点 模块。当前 step-mode 对齐后端暂不支持mode="spiking_affine"、spike_linear=True或spike_conv2d=True;这些配置会明确报错。time_steps参与阈值搜索和图中常量的多步展开,因而是转换 recipe 的一部分,而不仅是外部评估循环参数。转换产物是普通
nn.Module/fx.GraphModule。用户通过spikingjelly.activation_based.functional.set_step_mode()递归设置 内部 step-mode 模块。step_mode="s"时,用户自己按时间步调用转换 后的模型;step_mode="m"时,模型接收第 0 维为时间维的序列 tensor 并返回输出序列。最终累计 readout 由用户显式执行,例如对时间维求和。- 参数:
dataloader (Optional[Iterable]) -- 校准数据加载器。每个 batch 可为单输入 tensor、
(input, target)风格的 tuple/list,或传递给模型的 kwargs dict。mode="equivalent"默认不执行校准,可传None;显式 启用spike_linear或spike_conv2d时也需要提供。time_steps (int) -- STA 内部推理时间步数,也用于阈值搜索。
mode (str) -- 转换模式,支持
"equivalent"、"spiking_encoder"和"spiking_affine"。threshold_mode (str) -- 阈值统计模式,支持
"mse"和"max"。threshold_scale (float) -- 校准阈值的正数缩放因子。
spike_linear (Optional[bool]) -- 是否替换 Linear 为 spiking affine。若为
None, 在mode="spiking_affine"时启用。spike_conv2d (Optional[bool]) -- 是否替换 Conv2d 为 spiking affine。若为
None, 默认不启用。spike_classifier (bool) --
spike_linear=True时是否也转换分类头。momentum (float) -- 阈值 observer 的动量。
num_calibration_batches (Optional[int]) -- 最多使用的校准 batch 数;
None表示 使用整个 dataloader。show_progress (bool) -- 是否显示校准进度条。
eps (float) -- 阈值数值下界。
- 抛出:
ValueError -- 当校验发现不支持的转换模式、阈值模式、非正 time step、非正缩放因子、非法动量、非法校准 batch 上限、非法 模式组合,或布尔选项类型错误时抛出。
English
Implement a training-free Transformer conversion recipe based on Spatio-Temporal Approximation (STA) [1]. The recipe replaces Transformer Linear, Conv2d, LayerNorm, GELU,
MultiheadAttentionand related operators with step-mode modules that support STA differential temporal propagation. Conversion traces and calibrates the original ANN inevalmode;Converterrestores the original ANNtrainingflags after conversion finishes.mode="equivalent"is the default online cumulative-difference baseline: Linear, Conv2d, LayerNorm, GELU,MultiheadAttentionand FX tensor constants preserve the original ANN cumulative output across time. This mode establishes the Transformer graph shape and model-level acceptance baseline; it does not claim to be fully spike-driven.mode="spiking_encoder"inserts calibrated stateful spike encoders after LayerNorm, GELU andMultiheadAttentionoutputs while keeping main affine projections online-equivalent.mode="spiking_affine"calibrates thresholds for selected Linear/Conv2d modules and replaces them with stateful bipolar IF / burst affine modules; LayerNorm, GELU andMultiheadAttentionremain online cumulative-difference floating-point modules. The current step-mode-aligned backend does not supportmode="spiking_affine",spike_linear=Trueorspike_conv2d=True; these configurations raise a clear error.time_stepsis used by threshold search and multi-step expansion of graph constants, so it belongs to the conversion recipe rather than only to an external evaluation loop.The converted model is a plain
nn.Module/fx.GraphModule. Users callspikingjelly.activation_based.functional.set_step_mode()to recursively configure internal step-mode modules. Withstep_mode="s", users call the converted model once per timestep. Withstep_mode="m", the model consumes sequence tensors whose first dimension is time and returns output sequences. Final accumulated readout is explicit, e.g. summing the time dimension.- 参数:
dataloader (Optional[Iterable]) -- Calibration dataloader. Each batch can be a single-input tensor, a
(input, target)-style tuple/list, or a kwargs dict passed to the model.mode="equivalent"skips calibration by default and can useNone; explicitly enablingspike_linearorspike_conv2dstill requires a dataloader.time_steps (int) -- Number of STA internal inference timesteps. It is also used by threshold search.
mode (str) -- Conversion mode. Supported values are
"equivalent","spiking_encoder"and"spiking_affine".threshold_mode (str) -- Threshold statistics mode. Supported values are
"mse"and"max".threshold_scale (float) -- Positive scale factor applied to calibrated thresholds.
spike_linear (Optional[bool]) -- Whether to replace Linear with spiking affine modules. If
None, enable it formode="spiking_affine".spike_conv2d (Optional[bool]) -- Whether to replace Conv2d with spiking affine modules. If
None, disable it by default.spike_classifier (bool) -- Whether to convert classifier heads when
spike_linear=True.momentum (float) -- Momentum used by threshold observers.
num_calibration_batches (Optional[int]) -- Maximum number of calibration batches;
Noneuses the full dataloader.show_progress (bool) -- Whether to show a calibration progress bar.
eps (float) -- Numeric lower bound for thresholds.
- 抛出:
ValueError -- If validation finds an unsupported mode, threshold mode, non-positive timestep count, non-positive scale, invalid momentum, invalid calibration batch limit, unsupported mode combination, or invalid type for a boolean option.
- calibrate(converter, fx_model)[源代码]#
- 参数:
converter (Converter)
fx_model (fx.GraphModule)
- 返回类型:
fx.GraphModule
- finalize(converter, fx_model)[源代码]#
- 参数:
converter (Converter)
fx_model (fx.GraphModule)
- 返回类型:
nn.Module
- insert_observers(converter, fx_model)[源代码]#
- 参数:
converter (Converter)
fx_model (fx.GraphModule)
- 返回类型:
fx.GraphModule
- class spikingjelly.activation_based.ann2snn.recipes.TransformerTDEquivalentRecipe(time_steps=None)[源代码]#
-
中文
Transformer TD-equivalent operator 替换 recipe。该 recipe 不插入 observer,不运行 dataloader 校准,也不强制切换模型 train/eval 状态;它仅 将当前支持的 ANN core modules 和窄 attention 子集替换为 TD 等价算子。
English
Transformer TD-equivalent operator replacement recipe. This recipe does not insert observers, does not run dataloader calibration, and does not force train/eval mode changes. It only replaces the currently supported ANN core modules and narrow attention subset with TD-equivalent operators.
- 参数:
time_steps (int | None)
- finalize(converter, fx_model)[源代码]#
- 参数:
converter (Converter)
fx_model (fx.GraphModule)
- 返回类型:
nn.Module
- replace(converter, fx_model)[源代码]#
-
中文
将当前支持的 Transformer core modules、SDPA 调用和窄
MultiheadAttention调用替换为 TD-equivalent 算子。 该步骤不插入 observer,也不运行 rate-coding 校准。- 参数:
converter (Converter) -- 执行当前 recipe 的转换器。
fx_model (GraphModule) -- 已 trace 的
GraphModule。
- 返回:
替换后的
GraphModule。- 返回类型:
- 抛出:
ValueError -- 当 attention 调用或配置不在当前支持范围内时抛出。
English
Replace currently supported Transformer core modules, SDPA calls and narrow
MultiheadAttentioncalls with TD-equivalent operators. This step does not insert observers or run rate-coding calibration.- 参数:
converter (Converter) -- Converter that executes this recipe.
fx_model (GraphModule) -- Traced
GraphModule.
- 返回:
Replaced
GraphModule.- 返回类型:
- 抛出:
ValueError -- If an attention call or configuration is outside the currently supported subset.
Rate-Coding Rules, Factories, and Thresholds#
These modules support the ReLU-to-spiking-neuron path used by rate-coding
recipes, primarily RateCodingRecipe and LocalThresholdBalancingRecipe.
ActivationRule / ReLURule match FX activation nodes, insert calibration
hooks, and replace calibrated activations with spiking-neuron subgraphs.
HookFactory, NeuronFactory, and ThresholdOptimizer are the matching
calibration and construction utilities.
Transformer TD-equivalent, STA Transformer, and SpikeZIP conversions do not use this graph-rule interface. They implement their own recipe-specific operator or module replacement logic.
- class spikingjelly.activation_based.ann2snn.rules.ActivationRule(*args, **kwargs)[源代码]#
基类:
Protocol
中文
激活函数转换规则协议。实现该协议即可接入新的 ANN→SNN 转换算法。规则需要负责:
通过
match()判断是否处理某个fx.Node;通过
insert_hooks()在节点后插入校准 hook;通过
find_replacements()找到(activation_node, hook_node)对;通过
replace_with_neurons()将激活节点与 hook 替换为脉冲神经元结构。
English
Protocol for activation-to-neuron conversion rules. Implement this protocol to plug a new ANN→SNN algorithm into the converter. A rule must:
decide whether it handles a given
fx.Nodeviamatch();insert a calibration hook after the node via
insert_hooks();enumerate
(activation_node, hook_node)pairs to replace viafind_replacements();replace the activation + hook pair with spiking neurons via
replace_with_neurons().
- match(node, modules)[源代码]#
-
中文
判断该规则是否处理给定节点。
- 参数:
node (fx.Node) -- 待检查的
fx.Node。modules (Dict[str, nn.Module]) --
fx.GraphModule.named_modules()得到的模块名字典。
- 返回:
若该规则负责此节点则返回
True。- 返回类型:
English
Return True if this rule handles the given graph node.
- insert_hooks(fx_model, node, hook_factory, hook_counts_per_prefix)[源代码]#
-
中文
在
node之后插入一个由hook_factory创建的校准 hook,并将新节点加入fx_model。hook_counts_per_prefix用于在多 hook 场景下生成唯一的目标 名称。- 参数:
fx_model (fx.GraphModule) -- 待修改的
GraphModule。node (fx.Node) -- 触发 hook 插入的
fx.Node。hook_factory (HookFactory) -- 校准 hook 工厂。
hook_counts_per_prefix (Dict[str, int]) -- 用于生成唯一 hook 目标名的前缀计数器。
- 返回:
新插入的 hook 节点。
- 返回类型:
fx.Node
English
Insert a calibration hook created by
hook_factoryafternodeand register the new node insidefx_model.hook_counts_per_prefixis used to generate unique hook target names when multiple hooks are inserted.- 参数:
fx_model (fx.GraphModule) -- The
GraphModuleto modify.node (fx.Node) -- The
fx.Nodeafter which the hook is inserted.hook_factory (HookFactory) -- Hook factory used to build the calibration hook.
hook_counts_per_prefix (Dict[str, int]) -- Per-prefix counters used to build unique hook target names.
- 返回:
The newly inserted hook node.
- 返回类型:
fx.Node
- find_replacements(fx_model, modules)[源代码]#
-
中文
遍历
fx_model,产出需要被替换的(activation_node, hook_node)对。 对于非标准图结构的规则,应重写该方法实现自定义遍历。- 参数:
fx_model (fx.GraphModule) -- 已插入校准 hook 的
GraphModule。modules (Dict[str, nn.Module]) --
fx.GraphModule.named_modules()得到的模块名字典。
- 返回:
形如
(activation_node, hook_node)的迭代器。- 返回类型:
Iterator[Tuple[fx.Node, fx.Node]]
English
Iterate over
fx_modeland yield(activation_node, hook_node)pairs to replace. Rules with non-standard graph patterns should override this method with their own traversal.- 参数:
fx_model (fx.GraphModule) --
GraphModulewith calibration hooks already inserted.modules (Dict[str, nn.Module]) -- Module-name dictionary obtained from
fx.GraphModule.named_modules().
- 返回:
Iterator of
(activation_node, hook_node)pairs.- 返回类型:
Iterator[Tuple[fx.Node, fx.Node]]
- replace_with_neurons(fx_model, activation_node, hook_node, neuron_factory, threshold_optimizer)[源代码]#
-
中文
将
activation_node与hook_node替换为对应的脉冲神经元结构。threshold由threshold_optimizer基于 hook 校准数据计算得到;神经元由neuron_factory构造。- 参数:
fx_model (fx.GraphModule) -- 待修改的
GraphModule。activation_node (fx.Node) -- 激活节点。
hook_node (fx.Node) -- 校准 hook 节点。
neuron_factory (NeuronFactory) -- 脉冲神经元工厂。
threshold_optimizer (ThresholdOptimizer) -- 阈值优化器。
- 返回类型:
None
English
Replace the activation + hook pair with the corresponding spiking neuron structure. The threshold is computed by
threshold_optimizerfrom the calibration hook; the neuron is built byneuron_factory.- 参数:
fx_model (fx.GraphModule) -- The
GraphModuleto modify.activation_node (fx.Node) -- The activation node.
hook_node (fx.Node) -- The calibration hook node.
neuron_factory (NeuronFactory) -- Spiking-neuron factory.
threshold_optimizer (ThresholdOptimizer) -- Threshold optimizer.
- 返回类型:
None
- class spikingjelly.activation_based.ann2snn.rules.ReLURule[源代码]#
基类:
object
中文
nn.ReLU转换规则。复现 SpikingJelly 原有行为:将每个nn.ReLU替换为VoltageScaler(1/s) -> IFNode -> VoltageScaler(s),其中s由ThresholdOptimizer基于VoltageHook的校准结果计算。
English
Conversion rule for
nn.ReLUmodules. Reproduces the original SpikingJelly behaviour: eachnn.ReLUis replaced byVoltageScaler(1/s) -> IFNode -> VoltageScaler(s), wheresis computed byThresholdOptimizerfrom theVoltageHookcalibration data.- insert_hooks(fx_model, node, hook_factory, hook_counts_per_prefix)[源代码]#
- 参数:
fx_model (GraphModule)
node (Node)
hook_factory (HookFactory)
- 返回类型:
- replace_with_neurons(fx_model, activation_node, hook_node, neuron_factory, threshold_optimizer)[源代码]#
- 参数:
fx_model (GraphModule)
activation_node (Node)
hook_node (Node)
neuron_factory (NeuronFactory)
threshold_optimizer (ThresholdOptimizer)
- 返回类型:
None
- class spikingjelly.activation_based.ann2snn.factories.NeuronFactory(neuron_type=<class 'spikingjelly.activation_based.neuron.integrate_and_fire.IFNode'>, v_threshold=1.0, v_reset=None, **kwargs)[源代码]#
基类:
object
中文
用于创建替换激活函数的脉冲神经元模块。默认创建
spikingjelly.activation_based.neuron.IFNode,并使用v_threshold=1.0与v_reset=None保持原有 ANN2SNN 行为。默认转换会通过VoltageScaler处理激活尺度,因此默认工厂不会把scale直接写入 神经元阈值;自定义工厂可读取scale派生阈值或其他参数。- 参数:
English
Factory that creates spiking-neuron modules used to replace ANN activation functions. By default it instantiates
spikingjelly.activation_based.neuron.IFNodewithv_threshold=1.0andv_reset=Noneto preserve the original ANN2SNN behaviour. The default conversion handles the activation scale withVoltageScaler, so the default factory does not copyscaleinto the neuron threshold. Custom factories may derive thresholds or other neuron parameters fromscale.- 参数:
neuron_type (Type[nn.Module]) -- Neuron class to instantiate. Must accept
v_thresholdandv_resetkeyword arguments. Defaults tospikingjelly.activation_based.neuron.IFNode.v_threshold (float) -- Firing threshold passed to the neuron constructor.
v_reset (Optional[float]) -- Membrane reset value.
Nonemeans soft reset (subtractive reset). Defaults toNone.kwargs -- Additional keyword arguments forwarded to the neuron constructor.
- create(scale)[源代码]#
-
中文
根据工厂配置创建一个脉冲神经元模块实例。
scale为当前层校准得到的激活 尺度,默认实现不直接使用该值,但子类可据此派生阈值或其他参数。- 参数:
scale (float) -- 当前层的校准尺度。
- 返回:
配置完成的脉冲神经元模块。
- 返回类型:
nn.Module
English
Instantiate a spiking-neuron module with the configured parameters.
scaleis the calibrated activation scale of the current layer; the default implementation does not use it directly, but subclasses can derive thresholds or other neuron parameters from it.- 参数:
scale (float) -- Calibration scale for the layer.
- 返回:
A spiking-neuron module.
- 返回类型:
nn.Module
- class spikingjelly.activation_based.ann2snn.factories.HookFactory(mode='Max', momentum=0.1)[源代码]#
基类:
object
中文
用于创建校准阶段使用的
VoltageHook实例。每个匹配到的激活节点会获得 独立的 hook 实例。- 参数:
English
Factory that creates
VoltageHookinstances used during calibration. Each matched activation node receives an independent hook instance.- 参数:
- class spikingjelly.activation_based.ann2snn.threshold.ThresholdOptimizer(strategy='fixed')[源代码]#
基类:
object
中文
阈值优化器。根据
VoltageHook在校准阶段记录的scale计算当前层的 神经元阈值。当前内置策略:"fixed": 阈值等于校准scale(默认,等价于 SpikingJelly 原有行为)。
其他策略需通过子类化并重写
compute_threshold()实现;基类可接受任意策略 名,但只有"fixed"在基类中真正生效。- 参数:
strategy (str) -- 阈值计算策略名称。
English
Threshold optimizer. Computes the neuron threshold for a layer from the
scalerecorded byVoltageHookduring calibration. Built-in strategy:"fixed": threshold equals the calibratedscale(default, matches the original SpikingJelly behaviour).
Additional strategies should be implemented by subclassing and overriding
compute_threshold(). The base class accepts any strategy name but only implements"fixed"itself.- 参数:
strategy (str) -- Name of the threshold computation strategy.
- compute_threshold(hook)[源代码]#
-
中文
返回当前层对应的脉冲神经元阈值。当前仅在
strategy="fixed"时直接返回 hook 中记录的scale;其他策略由子类实现。- 参数:
hook (VoltageHook) -- 已完成校准的
VoltageHook,其scale属性保存激活 范围统计量。- 返回:
神经元阈值。
- 返回类型:
- 抛出:
NotImplementedError -- 当
strategy不是已实现策略时抛出。AttributeError -- 当
hook不包含scale属性时抛出。
English
Return the spiking-neuron threshold for the layer represented by hook. With
strategy="fixed"this returns thescalestored in the hook; other strategies should be implemented by subclasses.- 参数:
hook (VoltageHook) -- A calibrated
VoltageHookwhosescaleattribute holds the activation range statistic.- 返回:
The neuron threshold.
- 返回类型:
- 抛出:
NotImplementedError -- If
strategyis not implemented.AttributeError -- If
hookdoes not expose ascaleattribute.
Stateful Operators and Runtime Modules#
Temporal-difference (TD) operators in
spikingjelly.activation_based.ann2snn.operators follow stateful
SpikingJelly step-mode semantics:
ann_forward(...)runs the ordinary stateless ANN/PyTorch operation and does not read or write module memory.step_mode="s"/single_step_forward(...)consumes one differential timestep, updates cumulative memory, and returns one differential output.step_mode="m"/multi_step_forward(...)consumes a complete sequence whose first dimension is time, uses vectorized cumulative-sum / temporal-difference execution where implemented, and leaves the final memory.Call
reset()before starting an independent sequence.
This means single_step_forward is not the ordinary ANN forward path for TD
operators. Use ann_forward when comparing a TD module with the source
PyTorch module at one non-temporal input.
- class spikingjelly.activation_based.ann2snn.operators.TDModule(step_mode='m')[源代码]#
基类:
MemoryModuleAPI Language
中文
Temporal-difference / sequence-preserving 算子的基类。该类继承
spikingjelly.activation_based.base.MemoryModule,使用step_mode、memory 和reset语义实现 TD 状态传播。step_mode="s"时,输入被解释为当前差分时间步,模块更新内部累积 memory 并返回当前差分输出;step_mode="m"时,输入第 0 维被解释为 时间维,模块返回完整差分序列并保留最终 memory。普通 ANN/PyTorch 数值 路径由ann_forward()提供,且不读写 memory。子类必须实现ann_forward()和multi_step_forward()。子类__init__应调用super().__init__(step_mode)初始化步进模式。- 参数:
step_mode (str) -- 步进模式,
"s"或"m"。默认"m"保持既有 TD operator 行为。- 抛出:
ValueError -- 当
step_mode非法时,由StepModule的 setter 抛出;若子类绕过 setter 写入非法模式,forward也会抛出。
English
Base class for temporal-difference / sequence-preserving operators. It inherits
spikingjelly.activation_based.base.MemoryModuleand usesstep_mode, memory, andresetsemantics for TD state propagation.With
step_mode="s", inputs are interpreted as the current differential time step; the module updates its cumulative memory and returns the current differential output. Withstep_mode="m", dimension 0 is interpreted as the time dimension; the module returns a full differential sequence and keeps the final memory. The ordinary ANN/PyTorch numeric path is exposed byann_forward()and does not read or write memory. Subclasses must implementann_forward()andmulti_step_forward(). Subclass__init__methods should callsuper().__init__(step_mode)to initialize the step mode.- 参数:
step_mode (str) -- Step mode,
"s"or"m". The default"m"preserves existing TD operator behavior.- 抛出:
ValueError -- Raised by
StepModule's setter whenstep_modeis invalid;forwardalso raises if a subclass bypasses the setter and writes an invalid mode.
- class spikingjelly.activation_based.ann2snn.operators.TDSoftmax(dim=-1, step_mode='m')[源代码]#
基类:
TDModuleAPI Language
中文
Temporal-difference (TD) Softmax 算子。
step_mode="m"时输入 必须是完整时间序列,时间维固定为第 0 维,形状为[T, ...]; 模块先对输入在时间维做累积,再沿dim计算torch.softmax,最后返回累积输出在时间维上的差分。step_mode="s"时输入被解释为当前差分时间步,模块更新内部累积 memory 并返回当前差分输出;普通torch.softmax路径由ann_forward()提供。返回值是浮点差分值,可能包含负值;它不是二值脉冲,也不表示 fully spike-driven Softmax。输出 dtype 与输入 dtype 相同;推荐使用
float32、float16或float64输入。该算子完全由 PyTorch 可微算子组成,对 autograd 透明。该算子的机制来源于 SpikeZIP-TF: Conversion is All You Need for Transformer-based SNN 中对 Transformer 非线性算子的累积-差分等价转换思路。本文档中的 TD Softmax 只实现张量级算子:在多步模式下它仍调用
torch.softmax,需要完整时间序列输入,不是逐时间步在线算子, 也不是面向神经形态硬件的 fully spike-driven Softmax。op = TDSoftmax(dim=-1) x_seq = torch.randn(4, 2, 3) y_seq = op(x_seq)
- 参数:
English
Temporal-difference (TD) Softmax operator. With
step_mode="m", the input must be a complete time sequence whose time dimension is fixed at dimension 0, with shape[T, ...]. This module first accumulates the input over time, appliestorch.softmaxalongdimto each cumulative input, and returns the temporal difference of the cumulative outputs. Withstep_mode="s", the input is interpreted as the current differential time step; the module updates its cumulative memory and returns the current differential output. The ordinarytorch.softmaxpath is exposed byann_forward().The output contains floating-point differential values and may contain negative values. It is not a binary spike tensor and does not represent a fully spike-driven Softmax. The output dtype matches the input dtype;
float32,float16andfloat64inputs are recommended. The operator is composed entirely of differentiable PyTorch operations and is transparent to autograd.The mechanism follows the cumulative-difference equivalence idea for Transformer nonlinear operators in SpikeZIP-TF: Conversion is All You Need for Transformer-based SNN. This implementation provides only a tensor-level operator: in multi-step mode it still calls
torch.softmax, requires a complete time sequence, is not a step-wise online operator, and is not a fully spike-driven Softmax for neuromorphic hardware.op = TDSoftmax(dim=-1) x_seq = torch.randn(4, 2, 3) y_seq = op(x_seq)
- 参数:
- multi_step_forward(x_seq)[源代码]#
API Language
中文
对完整时间序列执行 TD Softmax。计算过程为:
\[X_{cum}[t] = \sum_{i=0}^{t} X[i]\]\[Y_{cum}[t] = \operatorname{Softmax}(X_{cum}[t])\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]因此
Y.cumsum(dim=0)与对X.cumsum(dim=0)逐时间步执行 ANN Softmax 的结果一致。输出是浮点差分值,可能为负,不是二值脉冲。 当T = 1时,Y[0]直接等于torch.softmax(X[0], dim=dim)。 输出 dtype 与输入 dtype 相同,且该算子对 autograd 透明。- 参数:
x_seq (Tensor) -- 输入时间序列,形状为
[T, ...],且T > 0。- 返回:
TD Softmax 差分序列,形状与
x_seq相同。- 返回类型:
- 抛出:
ValueError -- 若
x_seq少于 2 维、时间维为空,或dim指向时间维。
English
Apply TD Softmax to a complete time sequence:
\[X_{cum}[t] = \sum_{i=0}^{t} X[i]\]\[Y_{cum}[t] = \operatorname{Softmax}(X_{cum}[t])\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]Thus,
Y.cumsum(dim=0)matches ANN Softmax applied toX.cumsum(dim=0)at each time step. The output contains floating-point differential values, may be negative, and is not a binary spike tensor. WhenT = 1,Y[0]is exactlytorch.softmax(X[0], dim=dim). The output dtype matches the input dtype, and the operator is transparent to autograd.- 参数:
x_seq (Tensor) -- Input time sequence with shape
[T, ...]andT > 0.- 返回:
TD Softmax differential sequence with the same shape as
x_seq.- 返回类型:
- 抛出:
ValueError -- If
x_seqhas fewer than 2 dimensions, the time dimension is empty, ordimrefers to the time dimension.
- class spikingjelly.activation_based.ann2snn.operators.TDLayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, bias=True, device=None, dtype=None, step_mode='m')[源代码]#
基类:
TDModuleAPI Language
中文
Temporal-difference (TD) LayerNorm 算子。
step_mode="m"时输入 必须是完整时间序列,时间维固定为第 0 维,形状为[T, ...]; 模块先对输入在时间维做累积,再对每个累积输入执行torch.nn.functional.layer_norm(),最后返回累积输出在时间维上的 差分。step_mode="s"时输入被解释为当前差分时间步,模块更新内部 累积 memory 并返回当前差分输出;普通 LayerNorm 路径由ann_forward()提供。返回值是浮点差分值,可能包含负值;它不是二值脉冲,也不表示 fully spike-driven LayerNorm。输出 dtype 与输入 dtype 相同;推荐使用
float32、float16或float64输入。该算子完全由 PyTorch 可微算子组成,对 autograd 透明。该算子是 stateful TD MemoryModule; 重复处理独立序列前应调用reset。该算子的机制来源于 SpikeZIP-TF: Conversion is All You Need for Transformer-based SNN 中对 Transformer 非线性算子的累积-差分等价转换思路。本文档中的 TD LayerNorm 只实现张量级算子:在多步模式下它仍调用
torch.nn.functional.layer_norm(),需要完整时间序列输入,不是逐 时间步在线算子,也不是面向神经形态硬件的 fully spike-driven LayerNorm。op = TDLayerNorm(normalized_shape=3) x_seq = torch.randn(4, 2, 3) y_seq = op(x_seq)
- 参数:
normalized_shape (int or list[int] or Size) -- 输入尾部需要归一化的形状,与
torch.nn.LayerNorm的normalized_shape语义一致。eps (float) -- 加到方差上的数值稳定项。
elementwise_affine (bool) -- 若为
True,使用可学习的逐元素仿射 参数。bias (bool) -- 若
elementwise_affine和bias均为True, 使用可学习 bias 参数。若elementwise_affine为False, 则忽略bias。dtype (dtype or None) -- 参数初始化 dtype。
step_mode (str) -- 步进模式,
"s"或"m"。默认"m"。
English
Temporal-difference (TD) LayerNorm operator. With
step_mode="m", the input must be a complete time sequence whose time dimension is fixed at dimension 0, with shape[T, ...]. This module first accumulates the input over time, appliestorch.nn.functional.layer_norm()to each cumulative input, and returns the temporal difference of the cumulative outputs. Withstep_mode="s", the input is interpreted as the current differential time step; the module updates its cumulative memory and returns the current differential output. The ordinary LayerNorm path is exposed byann_forward().The output contains floating-point differential values and may contain negative values. It is not a binary spike tensor and does not represent a fully spike-driven LayerNorm. The output dtype matches the input dtype;
float32,float16andfloat64inputs are recommended. The operator is composed entirely of differentiable PyTorch operations and is transparent to autograd. The operator is a stateful TD MemoryModule; callresetbefore processing an independent sequence.The mechanism follows the cumulative-difference equivalence idea for Transformer nonlinear operators in SpikeZIP-TF: Conversion is All You Need for Transformer-based SNN. This implementation provides only a tensor-level operator: in multi-step mode it still calls
torch.nn.functional.layer_norm(), requires a complete time sequence, is not a step-wise online operator, and is not a fully spike-driven LayerNorm for neuromorphic hardware.op = TDLayerNorm(normalized_shape=3) x_seq = torch.randn(4, 2, 3) y_seq = op(x_seq)
- 参数:
normalized_shape (int or list[int] or Size) -- Input trailing shape to normalize, with the same semantics as
normalized_shapeintorch.nn.LayerNorm.eps (float) -- Value added to the variance for numerical stability.
elementwise_affine (bool) -- If
True, use learnable per-element affine parameters.bias (bool) -- If both
elementwise_affineandbiasareTrue, use a learnable bias parameter. Ifelementwise_affineisFalse,biasis ignored.device (device or str or None) -- Device used to initialize parameters.
dtype (dtype or None) -- Dtype used to initialize parameters.
step_mode (str) -- Step mode,
"s"or"m". The default is"m".
- multi_step_forward(x_seq)[源代码]#
API Language
中文
对完整时间序列执行 TD LayerNorm。计算过程为:
\[X_{cum}[t] = \sum_{i=0}^{t} X[i]\]\[Y_{cum}[t] = \operatorname{LayerNorm}(X_{cum}[t])\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]因此
Y.cumsum(dim=0)与对X.cumsum(dim=0)逐时间步执行 ANN LayerNorm 的结果一致。输出是浮点差分值,可能为负,不是二值 脉冲。 当T = 1时,Y[0]直接等于对X[0]执行 LayerNorm 的 结果。 输出 dtype 与输入 dtype 相同,且该算子对 autograd 透明。- 参数:
x_seq (Tensor) -- 输入时间序列,形状为
[T, ...],且T > 0,尾部形状必须 匹配normalized_shape。- 返回:
TD LayerNorm 差分序列,形状与
x_seq相同。- 返回类型:
- 抛出:
ValueError -- 若
x_seq少于 2 维、时间维为空或尾部形状不匹配。
English
Apply TD LayerNorm to a complete time sequence:
\[X_{cum}[t] = \sum_{i=0}^{t} X[i]\]\[Y_{cum}[t] = \operatorname{LayerNorm}(X_{cum}[t])\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]Thus,
Y.cumsum(dim=0)matches ANN LayerNorm applied toX.cumsum(dim=0)at each time step. The output contains floating-point differential values, may be negative, and is not a binary spike tensor. WhenT = 1,Y[0]is exactly LayerNorm applied toX[0]. The output dtype matches the input dtype, and the operator is transparent to autograd.- 参数:
x_seq (Tensor) -- Input time sequence with shape
[T, ...]andT > 0. The trailing shape must matchnormalized_shape.- 返回:
TD LayerNorm differential sequence with the same shape as
x_seq.- 返回类型:
- 抛出:
ValueError -- If
x_seqhas fewer than 2 dimensions, the time dimension is empty, or the trailing shape does not match.
- class spikingjelly.activation_based.ann2snn.operators.TDGELU(approximate='none', step_mode='m')[源代码]#
基类:
TDModuleAPI Language
中文
Temporal-difference (TD) GELU(Gaussian Error Linear Unit)算子。
step_mode="m"时输入必须是完整时间序列,时间维固定为第 0 维, 形状为[T, ...];模块先对输入在时间维做累积,再对每个累积输入 执行torch.nn.functional.gelu(),最后返回累积输出在时间维上的 差分。step_mode="s"时输入被解释为当前差分时间步,模块更新内部 累积 memory 并返回当前差分输出;普通 GELU 路径由ann_forward()提供。返回值是浮点差分值,可能包含负值;它不是二值脉冲,也不表示 fully spike-driven GELU。输出 dtype 与输入 dtype 相同;推荐使用
float32、float16、bfloat16或float64输入。该算子 完全由 PyTorch 可微算子组成,对 autograd 透明。该算子是 stateful TD MemoryModule;重复处理独立序列前应调用reset。该算子仅依赖torch.nn.functional.gelu(),支持 CPU 与 CUDA,后端与torch一致,无 CuPy / Triton 专用路径。该算子的机制来源于 SpikeZIP-TF: Conversion is All You Need for Transformer-based SNN 中对 Transformer 非线性算子的累积-差分等价转换思路。本文档中的 TD GELU 只实现张量级算子:在多步模式下它仍调用
torch.nn.functional.gelu(),需要完整时间序列输入,不是逐时间步 在线算子,也不是面向神经形态硬件的 fully spike-driven GELU。op = TDGELU(approximate="none") x_seq = torch.randn(4, 2, 3) y_seq = op(x_seq)
- 参数:
approximate (Literal["none", "tanh"]) -- GELU 近似模式,与
torch.nn.GELU的approximate语义一致。step_mode (str) -- 步进模式,
"s"或"m"。默认"m"。
- 抛出:
ValueError -- 若
approximate不是"none"或"tanh"。
English
Temporal-difference (TD) GELU (Gaussian Error Linear Unit) operator. With
step_mode="m", the input must be a complete time sequence whose time dimension is fixed at dimension 0, with shape[T, ...]. This module first accumulates the input over time, appliestorch.nn.functional.gelu()to each cumulative input, and returns the temporal difference of the cumulative outputs. Withstep_mode="s", the input is interpreted as the current differential time step; the module updates its cumulative memory and returns the current differential output. The ordinary GELU path is exposed byann_forward().The output contains floating-point differential values and may contain negative values. It is not a binary spike tensor and does not represent a fully spike-driven GELU. The output dtype matches the input dtype;
float32,float16,bfloat16andfloat64inputs are recommended. The operator is composed entirely of differentiable PyTorch operations and is transparent to autograd. The operator is a stateful TD MemoryModule; callresetbefore processing an independent sequence. It only depends ontorch.nn.functional.gelu(), supports CPU and CUDA, follows thetorchbackend behavior, and has no CuPy / Triton specific path.The mechanism follows the cumulative-difference equivalence idea for Transformer nonlinear operators in SpikeZIP-TF: Conversion is All You Need for Transformer-based SNN. This implementation provides only a tensor-level operator: in multi-step mode it still calls
torch.nn.functional.gelu(), requires a complete time sequence, is not a step-wise online operator, and is not a fully spike-driven GELU for neuromorphic hardware.op = TDGELU(approximate="none") x_seq = torch.randn(4, 2, 3) y_seq = op(x_seq)
- 参数:
approximate (Literal["none", "tanh"]) -- GELU approximation mode, with the same semantics as
approximateintorch.nn.GELU.step_mode (str) -- Step mode,
"s"or"m". The default is"m".
- 抛出:
ValueError -- If
approximateis not"none"or"tanh".
- multi_step_forward(x_seq)[源代码]#
API Language
中文
对完整时间序列执行 TD GELU。计算过程为:
\[X_{cum}[t] = \sum_{i=0}^{t} X[i]\]\[Y_{cum}[t] = \operatorname{GELU}(X_{cum}[t])\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]因此
Y.cumsum(dim=0)与对X.cumsum(dim=0)逐时间步执行 ANN GELU 的结果一致。输出是浮点差分值,可能为负,不是二值脉冲。 当T = 1时,Y[0]直接等于对X[0]执行 GELU 的结果。 输出 dtype 与输入 dtype 相同,且该算子对 autograd 透明。- 参数:
x_seq (Tensor) -- 输入时间序列,形状为
[T, ...],且T > 0。- 返回:
TD GELU 差分序列,形状与
x_seq相同。- 返回类型:
- 抛出:
ValueError -- 若
x_seq少于 2 维或时间维为空。
English
Apply TD GELU to a complete time sequence:
\[X_{cum}[t] = \sum_{i=0}^{t} X[i]\]\[Y_{cum}[t] = \operatorname{GELU}(X_{cum}[t])\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]Thus,
Y.cumsum(dim=0)matches ANN GELU applied toX.cumsum(dim=0)at each time step. The output contains floating-point differential values, may be negative, and is not a binary spike tensor. WhenT = 1,Y[0]is exactly GELU applied toX[0]. The output dtype matches the input dtype, and the operator is transparent to autograd.- 参数:
x_seq (Tensor) -- Input time sequence with shape
[T, ...]andT > 0.- 返回:
TD GELU differential sequence with the same shape as
x_seq.- 返回类型:
- 抛出:
ValueError -- If
x_seqhas fewer than 2 dimensions or the time dimension is empty.
- class spikingjelly.activation_based.ann2snn.operators.TDLinear(in_features, out_features, bias=True, device=None, dtype=None, step_mode='m')[源代码]#
基类:
TDModule
中文
Temporal-difference (TD) Linear 算子。
step_mode="m"时输入必须 是完整时间序列,时间维固定为第 0 维,形状为[T, ..., in_features];模块返回 sequence-preserving affine 差分序列,使Y.cumsum(dim=0)等于对X.cumsum(dim=0)逐时间 步执行torch.nn.functional.linear()。step_mode="s"时输入 被解释为当前差分时间步,模块更新内部累积 memory 并返回当前差分输出; 普通 Linear 路径由ann_forward()提供。返回值是浮点差分值,可能包含负值;它不是二值脉冲,也不表示 fully spike-driven Linear。输出 dtype 与 PyTorch Linear 一致;推荐使用
float32、float16、bfloat16或float64输入。该算子 完全由 PyTorch 可微算子组成,对 autograd 透明。该算子是 stateful TD MemoryModule;重复处理独立序列前应调用reset。该算子仅依赖 PyTorch Linear,支持 CPU 与 CUDA,后端与torch一致,无 CuPy / Triton 专用路径。该算子用于处理带 bias 的 affine projection。普通
torch.nn.Linear直接作用在 TD 差分序列上会在时间累积后得到T * bias;TD Linear 使累计输出保持W @ x_cum + bias。当bias=False时,该算子退化为普通逐时间步 Linear;当bias=True时,bias 只在第 0 个时间步进入差分序列。op = TDLinear(3, 5) x_seq = torch.randn(4, 2, 3) y_seq = op(x_seq)
- 参数:
English
Temporal-difference (TD) Linear operator. With
step_mode="m", the input must be a complete time sequence whose time dimension is fixed at dimension 0, with shape[T, ..., in_features]. This module returns a sequence-preserving affine differential sequence such thatY.cumsum(dim=0)matchestorch.nn.functional.linear()applied toX.cumsum(dim=0)at every time step. Withstep_mode="s", the input is interpreted as the current differential time step; the module updates its cumulative memory and returns the current differential output. The ordinary Linear path is exposed byann_forward().The output contains floating-point differential values and may contain negative values. It is not a binary spike tensor and does not represent a fully spike-driven Linear. The output dtype follows PyTorch Linear;
float32,float16,bfloat16andfloat64inputs are recommended. The operator is composed entirely of differentiable PyTorch operations and is transparent to autograd. The operator is a stateful TD MemoryModule; callresetbefore processing an independent sequence. It only depends on PyTorch Linear, supports CPU and CUDA, follows thetorchbackend behavior, and has no CuPy / Triton specific path.This operator handles affine projections with bias. Applying ordinary
torch.nn.Lineardirectly to a TD differential sequence would accumulate the bias asT * bias. TD Linear applies Linear to the cumulative input and then differences the cumulative output, preservingW @ x_cum + bias. Whenbias=False, this operator degenerates to ordinary per-time-step Linear. Whenbias=True, the bias appears only at the first time step of the differential sequence.op = TDLinear(3, 5) x_seq = torch.randn(4, 2, 3) y_seq = op(x_seq)
- 参数:
in_features (int) -- Number of input features.
out_features (int) -- Number of output features.
bias (bool) -- If
True, use a learnable bias parameter.device (device or str or None) -- Device used to initialize parameters.
dtype (dtype or None) -- Dtype used to initialize parameters.
step_mode (str) -- Step mode,
"s"or"m". The default is"m".
- multi_step_forward(x_seq)[源代码]#
-
中文
对完整时间序列执行 TD Linear。计算过程为:
\[X_{cum}[t] = \sum_{i=0}^{t} X[i]\]\[Y_{cum}[t] = X_{cum}[t] W^T + b\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]因此
Y.cumsum(dim=0)与对X.cumsum(dim=0)逐时间步执行 ANN Linear 的结果一致。若bias为None,该计算等价于直接对X逐时间步执行 Linear;若存在 bias,bias 只出现在Y[0]中, 避免累计后得到T * bias。输出是浮点差分值,可能为负,不是二值 脉冲。当T = 1时,Y[0]直接等于对X[0]执行 Linear 的 结果。输出 dtype 与 PyTorch Linear 一致,且该算子对 autograd 透明。- 参数:
x_seq (Tensor) -- 输入时间序列,形状为
[T, ..., in_features],且T > 0。- 返回:
TD Linear 差分序列,形状为
[T, ..., out_features]。- 返回类型:
- 抛出:
ValueError -- 若
x_seq少于 2 维或时间维为空。
English
Apply TD Linear to a complete time sequence:
\[X_{cum}[t] = \sum_{i=0}^{t} X[i]\]\[Y_{cum}[t] = X_{cum}[t] W^T + b\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]Thus,
Y.cumsum(dim=0)matches ANN Linear applied toX.cumsum(dim=0)at each time step. IfbiasisNone, this is equivalent to applying Linear toXat each time step directly. If a bias exists, the bias appears only inY[0], avoidingT * biasafter accumulation. The output contains floating-point differential values, may be negative, and is not a binary spike tensor. WhenT = 1,Y[0]is exactly Linear applied toX[0]. The output dtype follows PyTorch Linear, and the operator is transparent to autograd.- 参数:
x_seq (Tensor) -- Input time sequence with shape
[T, ..., in_features]andT > 0.- 返回:
TD Linear differential sequence with shape
[T, ..., out_features].- 返回类型:
- 抛出:
ValueError -- If
x_seqhas fewer than 2 dimensions or the time dimension is empty.
- class spikingjelly.activation_based.ann2snn.operators.TDConv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None, step_mode='m')[源代码]#
基类:
TDModule
中文
Temporal-difference (TD) Conv2d 算子。
step_mode="m"时输入必须是 完整时间序列,形状为[T, N, C, H, W];返回的浮点差分序列满足Y.cumsum(dim=0)等于对X.cumsum(dim=0)逐时间步执行torch.nn.functional.conv2d()。当存在 bias 时,bias 只出现在第 0 个差分时间步,避免累计后得到T * bias。step_mode="s"时 输入被解释为当前差分时间步,模块更新内部累积 memory 并返回当前差分 输出;普通 Conv2d 路径由ann_forward()提供。输出是浮点差分值,可能包含负值;它不是二值脉冲,也不表示 fully spike-driven Conv2d。构造参数对齐
torch.nn.Conv2d的 2D convolution 参数,支持padding="same"和padding="valid"。- 参数:
in_channels (int) -- 输入通道数。
out_channels (int) -- 输出通道数。
padding (str | int | Tuple[int, int]) -- padding 参数,可为整数、tuple、
"same"或"valid"。groups (int) -- 分组卷积组数。
bias (bool) -- 是否使用 learnable bias。
padding_mode (str) -- padding 模式。
dtype (dtype | None) -- 参数初始化 dtype。
step_mode (str) -- 步进模式,
"s"或"m"。默认"m"。
English
Temporal-difference (TD) Conv2d operator. With
step_mode="m", input must be a complete time sequence with shape[T, N, C, H, W]. The returned floating differential sequence satisfiesY.cumsum(dim=0)matchingtorch.nn.functional.conv2d()applied toX.cumsum(dim=0)at each timestep. When bias is present, it appears only inY[0]to avoid accumulatingT * bias. Withstep_mode="s", the input is interpreted as the current differential time step; the module updates its cumulative memory and returns the current differential output. The ordinary Conv2d path is exposed byann_forward().The output may contain negative floating-point differential values. It is not a binary spike tensor and does not represent a fully spike-driven Conv2d. Constructor arguments mirror the supported 2D convolution arguments of
torch.nn.Conv2d, includingpadding="same"andpadding="valid".- 参数:
in_channels (int) -- Number of input channels.
out_channels (int) -- Number of output channels.
kernel_size (int or Tuple[int, int]) -- Convolution kernel size.
padding (str | int | Tuple[int, int]) -- Padding argument, which can be an int, tuple,
"same"or"valid".groups (int) -- Number of convolution groups.
bias (bool) -- If
True, use a learnable bias parameter.padding_mode (str) -- Padding mode.
device (device | str | None) -- Device used to initialize parameters.
dtype (dtype | None) -- Dtype used to initialize parameters.
step_mode (str) -- Step mode,
"s"or"m". The default is"m".
- class spikingjelly.activation_based.ann2snn.operators.SNNMatrixOperator(step_mode='m')[源代码]#
基类:
TDModuleAPI Language
中文
Sequence-preserving SNN 矩阵乘法算子。
step_mode="m"时输入必须 是两条完整时间序列,时间维固定为第 0 维,形状分别为[T, ..., M, N]和[T, ..., N, P];模块先分别对两条输入在时间 维做累积,再执行torch.matmul(),最后返回累积输出在时间维上的 差分。step_mode="s"时输入被解释为当前差分时间步,模块更新内部 累积 memory 并返回当前差分输出;普通 matmul 路径由ann_forward()提供。该算子满足
Y.cumsum(dim=0) == torch.matmul(A.cumsum(dim=0), B.cumsum(dim=0))。 因而它保留 cross-time terms,例如A[0] @ B[1]与A[1] @ B[0];这不同于逐时间步执行A[t] @ B[t]。该算子是 LASSNNMatrixOperatorprefix recurrence 的 sequence-preserving 张量级形式,但不会在内部自动sum(0)。输出是浮点差分值,可能包含负值;它不是二值脉冲,也不表示 fully spike-driven matrix multiplication。dtype、device 与 broadcast 语义遵循
torch.matmul()。该算子是 stateful TD MemoryModule;重复处理独立 序列前应调用reset。- 参数:
step_mode (str) -- 步进模式,
"s"或"m"。默认"m"。
English
Sequence-preserving SNN matrix multiplication operator. With
step_mode="m", the inputs must be two complete time sequences whose time dimension is fixed at dimension 0, with shapes[T, ..., M, N]and[T, ..., N, P]. This module accumulates both inputs over time, appliestorch.matmul(), and returns the temporal difference of the cumulative outputs. Withstep_mode="s", the inputs are interpreted as the current differential time step; the module updates its cumulative memory and returns the current differential output. The ordinary matmul path is exposed byann_forward().The operator satisfies
Y.cumsum(dim=0) == torch.matmul(A.cumsum(dim=0), B.cumsum(dim=0)). Therefore it preserves cross-time terms such asA[0] @ B[1]andA[1] @ B[0]; it is not equivalent to applyingA[t] @ B[t]at each time step independently. It is the sequence-preserving tensor form of the LASSNNMatrixOperatorprefix recurrence, but it does not implicitly callsum(0).The output contains floating-point differential values and may contain negative values. It is not a binary spike tensor and does not represent fully spike-driven matrix multiplication. Dtype, device and broadcasting semantics follow
torch.matmul(). The operator is a stateful TD MemoryModule; callresetbefore processing an independent sequence.- 参数:
step_mode (str) -- Step mode,
"s"or"m". The default is"m".
- multi_step_forward(a_seq, b_seq)[源代码]#
API Language
中文
对两条完整时间序列执行 sequence-preserving SNN 矩阵乘法:
\[A_{cum}[t] = \sum_{i=0}^{t} A[i]\]\[B_{cum}[t] = \sum_{i=0}^{t} B[i]\]\[Y_{cum}[t] = A_{cum}[t] B_{cum}[t]\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]- 参数:
- 返回:
差分输出序列,形状为
[T, ..., M, P]。- 返回类型:
- 抛出:
ValueError -- 若输入少于 3 维、时间维为空或时间长度不一致。
English
Apply sequence-preserving SNN matrix multiplication to two complete time sequences:
\[A_{cum}[t] = \sum_{i=0}^{t} A[i]\]\[B_{cum}[t] = \sum_{i=0}^{t} B[i]\]\[Y_{cum}[t] = A_{cum}[t] B_{cum}[t]\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]- 参数:
- 返回:
Differential output sequence with shape
[T, ..., M, P].- 返回类型:
- 抛出:
ValueError -- If an input has fewer than 3 dimensions, the time dimension is empty, or the time lengths differ.
- class spikingjelly.activation_based.ann2snn.operators.SNNElementWiseProduct(step_mode='m')[源代码]#
基类:
TDModuleAPI Language
中文
Sequence-preserving SNN 逐元素乘法算子。
step_mode="m"时输入 必须是两条完整时间序列,时间维固定为第 0 维,形状为[T, ...], 非时间维遵循 PyTorch broadcast 规则;模块先分别对两条输入在时间维做 累积,再执行逐元素乘法,最后返回累积输出在时间维上的差分。step_mode="s"时输入被解释为当前差分时间步,模块更新内部累积 memory 并返回当前差分输出;普通逐元素乘法路径由ann_forward()提供。该算子满足
Y.cumsum(dim=0) == A.cumsum(dim=0) * B.cumsum(dim=0)。 它是 LASSNNMACOperator核心乘法-累积语义的 sequence-preserving 张量级形式,但不会在内部自动sum(0);需要单步聚合时由调用方显式 完成。输出是浮点差分值,可能包含负值;它不是二值脉冲,也不表示 fully spike-driven multiply-accumulate。dtype、device 与 broadcast 语义遵循 PyTorch 逐元素乘法。该算子是 stateful TD MemoryModule;重复处理独立 序列前应调用
reset。- 参数:
step_mode (str) -- 步进模式,
"s"或"m"。默认"m"。
English
Sequence-preserving SNN element-wise product operator. With
step_mode="m", the inputs must be two complete time sequences whose time dimension is fixed at dimension 0, with shape[T, ...]. Non-time dimensions follow PyTorch broadcasting rules. This module accumulates both inputs over time, applies element-wise multiplication, and returns the temporal difference of the cumulative outputs. Withstep_mode="s", the inputs are interpreted as the current differential time step; the module updates its cumulative memory and returns the current differential output. The ordinary element-wise multiplication path is exposed byann_forward().The operator satisfies
Y.cumsum(dim=0) == A.cumsum(dim=0) * B.cumsum(dim=0). It is the sequence-preserving tensor form of the core multiply-accumulate semantics in LASSNNMACOperator, but it does not implicitly callsum(0); callers should aggregate explicitly when a single-step output is required.The output contains floating-point differential values and may contain negative values. It is not a binary spike tensor and does not represent fully spike-driven multiply-accumulate. Dtype, device and broadcasting semantics follow PyTorch element-wise multiplication. The operator is a stateful TD MemoryModule; call
resetbefore processing an independent sequence.- 参数:
step_mode (str) -- Step mode,
"s"or"m". The default is"m".
- multi_step_forward(a_seq, b_seq)[源代码]#
API Language
中文
对两条完整时间序列执行 sequence-preserving SNN 逐元素乘法:
\[A_{cum}[t] = \sum_{i=0}^{t} A[i]\]\[B_{cum}[t] = \sum_{i=0}^{t} B[i]\]\[Y_{cum}[t] = A_{cum}[t] \odot B_{cum}[t]\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]- 参数:
- 返回:
差分输出序列,形状由 PyTorch broadcast 规则决定。
- 返回类型:
- 抛出:
ValueError -- 若输入少于 2 维、时间维为空或时间长度不一致。
English
Apply sequence-preserving SNN element-wise product to two complete time sequences:
\[A_{cum}[t] = \sum_{i=0}^{t} A[i]\]\[B_{cum}[t] = \sum_{i=0}^{t} B[i]\]\[Y_{cum}[t] = A_{cum}[t] \odot B_{cum}[t]\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]- 参数:
- 返回:
Differential output sequence whose shape follows PyTorch broadcasting rules.
- 返回类型:
- 抛出:
ValueError -- If an input has fewer than 2 dimensions, the time dimension is empty, or the time lengths differ.
- class spikingjelly.activation_based.ann2snn.operators.TDScaledDotProductAttention(is_causal=False, scale=None, step_mode='m')[源代码]#
基类:
TDModuleAPI Language
中文
Temporal-difference (TD) scaled dot-product attention 算子。
step_mode="m"时输入必须是完整时间序列,时间维固定为第 0 维。query_seq的形状为[T, ..., L, E],key_seq的形状为[T, ..., S, E],value_seq的形状为[T, ..., S, Ev]; 模块先分别对 query、key、value 在时间维做累积,再调用torch.nn.functional.scaled_dot_product_attention(),最后返回 累积输出在时间维上的差分。step_mode="s"时输入被解释为当前差分 时间步,模块更新内部累积 memory 并返回当前差分输出;普通 SDPA 路径 由ann_forward()提供。返回值是浮点差分值,可能包含负值;它不是二值脉冲,也不表示 fully spike-driven attention。dtype、device 与 mask broadcast 语义遵循
torch.nn.functional.scaled_dot_product_attention();推荐使用float32、float16、bfloat16或float64输入。该算子 完全由 PyTorch 可微算子组成,对 autograd 透明。该算子是 stateful TD MemoryModule;重复处理独立序列前应调用reset。该算子仅依赖 PyTorch SDPA,支持 CPU 与 CUDA,后端与torch一致,无 CuPy / Triton 专用路径。该算子的机制来源于 SpikeZIP-TF: Conversion is All You Need for Transformer-based SNN 中对 Transformer 算子的累积-差分等价转换思路。本文档中的 TD scaled dot-product attention 只实现张量级最小 primitive:在多步模式下它仍 调用 PyTorch SDPA,需要完整时间序列输入,不是逐时间步在线算子,也 不是面向神经形态硬件的 fully spike-driven attention。本实现固定
dropout_p=0.0,且不暴露enable_gqa。组合 TD Transformer block 时,普通带 bias 的torch.nn.Linear不能直接作用在差分 序列上,因为累计后 bias 会被重复累加;应使用bias=False或专门的 TD Linear。op = TDScaledDotProductAttention() q_seq = torch.randn(4, 2, 3, 8) k_seq = torch.randn(4, 2, 5, 8) v_seq = torch.randn(4, 2, 5, 6) y_seq = op(q_seq, k_seq, v_seq)
- 参数:
English
Temporal-difference (TD) scaled dot-product attention operator. With
step_mode="m", the inputs must be complete time sequences whose time dimension is fixed at dimension 0.query_seqhas shape[T, ..., L, E],key_seqhas shape[T, ..., S, E], andvalue_seqhas shape[T, ..., S, Ev]. This module first accumulates query, key, and value over time, callstorch.nn.functional.scaled_dot_product_attention(), and returns the temporal difference of the cumulative outputs. Withstep_mode="s", the inputs are interpreted as the current differential time step; the module updates its cumulative memory and returns the current differential output. The ordinary SDPA path is exposed byann_forward().The output contains floating-point differential values and may contain negative values. It is not a binary spike tensor and does not represent fully spike-driven attention. Dtype, device, and mask broadcasting follow
torch.nn.functional.scaled_dot_product_attention();float32,float16,bfloat16andfloat64inputs are recommended. The operator is composed entirely of differentiable PyTorch operations and is transparent to autograd. The operator is a stateful TD MemoryModule; callresetbefore processing an independent sequence. It only depends on PyTorch SDPA, supports CPU and CUDA, follows thetorchbackend behavior, and has no CuPy / Triton specific path.The mechanism follows the cumulative-difference equivalence idea for Transformer operators in SpikeZIP-TF: Conversion is All You Need for Transformer-based SNN. This implementation provides only a tensor-level minimal primitive: in multi-step mode it still calls PyTorch SDPA, requires a complete time sequence, is not a step-wise online operator, and is not fully spike-driven attention for neuromorphic hardware. This implementation fixes
dropout_p=0.0and does not exposeenable_gqa. When composing TD Transformer blocks, ordinarytorch.nn.Linearlayers with bias must not be applied directly to differential sequences, because the bias would be accumulated repeatedly; usebias=Falseor a dedicated TD Linear.op = TDScaledDotProductAttention() q_seq = torch.randn(4, 2, 3, 8) k_seq = torch.randn(4, 2, 5, 8) v_seq = torch.randn(4, 2, 5, 6) y_seq = op(q_seq, k_seq, v_seq)
- 参数:
- multi_step_forward(query_seq, key_seq, value_seq, attn_mask=None)[源代码]#
API Language
中文
对完整 query、key、value 时间序列执行 TD scaled dot-product attention。计算过程为:
\[Q_{cum}[t] = \sum_{i=0}^{t} Q[i], \quad K_{cum}[t] = \sum_{i=0}^{t} K[i], \quad V_{cum}[t] = \sum_{i=0}^{t} V[i]\]\[Y_{cum}[t] = \operatorname{SDPA}(Q_{cum}[t], K_{cum}[t], V_{cum}[t])\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]因此
Y.cumsum(dim=0)与对累积 query、key、value 逐时间步执行 ANN SDPA 的结果一致。输出是浮点差分值,可能为负,不是二值脉冲。当T = 1时,Y[0]直接等于对第一步 query、key、value 执行 SDPA 的结果。输出 dtype 与 PyTorch SDPA 一致,且该算子对 autograd 透明。- 参数:
- 返回:
TD scaled dot-product attention 差分序列,形状为
[T, ..., L, Ev]。- 返回类型:
- 抛出:
ValueError -- 若任一输入少于 3 维、时间维为空、三者时间维长度不一致, 或
is_causal=True时同时传入attn_mask。
English
Apply TD scaled dot-product attention to complete query, key, and value time sequences:
\[Q_{cum}[t] = \sum_{i=0}^{t} Q[i], \quad K_{cum}[t] = \sum_{i=0}^{t} K[i], \quad V_{cum}[t] = \sum_{i=0}^{t} V[i]\]\[Y_{cum}[t] = \operatorname{SDPA}(Q_{cum}[t], K_{cum}[t], V_{cum}[t])\]\[Y[0] = Y_{cum}[0], \quad Y[t] = Y_{cum}[t] - Y_{cum}[t-1]\]Thus,
Y.cumsum(dim=0)matches ANN SDPA applied to cumulative query, key, and value at each time step. The output contains floating-point differential values, may be negative, and is not a binary spike tensor. WhenT = 1,Y[0]is exactly SDPA applied to the first query, key, and value step. The output dtype follows PyTorch SDPA, and the operator is transparent to autograd.- 参数:
query_seq (Tensor) -- Query time sequence with shape
[T, ..., L, E]andT > 0.key_seq (Tensor) -- Key time sequence with shape
[T, ..., S, E]. Its time dimension length must matchquery_seq.value_seq (Tensor) -- Value time sequence with shape
[T, ..., S, Ev]. Its time dimension length must matchquery_seq.attn_mask (Tensor or None) -- Attention mask with the same broadcast semantics as PyTorch SDPA.
- 返回:
TD scaled dot-product attention differential sequence with shape
[T, ..., L, Ev].- 返回类型:
- 抛出:
ValueError -- If any input has fewer than 3 dimensions, any time dimension is empty, the time lengths differ, or
attn_maskis passed whenis_causal=True.
- class spikingjelly.activation_based.ann2snn.operators.TDMultiheadAttention(embed_dim, num_heads, dropout=0.0, bias=True, batch_first=True, device=None, dtype=None, step_mode='m')[源代码]#
基类:
TDModule
中文
Temporal-difference (TD) MultiheadAttention 的窄子集实现。
step_mode="m"时输入必须是完整时间序列,时间维固定为第 0 维, 形状为[T, batch, seq, embed_dim];该模块使用TDLinear生成 q/k/v projection,执行 TD scaled dot-product attention,再用TDLinear执行输出 projection。step_mode="s"时输入被解释为 当前差分时间步,形状为[batch, seq, embed_dim],模块更新内部累积 memory 并返回当前差分输出;普通 MultiheadAttention 数值路径由ann_forward()提供。返回值是
(attn_output_seq, None),用于匹配torch.nn.MultiheadAttention在need_weights=False时的 tuple 返回结构。输出是浮点差分值,不是二值脉冲,也不是 fully spike-driven attention。输出 dtype 跟随 PyTorch Linear / SDPA; 推荐使用float32、float16、bfloat16或float64输入。 该算子完全由 PyTorch 可微算子组成,对 autograd 透明。该算子是 stateful TD MemoryModule;重复处理独立序列前应调用reset;支持 CPU 与 CUDA, 后端与torch一致,无 CuPy / Triton 专用路径。当前只支持dropout=0.0、batch_first=True和need_weights=False。该算子的机制来源于 SpikeZIP-TF: Conversion is All You Need for Transformer-based SNN 中的 累积-差分等价转换思路。本实现是窄子集 TD wrapper,仍使用浮点
TDLinear和 PyTorch SDPA,不是逐时间步在线 attention,也不是面向 神经形态硬件的 fully spike-driven MultiheadAttention。bias=True时 projection bias 由TDLinear在累积输入上处理,避免普通nn.Linear直接作用在差分序列时产生重复累计 bias。 父模块的step_mode会同步到内部 q/k/v/out projection。常规forward调用由父模块的step_mode分发;直接调用single_step_forward或multi_step_forward时,父模块会显式调用内部 projection 的对应 step 方法,而不依赖子模块当前step_mode。op = TDMultiheadAttention(embed_dim=8, num_heads=2) x_seq = torch.randn(4, 2, 5, 8) y_seq, weights = op(x_seq, x_seq, x_seq, need_weights=False)
- 参数:
embed_dim (int) -- 输入和输出 embedding 维度。
num_heads (int) -- attention head 数量,必须整除
embed_dim。dropout (float) -- attention dropout。当前必须为
0.0。bias (bool) -- 若为
True,q/k/v 和 out projection 使用 bias。batch_first (bool) -- 当前必须为
True,即每个时间步的输入形状为[batch, seq, embed_dim]。dtype (dtype or None) -- 参数初始化 dtype。
step_mode (str) -- 步进模式,
"s"或"m"。默认"m"。
- 抛出:
ValueError -- 若
embed_dim不能被num_heads整除、或传入 当前不支持的dropout/batch_first。
English
Narrow temporal-difference (TD) MultiheadAttention implementation. With
step_mode="m", the input must be a complete time sequence whose time dimension is fixed at dimension 0, with shape[T, batch, seq, embed_dim]. This module usesTDLinearfor q/k/v projections, applies TD scaled dot-product attention, and then applies aTDLinearoutput projection. Withstep_mode="s", the input is interpreted as the current differential time step with shape[batch, seq, embed_dim]; the module updates its cumulative memory and returns the current differential output. The ordinary MultiheadAttention numeric path is exposed byann_forward().The return value is
(attn_output_seq, None)to match the tuple structure oftorch.nn.MultiheadAttentionwhenneed_weights=False. The output contains floating-point differential values, is not a binary spike tensor, and is not fully spike-driven attention. The output dtype follows PyTorch Linear / SDPA;float32,float16,bfloat16andfloat64inputs are recommended. The operator is composed entirely of differentiable PyTorch operations and is transparent to autograd. The operator is a stateful TD MemoryModule; callresetbefore processing an independent sequence. It supports CPU and CUDA, follows thetorchbackend behavior, and has no CuPy / Triton specific path. Currently onlydropout=0.0,batch_first=Trueandneed_weights=Falseare supported.The mechanism follows the cumulative-difference equivalence idea in SpikeZIP-TF: Conversion is All You Need for Transformer-based SNN. This implementation is a narrow TD wrapper: it still uses floating-point
TDLinearand PyTorch SDPA, is not step-wise online attention, and is not fully spike-driven MultiheadAttention for neuromorphic hardware. Whenbias=True, projection biases are handled byTDLinearon cumulative inputs, avoiding the repeated bias accumulation that would occur if ordinarynn.Linearwere applied directly to differential sequences. The parent module'sstep_modeis synchronized to the internal q/k/v/out projections. Regularforwardcalls are dispatched by the parentstep_mode; whensingle_step_forwardormulti_step_forwardis called directly, the parent explicitly invokes the matching child projection step method instead of depending on the child modules' currentstep_mode.op = TDMultiheadAttention(embed_dim=8, num_heads=2) x_seq = torch.randn(4, 2, 5, 8) y_seq, weights = op(x_seq, x_seq, x_seq, need_weights=False)
- 参数:
embed_dim (int) -- Input and output embedding dimension.
num_heads (int) -- Number of attention heads. Must divide
embed_dim.dropout (float) -- Attention dropout. It must be
0.0currently.bias (bool) -- If
True, use bias in q/k/v and output projections.batch_first (bool) -- Must be
Truecurrently. Each time step has shape[batch, seq, embed_dim].device (device or str or None) -- Device used to initialize parameters.
dtype (dtype or None) -- Dtype used to initialize parameters.
step_mode (str) -- Step mode,
"s"or"m". The default is"m".
- 抛出:
ValueError -- If
embed_dimis not divisible bynum_heads, or unsupporteddropout/batch_firstis passed.
- property step_mode: str#
-
中文
- 返回:
模块当前使用的步进模式
- 返回类型:
English
- 返回:
the current step mode of this module
- 返回类型:
- ann_forward(query, key, value, key_padding_mask=None, need_weights=False, attn_mask=None, average_attn_weights=True, is_causal=False)[源代码]#
- single_step_forward(query, key, value, key_padding_mask=None, need_weights=False, attn_mask=None, average_attn_weights=True, is_causal=False)[源代码]#
- multi_step_forward(query_seq, key_seq, value_seq, key_padding_mask=None, need_weights=False, attn_mask=None, average_attn_weights=True, is_causal=False)[源代码]#
-
中文
对完整 query/key/value 时间序列执行 TD multi-head attention。输入形状 为
[T, batch, seq, embed_dim],且T > 0。当need_weights=False时返回(attn_output_seq, None)。输出是浮点 差分值,且attn_output_seq.cumsum(dim=0)与对累积输入逐时间步执行 支持子集内的 ANN MultiheadAttention 输出一致。当T = 1时,attn_output_seq[0]等于支持子集内 ANN MultiheadAttention 对第一步 输入的输出。输出 dtype 与 PyTorch Linear / SDPA 一致,且该算子对 autograd 透明。- 参数:
query_seq (Tensor) -- query 时间序列,形状为
[T, batch, target_len, embed_dim]。key_seq (Tensor) -- key 时间序列,形状为
[T, batch, source_len, embed_dim]。value_seq (Tensor) -- value 时间序列,形状为
[T, batch, source_len, embed_dim]。key_padding_mask (Tensor or None) -- 当前不支持,必须为
None。need_weights (bool) -- 当前必须为
False。attn_mask (Tensor or None) -- attention mask,语义与
torch.nn.MultiheadAttention一致;bool mask 中True表示禁止 attention。average_attn_weights (bool) -- 为兼容
torch.nn.MultiheadAttention调用签名保留;由于当前不返回 attention weights,必须为True。is_causal (bool) -- 是否应用 causal attention mask。
- 返回:
(attn_output_seq, None),其中attn_output_seq形状为[T, batch, target_len, embed_dim]。- 返回类型:
Tuple[Tensor, None]
- 抛出:
ValueError -- 若传入不支持的 mask/options 或非法输入形状。
English
Apply TD multi-head attention to complete query/key/value time sequences. Inputs have shape
[T, batch, seq, embed_dim]withT > 0. Whenneed_weights=False, this method returns(attn_output_seq, None). The output contains floating-point differential values, andattn_output_seq.cumsum(dim=0)matches ANN MultiheadAttention in the supported subset applied to cumulative inputs at each time step. WhenT = 1,attn_output_seq[0]equals the output of ANN MultiheadAttention in the supported subset applied to the first input step. The output dtype follows PyTorch Linear / SDPA, and the operator is transparent to autograd.- 参数:
query_seq (Tensor) -- Query sequence with shape
[T, batch, target_len, embed_dim]andT > 0.key_seq (Tensor) -- Key sequence with shape
[T, batch, source_len, embed_dim].value_seq (Tensor) -- Value sequence with shape
[T, batch, source_len, embed_dim].key_padding_mask (Tensor or None) -- Unsupported in this narrow implementation.
need_weights (bool) -- Must be
False. Attention weights are not implemented.attn_mask (Tensor or None) -- Optional attention mask with the same semantics as
torch.nn.MultiheadAttention;Truevalues in a bool mask disallow attention.average_attn_weights (bool) -- Kept for
torch.nn.MultiheadAttentionsignature compatibility. It must beTruebecause attention weights are not returned.is_causal (bool) -- Whether to apply causal masking.
- 返回:
(attn_output_seq, None)whereattn_output_seqhas shape[T, batch, target_len, embed_dim].- 返回类型:
Tuple[Tensor, None]
- 抛出:
ValueError -- If unsupported masks/options or invalid shapes are passed.
- class spikingjelly.activation_based.ann2snn.modules.VoltageHook(scale=1.0, momentum=0.1, mode='Max')[源代码]#
基类:
Module
中文
VoltageHook的构造函数。- 参数:
English
Constructor of
VoltageHook.- 参数:
- class spikingjelly.activation_based.ann2snn.modules.VoltageScaler(scale=1.0, step_mode='s')[源代码]#
基类:
Module,StepModule
中文
VoltageScaler的构造函数。用于SNN推理中缩放电流。
English
Constructor of
VoltageScaler. Used for scaling current in SNN inference.- 参数:
- class spikingjelly.activation_based.ann2snn.modules.ChannelVoltageScaler(scale=1.0, channel_dim=1, step_mode='s')[源代码]#
基类:
Module,StepModule
中文
按通道缩放输入电流。
scale可以是标量或 1D 张量;当为 1D 张量时, 会沿channel_dim广播到输入张量。该模块用于需要 channel-wise 阈值/尺度的 ANN2SNN 转换 recipe。- 参数:
- 抛出:
ValueError -- 当
scale或channel_dim非法时抛出。
English
Scale input current channel-wise.
scalecan be a scalar or a 1D tensor; a 1D tensor is broadcast to the input tensor alongchannel_dim. This module is used by ANN2SNN recipes that need channel-wise thresholds or scales.- 参数:
- 抛出:
ValueError -- If
scaleorchannel_dimis invalid.
Utilities#
- spikingjelly.activation_based.ann2snn.utils.download_url(url, dst)[源代码]#
-
中文
从指定 URL 下载文件并保存到目标路径。支持断点续传。
- 参数:
- 返回:
文件的总大小(以字节为单位)。若服务器没有返回
content-length,则返回实际下载的字节数。- 返回类型:
- 抛出:
RuntimeError -- 当服务器响应不符合断点续传要求,或实际接收字节数与声明长度不一致时抛出
English
Download a file from a given URL and save it to a destination path. Supports resuming interrupted downloads.
- 参数:
- 返回:
the total file size in bytes. If the server does not return
content-length, this function returns the actually downloaded byte count.- 返回类型:
- 抛出:
RuntimeError -- Raised when the server response is invalid for resume, or when the received byte count does not match the declared length