From 7ab204861fde0e1f6336e8335824d31767800baf Mon Sep 17 00:00:00 2001 From: Chen Cheng <85005591+ischencheng@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:01:40 -0500 Subject: [PATCH 1/2] feat(moe): serve inkling 2 mini under --moe-strategy hybrid and cpu --- python/freetoken/engine/engine.py | 30 +++++--- python/freetoken/kernel/csrc/cpu_moe/common.h | 3 + .../kernel/csrc/cpu_moe/cpu_moe_ext.cpp | 2 +- python/freetoken/kernel/csrc/cpu_moe/format.h | 6 +- python/freetoken/moe/cpu_executor.py | 1 + python/freetoken/moe/pool_policy.py | 13 ++-- tests/moe/test_mixed_expert_formats.py | 70 ++++++++++++------- 7 files changed, 84 insertions(+), 41 deletions(-) diff --git a/python/freetoken/engine/engine.py b/python/freetoken/engine/engine.py index 9b8930b882..9fdb3529ea 100644 --- a/python/freetoken/engine/engine.py +++ b/python/freetoken/engine/engine.py @@ -851,10 +851,10 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache: layer_methods = offload_layer_methods(self.model) if not is_mixed(layer_methods): layer_methods = None - elif config.moe_strategy == "cpu" or config.moe_cpu_layers: + elif config.moe_cpu_layers: raise ValueError( "this model's experts come in several formats, which are served from per-format GPU slot pools; " - "they do not combine with --moe-strategy cpu or --moe-cpu-layers (use offload or hybrid)" + "they do not combine with --moe-cpu-layers (use offload, hybrid or cpu)" ) # Fast path: an FTW checkpoint loads its repacked banks directly. # Slow path: load_expert_banks auto-picks parallel vs serial baseline by @@ -875,7 +875,9 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache: reserved = self._host_tables_bytes + staging_reserve(config, lambda: _bank_bytes(config, method, layer_methods)) cpu_layer_ids = _resolve_cpu_layers(config, num_moe_layers, reserved=reserved, method=method) _check_pin_budget(config, reserved=reserved, method=method, layer_methods=layer_methods) - decode_target, split_residency = self._residency_split(config, cpu_layer_ids, method, capped=_pin_budget_bytes(reserved) is not None) + decode_target, split_residency = self._residency_split( + config, cpu_layer_ids, method, capped=_pin_budget_bytes(reserved) is not None, layer_methods=layer_methods + ) requested_residency = None if split_residency: from freetoken.moe.host_banks import HostResidency @@ -918,7 +920,9 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache: if locked_fetch: # a locked refill costs a staged copy: place the locked pools after the pinned ones, which hold the prefill staging when they are big enough self._moe_pool_groups.sort(key=lambda layers: layers[0] in cpu_layer_ids) - if len(self._moe_pool_groups) > 1 and cpu_layer_ids and not locked_fetch: + # --moe-strategy cpu decodes no layer from the slots, which only back the prefill staging (sized below) + staging_only = config.moe_strategy == "cpu" and config.moe_cache_scope == "unified" + if len(self._moe_pool_groups) > 1 and cpu_layer_ids and not locked_fetch and not staging_only: raise ValueError( "several MoE slot pools (--moe-cache-scope per-layer, or experts in several quant formats) need every MoE " "layer to decode from the GPU slot cache; they combine with --moe-cpu-layers only for locked layers under " @@ -966,6 +970,11 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache: f"--moe-cache-mem {mem_GB(config.moe_cache_mem)} resolved moe_cache_size={size} " f"({per_slot / 2**20:.2f} MiB per slot, prefill_overlap={overlap})" ) + if staging_only and len(pools) > 1: + # 2 * num_experts slots split over the pools leave a bank short of two layers of its widest format + size = stage_floor(layer_bank_bytes(banks.sources), pools, config.model_config.num_experts, self._moe_expert_counts, buffers=2) + object.__setattr__(config, "moe_cache_size", max(config.moe_cache_size, size)) + logger.info_rank0(f"MoE backend 'cpu': {len(pools)} slot pools, prefill double buffer of moe_cache_size={config.moe_cache_size}") _require_offload_cache_size(config.moe_cache_size, config.model_config.num_experts) pool_sizes = split_slots(config.moe_cache_size, pools, self._moe_expert_counts) if len(pools) > 1: @@ -1034,7 +1043,7 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache: self.moe_offload_cache = cache return cache - def _residency_split(self, config: EngineConfig, cpu_layer_ids, method, *, capped: bool): + def _residency_split(self, config: EngineConfig, cpu_layer_ids, method, *, capped: bool, layer_methods=None): """(decode_target, split_residency) for a CPU-layer set; turns prefill overlap off when some layers stay unpinned.""" # the kernels were picked for model_config.decode_target; --moe-cpu-layers auto may still find that every bank fits the pin budget decode_target = config.model_config.decode_target @@ -1050,13 +1059,16 @@ def _residency_split(self, config: EngineConfig, cpu_layer_ids, method, *, cappe ) if config.moe_strategy == "cpu" and not split_residency: # cpu mode pins every bank for the prefill double buffer; over the pin cap that dies in cudaHostRegister, so lock everything instead - from freetoken.moe.expert_banks import bank_bytes_estimate, ftw_bank_bytes - budget = _pin_budget_bytes(self._host_tables_bytes) bank_bytes = None if budget is not None: - bank_bytes = ftw_bank_bytes(config.model_path) or bank_bytes_estimate(config.model_config, method) + bank_bytes = _bank_bytes(config, method, layer_methods) if bank_bytes and bank_bytes > budget: + if layer_methods is not None: + raise ValueError( + f"--moe-strategy cpu: the expert banks ({bank_bytes / 2**30:.2f} GiB) exceed this host's pin budget, and " + "experts of several formats cannot be OS-locked instead" + ) split_residency = True logger.info_rank0( f"--moe-strategy cpu: banks {bank_bytes / 2**30:.2f} GiB exceed the " @@ -1764,7 +1776,7 @@ def _decode_target(config: EngineConfig) -> str: # expert activations the CPU MoE executor supports (csrc ActKind) _CPU_MOE_ACTS = ( "silu", "swish", "gelu", "gelu_tanh", "gelu_pytorch_tanh", "swigluoai", - "swiglu_clamp", + "swiglu_clamp", "softcap_swiglu", ) diff --git a/python/freetoken/kernel/csrc/cpu_moe/common.h b/python/freetoken/kernel/csrc/cpu_moe/common.h index 0edee0150a..612cff2fd4 100644 --- a/python/freetoken/kernel/csrc/cpu_moe/common.h +++ b/python/freetoken/kernel/csrc/cpu_moe/common.h @@ -66,12 +66,15 @@ inline bf16_t f32_to_bf16(float f) { // the mxfp4 kernel additionally fuses its own copy of the same math). // ACT_SWIGLU_CLAMP (GLM-5.3 "swiglu_limit") is the same clamped form WITHOUT // the (up + 1) bias: clamp(gate, max=lim) * sigmoid(alpha*gate) * clamp(up, +-lim). +// ACT_SOFTCAP_SWIGLU (Inkling 2) caps with tanh instead and the sigmoid sees the raw gate: +// alpha*tanh(gate/alpha) * sigmoid(gate) * lim*tanh(up/lim). enum ActKind { ACT_SILU = 0, ACT_GELU = 1, ACT_GELU_TANH = 2, ACT_SWIGLUOAI = 3, ACT_SWIGLU_CLAMP = 4, + ACT_SOFTCAP_SWIGLU = 5, }; inline float act_apply(int act, float x) { diff --git a/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp index 31d5224923..6366089542 100644 --- a/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp +++ b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp @@ -645,7 +645,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { // accepts id 3 without error and silently computes the wrong activation // (act_apply falls through to gelu_tanh); the probe turns a stale extension // into a loud rebuild instruction instead of wrong model outputs. - m.def("max_generic_act_id", []() { return static_cast(freetoken::cpu_moe::ACT_SWIGLU_CLAMP); }); + m.def("max_generic_act_id", []() { return static_cast(freetoken::cpu_moe::ACT_SOFTCAP_SWIGLU); }); // The ggml-cpu variant the gguf format calls: the kernel table address that freetoken.kernel.ggml_cpu.select() returns. m.def("set_ggml_cpu", &freetoken::cpu_moe::set_ggml_cpu, py::arg("api")); m.def("weight_formats", []() { diff --git a/python/freetoken/kernel/csrc/cpu_moe/format.h b/python/freetoken/kernel/csrc/cpu_moe/format.h index 1c4ffa41a0..84ecbae36d 100644 --- a/python/freetoken/kernel/csrc/cpu_moe/format.h +++ b/python/freetoken/kernel/csrc/cpu_moe/format.h @@ -76,7 +76,7 @@ struct DownRoute { }; // g[i] for i in [i0, i1) from the gate row i and the up row I + i; dot(row) is the row's GEMV. -// ACT_SWIGLUOAI and ACT_SWIGLU_CLAMP clamp both inputs; the other kinds go through act_apply. +// ACT_SWIGLUOAI and ACT_SWIGLU_CLAMP clamp both inputs, ACT_SOFTCAP_SWIGLU tanh-caps them; the other kinds go through act_apply. template inline void gated_rows(const MoeParams& p, int i0, int i1, float w_in, bf16_t* g, RowDot dot) { const bool clamped = p.act == ACT_SWIGLUOAI || p.act == ACT_SWIGLU_CLAMP; @@ -86,7 +86,9 @@ inline void gated_rows(const MoeParams& p, int i0, int i1, float w_in, bf16_t* g // gate = row i, up = row I+i float gate = dot(i) * w_in; float up = dot(p.I + i) * w_in; - if (clamped) { + if (p.act == ACT_SOFTCAP_SWIGLU) { + g[i] = f32_to_bf16(alpha * std::tanh(gate / alpha) / (1.0f + std::exp(-gate)) * (lim * std::tanh(up / lim))); + } else if (clamped) { // clamp(gate, max=lim) * sigmoid(alpha * gate) * (clamp(up, +-lim) + up_bias) // -- swigluoai carries the +1 up bias (gpt-oss/MiniMax); swiglu_clamp // (GLM-5.3) does not. lim == +inf: no clamp. diff --git a/python/freetoken/moe/cpu_executor.py b/python/freetoken/moe/cpu_executor.py index a168256678..e57e770c09 100644 --- a/python/freetoken/moe/cpu_executor.py +++ b/python/freetoken/moe/cpu_executor.py @@ -65,6 +65,7 @@ "gpt_oss_swiglu": 3, "swigluoai": 3, "swiglu_clamp": 4, + "softcap_swiglu": 5, } diff --git a/python/freetoken/moe/pool_policy.py b/python/freetoken/moe/pool_policy.py index f31b3c2b68..547d7b6dd6 100644 --- a/python/freetoken/moe/pool_policy.py +++ b/python/freetoken/moe/pool_policy.py @@ -80,11 +80,14 @@ def split_slots(total: int, pools: list[PoolSpec], counts: torch.Tensor | None = return _split_equal(total, pools) if counts is None else _split_hot(total, pools, counts) -def stage_floor(layer_rows: list[list[int]], pools: list[PoolSpec], num_experts: int, counts: torch.Tensor | None = None) -> int: - """Fewest slots whose split gives every bank the bytes to stage one whole layer of its widest rows, as the offload - cache's shared bank bytes must (``layer_rows[l][k]``: one expert's bytes of bank k in layer l); the pools' room when - no size does. Row padding is left out: the cache adds the largest pad to both sides of that check.""" - widest = [num_experts * max(rows[k] for rows in layer_rows) for k in range(len(layer_rows[0]))] +def stage_floor( + layer_rows: list[list[int]], pools: list[PoolSpec], num_experts: int, counts: torch.Tensor | None = None, buffers: int = 1, +) -> int: + """Fewest slots whose split gives every bank the bytes to stage ``buffers`` whole layers of its widest rows, as the + offload cache's shared bank bytes must (``layer_rows[l][k]``: one expert's bytes of bank k in layer l); the pools' + room when no size does. Row padding is left out: a bank also holds each pool's pad and the largest one, which + covers the pads of one or two buffers.""" + widest = [buffers * num_experts * max(rows[k] for rows in layer_rows) for k in range(len(layer_rows[0]))] def fits(total: int) -> bool: sizes = split_slots(total, pools, counts) diff --git a/tests/moe/test_mixed_expert_formats.py b/tests/moe/test_mixed_expert_formats.py index 078f5093cf..5e5033e332 100644 --- a/tests/moe/test_mixed_expert_formats.py +++ b/tests/moe/test_mixed_expert_formats.py @@ -20,6 +20,8 @@ E, H, I, TOPK = 8, 256, 128, 2 FORMATS = ["bf16", "nvfp4", "nvfp4", "nvfp4", "bf16", "mxfp8"] L = len(FORMATS) +# (alpha, limit) per expert activation; softcap_swiglu's caps are ones the test inputs reach +ACTS = {"silu": (1.0, None), "softcap_swiglu": (1.5, 6.0)} _E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0]) @@ -29,7 +31,7 @@ def _init_tp(): set_tp_info(rank=0, size=1) -def _layer(layer_id: int, fmt: str): +def _layer(layer_id: int, fmt: str, act: str = "silu"): from freetoken.layers.moe import OffloadMoELayer from freetoken.layers.quantization import NoQuantConfig, QuantBackend, QuantConfig, set_quant_backend @@ -41,7 +43,10 @@ def _layer(layer_id: int, fmt: str): else: set_quant_backend(QuantBackend.parse("moe.nvfp4=triton")) quant = QuantConfig.from_hf({"quantization_config": {"quant_method": "modelopt", "quant_algo": "NVFP4", "ignore": ["lm_head"]}}) - return OffloadMoELayer(layer_id, E, TOPK, H, I, quant_config=quant, prefix=f"model.layers.{layer_id}.mlp.experts") + alpha, limit = ACTS[act] + return OffloadMoELayer( + layer_id, E, TOPK, H, I, activation=act, alpha=alpha, limit=limit, quant_config=quant, prefix=f"model.layers.{layer_id}.mlp.experts" + ) def _dequant(packed, scale, row_global): @@ -102,15 +107,22 @@ def _weights(pieces, layer): return gu, dn -def _reference(pieces, layer, hidden, weights, ids): +def _gated(h, act): + gate, up = h[:I], h[I:] + if act == "silu": + return torch.nn.functional.silu(gate) * up + alpha, limit = ACTS[act] + return alpha * torch.tanh(gate / alpha) * torch.sigmoid(gate) * limit * torch.tanh(up / limit) + + +def _reference(pieces, layer, hidden, weights, ids, act="silu"): gu, dn = _weights(pieces, layer) out = torch.zeros(hidden.shape, dtype=torch.float32) x = hidden.float().cpu() for t in range(hidden.shape[0]): for k in range(ids.shape[1]): e = int(ids[t, k]) - h = gu[e] @ x[t] - out[t] += float(weights[t, k]) * (dn[e] @ (torch.nn.functional.silu(h[:I]) * h[I:])) + out[t] += float(weights[t, k]) * (dn[e] @ _gated(gu[e] @ x[t], act)) return out @@ -118,10 +130,10 @@ def _assert_close(out, ref): torch.testing.assert_close(out.float().cpu(), ref, rtol=3e-2, atol=0.03 * float(ref.abs().max())) -def _mixed_banks(pieces, device, layer_sink=None): +def _mixed_banks(pieces, device, layer_sink=None, act="silu"): from freetoken.moe.expert_banks import build_expert_banks, merge_expert_banks, method_groups - methods = [_layer(layer, fmt).quant_method for layer, fmt in enumerate(FORMATS)] + methods = [_layer(layer, fmt, act).quant_method for layer, fmt in enumerate(FORMATS)] parts = [ build_expert_banks(method, L, _reader(pieces, method.kind), device=device, layer_sink=layer_sink, layers=layers) for method, layers in method_groups(methods) @@ -129,12 +141,12 @@ def _mixed_banks(pieces, device, layer_sink=None): return merge_expert_banks(parts, methods, E), methods -def _mixed_cache(device, pieces, *, decode_target="gpu", prefill_overlap=False): +def _mixed_cache(device, pieces, *, decode_target="gpu", prefill_overlap=False, act="silu"): from freetoken.moe.offload_cache import OffloadMoeCache, bank_layouts from freetoken.moe.pool_policy import group_layers, make_pools, pool_of_layer, split_slots from freetoken.engine.cache_budget import layer_slot_bytes - banks, methods = _mixed_banks(pieces, device) + banks, methods = _mixed_banks(pieces, device, act=act) slot_bytes = layer_slot_bytes(banks.sources) groups = group_layers("unified", bank_layouts(banks.sources, banks.layer_tags), slot_bytes) pools = make_pools(groups, E, TOPK, None) @@ -146,7 +158,7 @@ def _mixed_cache(device, pieces, *, decode_target="gpu", prefill_overlap=False): ) cache.set_bank_sources(banks.sources, layer_tags=banks.layer_tags) cache.reset() - layers = [_layer(layer, fmt) for layer, fmt in enumerate(FORMATS)] + layers = [_layer(layer, fmt, act) for layer, fmt in enumerate(FORMATS)] for layer in layers: layer.offload_cache = cache return cache, layers, banks @@ -253,8 +265,10 @@ def test_mixed_layers_decode_and_prefill_through_their_pools(): @cuda -def test_the_planned_floor_is_the_fewest_slots_that_stage_a_layer(): - # the nvfp4 scale banks hold bytes that cannot stage bf16 weight rows, so the floor is per bank, not per slot +@pytest.mark.parametrize("buffers", [1, 2]) +def test_the_planned_floor_is_the_fewest_slots_that_stage_a_layer(buffers): + # the nvfp4 scale banks hold bytes that cannot stage bf16 weight rows, so the floor is per bank, not per slot; + # two buffers are --moe-strategy cpu's prefill double buffer from freetoken.engine.cache_budget import layer_bank_bytes, layer_slot_bytes from freetoken.moe.offload_cache import OffloadMoeCache, bank_layouts from freetoken.moe.pool_policy import group_layers, make_pools, pool_of_layer, split_slots, stage_floor @@ -265,47 +279,55 @@ def test_the_planned_floor_is_the_fewest_slots_that_stage_a_layer(): rows = layer_bank_bytes(banks.sources) # expert use that sends every slot past the minimums to the nvfp4 pool counts = torch.tensor([[0.0 if fmt == "bf16" else 1.0] * E for fmt in FORMATS]) - floor = stage_floor(rows, pools, E, counts) + floor = stage_floor(rows, pools, E, counts, buffers=buffers) def build(size): cache = OffloadMoeCache( num_layers=L, num_experts=E, cache_size=size, device=device, quant_format=banks.quant_format, - decode_target="gpu", hybrid_max_fetch=1, prefill_overlap=False, + decode_target="gpu", hybrid_max_fetch=1, prefill_overlap=buffers == 2, layer_layouts=[m.layout() for m in methods], pool_of_layer=pool_of_layer(pools, L), pool_sizes=split_slots(size, pools, counts), ) cache.set_bank_sources(banks.sources, layer_tags=banks.layer_tags) + return cache - build(floor) - with pytest.raises(ValueError, match="cannot stage one whole layer"): - build(floor - 1) + if buffers == 1: + build(floor) + with pytest.raises(ValueError, match="cannot stage one whole layer"): + build(floor - 1) + else: + # one slot short of the floor, the cache turns the overlap off + assert build(floor).prefill_overlap and not build(floor - 1).prefill_overlap @cuda -def test_cpu_executor_computes_each_layer_in_its_format(): +@pytest.mark.parametrize("act", list(ACTS)) +def test_cpu_executor_computes_each_layer_in_its_format(act): pytest.importorskip("freetoken.kernel._cpu_moe") from freetoken.moe.cpu_executor import CpuMoeExecutor torch.manual_seed(1) device = torch.device("cuda") pieces = _pieces(seed=1) - cache, layers, _ = _mixed_cache(device, pieces, decode_target="hybrid") + cache, layers, _ = _mixed_cache(device, pieces, decode_target="hybrid", act=act) + alpha, limit = ACTS[act] ex = CpuMoeExecutor( - cache, top_k=TOPK, activation="silu", apply_router_weight_on_input=False, num_threads=2, - max_tokens=4, device=device, layer_formats=[(f, {}) for f in FORMATS], + cache, top_k=TOPK, activation=act, apply_router_weight_on_input=False, num_threads=2, + max_tokens=4, device=device, swiglu_alpha=alpha, swiglu_limit=limit, layer_formats=[(f, {}) for f in FORMATS], ) cache.set_cpu_executor(ex) bs = 3 - hidden = torch.randn(bs, H, dtype=torch.bfloat16, device=device) / 4 + # softcap_swiglu: large enough that the gate and up rows reach past the caps + hidden = torch.randn(bs, H, dtype=torch.bfloat16, device=device) * (4 if act == "softcap_swiglu" else 0.25) weights = torch.rand(bs, TOPK, device=device) for layer in range(L): ids = torch.stack([torch.randperm(E)[:TOPK] for _ in range(bs)]).to(torch.int32) - _assert_close(ex.decode(layer, hidden, weights, ids.to(device)), _reference(pieces, layer, hidden, weights, ids)) + _assert_close(ex.decode(layer, hidden, weights, ids.to(device)), _reference(pieces, layer, hidden, weights, ids, act)) # hybrid: capped PCIe fetch on the GPU, the overflow misses on the CPU, per layer format for _ in range(3): for layer in layers: ids = torch.stack([torch.randperm(E)[:TOPK] for _ in range(bs)]).to(torch.int32) out = layer._decode_routed(hidden, weights, ids.clone().to(device)) - _assert_close(out, _reference(pieces, layer.layer_id, hidden, weights, ids)) + _assert_close(out, _reference(pieces, layer.layer_id, hidden, weights, ids, act)) @cuda From 54304b7bd9c26a1330a812c416e8739100281964 Mon Sep 17 00:00:00 2001 From: Chen Cheng <85005591+ischencheng@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:40:05 -0500 Subject: [PATCH 2/2] refactor(moe): check the softcap activation once per gated_rows call --- python/freetoken/kernel/csrc/cpu_moe/format.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python/freetoken/kernel/csrc/cpu_moe/format.h b/python/freetoken/kernel/csrc/cpu_moe/format.h index 84ecbae36d..5f1ed88b3c 100644 --- a/python/freetoken/kernel/csrc/cpu_moe/format.h +++ b/python/freetoken/kernel/csrc/cpu_moe/format.h @@ -79,6 +79,7 @@ struct DownRoute { // ACT_SWIGLUOAI and ACT_SWIGLU_CLAMP clamp both inputs, ACT_SOFTCAP_SWIGLU tanh-caps them; the other kinds go through act_apply. template inline void gated_rows(const MoeParams& p, int i0, int i1, float w_in, bf16_t* g, RowDot dot) { + const bool softcap = p.act == ACT_SOFTCAP_SWIGLU; const bool clamped = p.act == ACT_SWIGLUOAI || p.act == ACT_SWIGLU_CLAMP; const float up_bias = p.act == ACT_SWIGLUOAI ? 1.0f : 0.0f; const float lim = p.swiglu_limit, alpha = p.swiglu_alpha; @@ -86,7 +87,7 @@ inline void gated_rows(const MoeParams& p, int i0, int i1, float w_in, bf16_t* g // gate = row i, up = row I+i float gate = dot(i) * w_in; float up = dot(p.I + i) * w_in; - if (p.act == ACT_SOFTCAP_SWIGLU) { + if (softcap) { g[i] = f32_to_bf16(alpha * std::tanh(gate / alpha) / (1.0f + std::exp(-gate)) * (lim * std::tanh(up / lim))); } else if (clamped) { // clamp(gate, max=lim) * sigmoid(alpha * gate) * (clamp(up, +-lim) + up_bias)