mrs83 commited on
Commit
40474e4
Β·
verified Β·
1 Parent(s): 4590d39

Upload folder using huggingface_hub

Browse files
1_Pooling/config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "embedding_dimension": 2048,
3
+ "pooling_mode": "mean",
4
+ "include_prompt": true
5
+ }
README.md ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: sentence-transformers
3
+ pipeline_tag: sentence-similarity
4
+ tags:
5
+ - sentence-transformers
6
+ - feature-extraction
7
+ - sentence-similarity
8
+ - transformers
9
+ - echo
10
+ - linear-complexity
11
+ - recurrent-hybrid
12
+ datasets:
13
+ - sentence-transformers/all-nli
14
+ - mteb/sts-b
15
+ metrics:
16
+ - spearman
17
+ - pearson
18
+ language:
19
+ - en
20
+ ---
21
+
22
+ # Echo-DSRN Embedding Model (Echo-DSRN-v0.1.3-Embed-Exp)
23
+
24
+ This is a high-performance sentence embedding model based on the recurrent-hybrid **Echo-DSRN** architecture. It scales **linearly** ($O(N)$) with sequence length, offering extreme efficiency and sub-millisecond latency on both CPU and GPU.
25
+
26
+ ## πŸš€ Model Details
27
+ - **Developer:** ethicalabs
28
+ - **Base Model:** [ethicalabs/Echo-DSRN-114M-v0.1.2](https://huggingface.co/ethicalabs/Echo-DSRN-114M-v0.1.2)
29
+ - **Architecture:** [Echo-DSRN](https://huggingface.co/ethicalabs/Echo-DSRN-114M-v0.1.2) Recurrent-Hybrid
30
+ - **Parameters:** 98.26M (98,264,064)
31
+ - **Embedding Dimension:** 2048
32
+ - **Max Sequence Length:** 2048
33
+
34
+ ## πŸ“Š Evaluation Results (MTEB STS)
35
+ Spearman Rank Correlation scores on Semantic Textual Similarity (STS) benchmark tasks:
36
+
37
+ | Benchmark Task | Echo-DSRN (Ours) |
38
+ | :--- | :---: |
39
+ | **STS12** | `0.6667` |
40
+ | **STS13** | `0.7692` |
41
+ | **STS14** | `0.7683` |
42
+ | **STS15** | `0.8227` |
43
+ | **STS16** | `0.7460` |
44
+ | **STSBenchmark** | `0.7293` |
45
+ | **SICK-R** | `0.7876` |
46
+ | **Average STS** | **`0.7557`** |
47
+
48
+ ## ⚑ Efficiency and Systems Scaling Profile
49
+ Inference performance (latency and peak VRAM allocation) on GPU and CPU configurations across different sequence lengths:
50
+
51
+ ### GPU Latency & VRAM Benchmark
52
+ | Sequence Length | Echo-DSRN Latency (GPU) | Echo-DSRN VRAM (GPU) |
53
+ | :---: | :---: | :---: |
54
+ | 128 | `15.93 ms` | `516.69 MB` |
55
+ | 256 | `17.56 ms` | `548.44 MB` |
56
+ | 512 | `32.14 ms` | `604.95 MB` |
57
+ | 1024 | `71.30 ms` | `710.96 MB` |
58
+ | 2048 | `155.26 ms` | `932.99 MB` |
59
+ | 4096 | N/A (OOR) | N/A (OOR) |
60
+
61
+ ### CPU Latency Benchmark
62
+ | Sequence Length | Echo-DSRN Latency (CPU) |
63
+ | :---: | :---: |
64
+ | 128 | `48.50 ms` |
65
+ | 256 | `84.94 ms` |
66
+ | 512 | `160.93 ms` |
67
+ | 1024 | `328.93 ms` |
68
+ | 2048 | `727.57 ms` |
69
+ | 4096 | N/A (OOR) |
70
+
71
+ *Note: 'N/A (OOR)' indicates sequence length exceeds model's maximum position embedding range.*
72
+
73
+ ## πŸ—οΈ Architecture Details
74
+ | Property | Value |
75
+ | :--- | :--- |
76
+ | Layers | 8 |
77
+ | Hidden Dim | 512 |
78
+ | Vocab Size | 32017 |
79
+ | Attention Heads | 4 |
80
+
81
+ ## πŸ“Š Parameter Breakdown
82
+ | Component | Parameters | % of Total |
83
+ | :--- | :--- | :--- |
84
+ | **Total** | **98.26M (98,264,064)** | **100%** |
85
+ | Embeddings | 16.39M | 16.68% |
86
+ | DSRN Recurrent Blocks | 81.87M | 83.32% |
87
+ | Norms & Biases | 512 | 0.00% |
88
+
89
+ ## πŸ’» Usage
90
+ You can load and use this model directly via `sentence-transformers`:
91
+ ```python
92
+ from sentence_transformers import SentenceTransformer
93
+
94
+ # Load model with auto-mapping enabled
95
+ model = SentenceTransformer("ethicalabs/Echo-DSRN-v0.1.3-Embed-Exp", trust_remote_code=True)
96
+
97
+ # Encode text to get 2048-dimensional embeddings
98
+ sentences = ["The recurrent slow state contains the aligned sequence representations.", "Echo-DSRN has linear complexity."]
99
+ embeddings = model.encode(sentences)
100
+ print(embeddings.shape) # (2, 2048)
101
+ ```
102
+
103
+ ## πŸ› οΈ Training Procedure
104
+ The model was trained in three sequential phases:
105
+ 1. **Contrastive Pre-training**: Representation space alignment using natural language inference datasets.
106
+ 2. **Fine-grained Similarity Tuning**: Fine-tuning using semantic textual similarity benchmarks to calibrate similarity scores.
107
+ 3. **Multi-Task Generalization Tuning**: Training on NLI retrieval, Banking77 intent classification, and STS semantic similarity simultaneously with dynamic early stopping to prevent representation collapse.
108
+
109
+ ---
110
+ *This model card was automatically generated by `scripts/generate_model_card.py`.*
chat_template.jinja ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if messages[0]['role'] == 'system' %}
2
+ {%- set system_message = messages[0]['content'] %}
3
+ {%- else %}
4
+ {%- set system_message = 'You are Echo-DSRN, created by ethicalabs.ai. You are a helpful assistant.' %}
5
+ {%- endif %}
6
+
7
+ {%- if tools %}
8
+ {{- '<|system|>\n' + system_message }}
9
+ {{- "\n\n# Tools\n\nYou are a precise routing agent. You have access to the following tools. If a tool is required, output EXACTLY the tool call format. If no tool is required, respond conversationally.\n\nAvailable tools:\n<tools>" }}
10
+ {%- for tool in tools %}
11
+ {{- "\n" + tool | tojson }}
12
+ {%- endfor %}
13
+ {{- "\n</tools><|end|>\n" }}
14
+ {%- else %}
15
+ {{- '<|system|>\n' + system_message + '<|end|>\n' }}
16
+ {%- endif %}
17
+
18
+ {%- for message in messages %}
19
+ {%- if (message['role'] == "user") or (message['role'] == "system" and not loop.first) or (message['role'] == "assistant" and not message['tool_calls']) %}
20
+ {{- '<|' + message['role'] + '|>\n' + message['content'] + '<|end|>\n' }}
21
+ {%- elif message['role'] == "assistant" %}
22
+ {{- '<|assistant|>\n' }}
23
+ {%- if message['content'] %}
24
+ {{- message['content'] }}
25
+ {%- endif %}
26
+ {%- if message['tool_calls'] %}
27
+ {%- for tool_call in message['tool_calls'] %}
28
+ {%- if tool_call['function'] is defined %}
29
+ {%- set tool_call = tool_call['function'] %}
30
+ {%- endif %}
31
+ {{- '\n<tool_call>\n{"name": "' + tool_call['name'] + '", "arguments": ' + tool_call['arguments'] | tojson + '}\n</tool_call>' }}
32
+ {%- endfor %}
33
+ {%- endif %}
34
+ {{- '<|end|>\n' }}
35
+ {%- elif message['role'] == "tool" %}
36
+ {%- if loop.first or messages[loop.index0 - 1]['role'] != "tool" %}
37
+ {{- '<|user|>\n' }}
38
+ {%- endif %}
39
+ {{- '<tool_response>\n' + message['content'] + '\n</tool_response>' }}
40
+ {%- if loop.last or messages[loop.index0 + 1]['role'] != "tool" %}
41
+ {{- '<|end|>\n' }}
42
+ {%- endif %}
43
+ {%- endif %}
44
+ {%- endfor %}
45
+
46
+ {%- if add_generation_prompt %}
47
+ {{- '<|assistant|>\n' }}
48
+ {%- else %}
49
+ {{- eos_token }}
50
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "EchoModelForSentenceEmbedding"
4
+ ],
5
+ "attention_masking": "non_causal_window",
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_echo.EchoConfig",
8
+ "AutoModel": "modeling_embedding.EchoModelForSentenceEmbedding",
9
+ "AutoModelForCausalLM": "modeling_echo.EchoForCausalLM",
10
+ "DSRNScan": "triton_scan.DSRNScanTriton"
11
+ },
12
+ "bos_token_id": 1,
13
+ "classifier_dropout": 0.0,
14
+ "dtype": "float32",
15
+ "embed_dim": 512,
16
+ "eos_token_id": 32000,
17
+ "gate_bias_init": 0.0,
18
+ "hf_model_name": "ethicalabs/Echo-DSRN-v0.1.3-Embed-Exp",
19
+ "hidden_size": 512,
20
+ "id2label": {
21
+ "0": "0",
22
+ "1": "1"
23
+ },
24
+ "label2id": {
25
+ "0": 0,
26
+ "1": 1
27
+ },
28
+ "max_position_embeddings": 2048,
29
+ "mlp_bias": false,
30
+ "mlp_ratio": 8.0,
31
+ "model_type": "echo",
32
+ "num_attention_heads": 4,
33
+ "num_heads": 4,
34
+ "num_hidden_layers": 8,
35
+ "num_layers": 8,
36
+ "pad_token_id": 32000,
37
+ "pooling_mode": "mean_c_all",
38
+ "rope_theta": 10000.0,
39
+ "surprise_lambda_init": 0.1,
40
+ "tie_word_embeddings": false,
41
+ "transformers_version": "5.2.0",
42
+ "use_cache": false,
43
+ "use_hybrid_attention": true,
44
+ "use_rmsnorm": true,
45
+ "use_triton": true,
46
+ "vocab_size": 32017
47
+ }
config_sentence_transformers.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "pytorch": "2.12.0+rocm7.2",
4
+ "sentence_transformers": "5.5.1",
5
+ "transformers": "5.2.0"
6
+ },
7
+ "default_prompt_name": null,
8
+ "model_type": "SentenceTransformer",
9
+ "prompts": {
10
+ "document": "",
11
+ "query": ""
12
+ },
13
+ "similarity_fn_name": "cosine"
14
+ }
configuration_echo.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from transformers import PretrainedConfig
4
+
5
+
6
+ class EchoConfig(PretrainedConfig):
7
+ model_type = "echo"
8
+
9
+ def __init__(
10
+ self,
11
+ vocab_size=49152,
12
+ embed_dim=None,
13
+ num_layers=4,
14
+ num_heads=4,
15
+ mlp_ratio=4,
16
+ gate_bias_init=0.0,
17
+ use_hybrid_attention=True,
18
+ use_rmsnorm=True,
19
+ mlp_bias: bool = False,
20
+ pooling_mode: str = "c_T",
21
+ attention_masking: str = "causal",
22
+ # --- Classification fields (optional, ignored by CausalLM) ---
23
+ num_labels: int = 2,
24
+ id2label: Optional[dict] = None,
25
+ label2id: Optional[dict] = None,
26
+ classifier_dropout: float = 0.0,
27
+ **kwargs,
28
+ ):
29
+ # Synchronize hidden_size / embed_dim (HF synonym pair).
30
+ # Priority: explicit embed_dim > explicit hidden_size > package default (768).
31
+ hidden_size = kwargs.pop("hidden_size", None)
32
+
33
+ if embed_dim is None and hidden_size is None:
34
+ embed_dim = 768 # package default
35
+ elif embed_dim is None:
36
+ embed_dim = hidden_size
37
+ elif hidden_size is None:
38
+ hidden_size = embed_dim
39
+ elif embed_dim != hidden_size:
40
+ raise ValueError(
41
+ f"embed_dim ({embed_dim}) and hidden_size ({hidden_size}) must be equal in "
42
+ "Echo-DSRN β€” they are the same architectural dimension. Pass only one."
43
+ )
44
+
45
+ hidden_size = embed_dim # keep them in sync
46
+
47
+ self.vocab_size = vocab_size
48
+ self.embed_dim = embed_dim
49
+ self.hidden_size = hidden_size
50
+ self.num_layers = num_layers
51
+ self.num_heads = num_heads
52
+ self.mlp_ratio = mlp_ratio
53
+ self.gate_bias_init = gate_bias_init
54
+ self.use_hybrid_attention = use_hybrid_attention
55
+ self.use_rmsnorm = use_rmsnorm
56
+ self.mlp_bias = mlp_bias
57
+ self.pooling_mode = pooling_mode
58
+ self.attention_masking = attention_masking
59
+ self.classifier_dropout = classifier_dropout
60
+
61
+ # Standard HF aliases
62
+ self.num_hidden_layers = num_layers
63
+ self.num_attention_heads = num_heads
64
+
65
+ # TGI/HF AutoMap support
66
+ self.auto_map = {
67
+ "AutoConfig": "configuration_echo.EchoConfig",
68
+ "AutoModel": "modeling_echo.EchoModel",
69
+ "AutoModelForCausalLM": "modeling_echo.EchoForCausalLM",
70
+ "AutoModelForSequenceClassification": ("modeling_echo.EchoForSequenceClassification"),
71
+ }
72
+
73
+ # vLLM Advanced Parallelism Plans
74
+ self.base_model_tp_plan = {
75
+ "model.embedding": "rowwise",
76
+ "lm_head": "colwise",
77
+ "model.blocks.*.attn.qkv_proj": "colwise",
78
+ "model.blocks.*.attn.out_proj": "rowwise",
79
+ "model.blocks.*.mlp_up": "colwise",
80
+ "model.blocks.*.mlp_down": "rowwise",
81
+ "model.blocks.*.linear_gate": "colwise",
82
+ "model.blocks.*.linear_memory": "colwise",
83
+ "model.blocks.*.linear_read": "rowwise",
84
+ }
85
+
86
+ self.base_model_pp_plan = {
87
+ "blocks": (["x", "state_prev"], ["x", "h_new_full"]) # Inputs # Outputs
88
+ }
89
+
90
+ # PretrainedConfig manages id2label / label2id / num_labels as
91
+ # properties internally. Pass them through super().__init__ so HF's
92
+ # property setters run in the correct order. We must NOT pop them here.
93
+ if id2label is not None:
94
+ kwargs["id2label"] = {int(k): v for k, v in id2label.items()}
95
+ kwargs["label2id"] = {v: int(k) for k, v in id2label.items()}
96
+ elif "id2label" not in kwargs:
97
+ # Inject defaults so the property chain initialises cleanly
98
+ default_id2label = {i: str(i) for i in range(num_labels)}
99
+ kwargs["id2label"] = default_id2label
100
+ kwargs["label2id"] = {v: k for k, v in default_id2label.items()}
101
+
102
+ if label2id is not None and "label2id" not in kwargs:
103
+ kwargs["label2id"] = label2id
104
+
105
+ super().__init__(**kwargs)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:185ad110c4181d163d24c4123289602f65e182bee2ddc181642671fd765fcfe8
3
+ size 393070680
modeling_echo.py ADDED
@@ -0,0 +1,1497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from transformers import GenerationMixin, PreTrainedModel
7
+ from transformers.modeling_outputs import (
8
+ BaseModelOutputWithPast,
9
+ CausalLMOutputWithPast,
10
+ SequenceClassifierOutputWithPast,
11
+ )
12
+
13
+ from .configuration_echo import EchoConfig
14
+
15
+ if TYPE_CHECKING:
16
+ # Force HF trust_remote_code AST parser to bundle triton_scan.py
17
+ pass
18
+
19
+ try:
20
+ # pyrefly: ignore [missing-import]
21
+ from vllm.model_executor.models.transformers import ALL_ATTENTION_FUNCTIONS
22
+ except ImportError:
23
+ ALL_ATTENTION_FUNCTIONS = {}
24
+
25
+ try:
26
+ from transformers.cache_utils import Cache
27
+ except ImportError:
28
+
29
+ class Cache:
30
+ pass
31
+
32
+
33
+ class EchoCache(Cache):
34
+ """
35
+ Custom Cache to prevent Hugging Face's DynamicCache from dropping
36
+ the (k_attn, v_attn) elements from the DSRN 4-tuple state.
37
+ """
38
+
39
+ def __init__(self, states=None):
40
+ self.states = states if states is not None else []
41
+ self.layers = self.states # HF expectation
42
+
43
+ @property
44
+ def is_compileable(self):
45
+ return False
46
+
47
+ def get_seq_length(self, layer_idx=0):
48
+ if not self.states or len(self.states) <= layer_idx:
49
+ return 0
50
+ state = self.states[layer_idx]
51
+ if len(state) == 4:
52
+ return state[2].shape[2]
53
+ return 0
54
+
55
+ def get_max_length(self):
56
+ return None
57
+
58
+ def update(
59
+ self,
60
+ key_states: torch.Tensor,
61
+ value_states: torch.Tensor,
62
+ layer_idx: int,
63
+ cache_kwargs: Optional[dict] = None,
64
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
65
+ # EchoModel handles its own cache updates internally within the blocks.
66
+ # This update method is just a shim to satisfy the Cache protocol.
67
+ # k, v are already updated in the state tuple returned by the block.
68
+ if len(self.states) > layer_idx:
69
+ state = self.states[layer_idx]
70
+ if len(state) == 4:
71
+ return state[2], state[3]
72
+ return key_states, value_states
73
+
74
+ def get_usable_length(self, new_seq_length, layer_idx=0):
75
+ return self.get_seq_length(layer_idx)
76
+
77
+ def __getitem__(self, idx):
78
+ return self.states[idx]
79
+
80
+ def __len__(self):
81
+ return len(self.states)
82
+
83
+ def __iter__(self):
84
+ return iter(self.states)
85
+
86
+ def reorder_cache(self, beam_idx: torch.LongTensor):
87
+ reordered_states = []
88
+ for layer_state in self.states:
89
+ reordered_layer_state = tuple(
90
+ tensor.index_select(0, beam_idx.to(tensor.device)) for tensor in layer_state
91
+ )
92
+ reordered_states.append(reordered_layer_state)
93
+ self.states = reordered_states
94
+
95
+
96
+ # --- STANDALONE KERNELS (AUTOMAGICALLY INLINED) ---
97
+ def _sequential_scan(a, b, h):
98
+ """
99
+ Core sequential scan for a batch of sequences.
100
+ Vectorized across all dimensions except time.
101
+ """
102
+ a.shape[:-1]
103
+ a.shape[-1]
104
+ # a, b: (..., T, D)
105
+ # h: (..., D)
106
+ T = a.shape[-2]
107
+
108
+ res = torch.empty_like(b)
109
+ curr_h = h
110
+ for t in range(T):
111
+ curr_h = a[..., t, :] * curr_h + b[..., t, :]
112
+ res[..., t, :] = curr_h
113
+ return res, curr_h
114
+
115
+
116
+ def dsrn_parallel_scan(g_t, m_t, c_0=None, chunk_size=32, use_triton=False):
117
+ """
118
+ Parallel implementation of the DSRN slow-state update:
119
+ c_t = (1 - g_t) * c_{t-1} + g_t * m_t
120
+
121
+ Uses a Hierarchical Chunked Scan for O(T/K + K) speed and stability,
122
+ or a custom Triton kernel for dramatically reduced memory bandwidth.
123
+ """
124
+ # Triton kernel for GPU-accelerated parallel scan.
125
+ if use_triton and g_t.is_cuda:
126
+ try:
127
+ from .triton_scan import triton_dsrn_parallel_scan
128
+
129
+ return triton_dsrn_parallel_scan(g_t, m_t, c_0)
130
+ except ImportError:
131
+ import warnings
132
+
133
+ warnings.warn("Triton scan unavailable. Falling back to PyTorch scan.", UserWarning)
134
+
135
+ orig_dtype = g_t.dtype
136
+ a = (1.0 - g_t).float()
137
+ b = (g_t * m_t).float()
138
+
139
+ B, T, D = a.shape
140
+ device = a.device
141
+
142
+ # Pad T to be multiple of chunk_size
143
+ pad_len = (chunk_size - (T % chunk_size)) % chunk_size
144
+ if pad_len > 0:
145
+ a = F.pad(a, (0, 0, 0, pad_len), value=1.0)
146
+ b = F.pad(b, (0, 0, 0, pad_len), value=0.0)
147
+
148
+ new_T = T + pad_len
149
+ num_chunks = new_T // chunk_size
150
+
151
+ # 1. Reshape to (B, num_chunks, chunk_size, D)
152
+ a_chunks = a.view(B, num_chunks, chunk_size, D)
153
+ b_chunks = b.view(B, num_chunks, chunk_size, D)
154
+
155
+ # 2. Local scan within each chunk (vectorized across B and num_chunks)
156
+ h_init_local = torch.zeros(B, num_chunks, D, device=device, dtype=torch.float32)
157
+ c_res, c_final = _sequential_scan(a_chunks, b_chunks, h_init_local)
158
+
159
+ # Summary of a for each chunk (product of a)
160
+ a_final = torch.prod(a_chunks, dim=2) # (B, num_chunks, D)
161
+
162
+ # 3. Global scan across chunk summaries
163
+ h_0 = c_0.float() if c_0 is not None else torch.zeros(B, D, device=device, dtype=torch.float32)
164
+
165
+ # h_chunk_outputs[:, j] is the state AFTER chunk j.
166
+ h_chunk_outputs, _ = _sequential_scan(a_final, c_final, h_0)
167
+ # The state BEFORE chunk j is h_chunk_outputs[:, j-1].
168
+ h_starts = torch.cat([h_0.unsqueeze(1), h_chunk_outputs[:, :-1]], dim=1)
169
+
170
+ # 4. Final combine: h_{j, i} = a_prefix_{j, i} * h_starts[j] + c_res[j, i]
171
+ a_prefix = torch.cumprod(a_chunks, dim=2)
172
+ final_h = a_prefix * h_starts.unsqueeze(2) + c_res
173
+
174
+ # Reshape back and crop, then cast back to original dtype
175
+ return final_h.view(B, -1, D)[:, :T].to(orig_dtype)
176
+
177
+
178
+ def rms_norm_fn(hidden_states, weight, eps=1e-6):
179
+ input_dtype = hidden_states.dtype
180
+ hidden_states = hidden_states.contiguous().to(torch.float32)
181
+ variance = (hidden_states * hidden_states).mean(-1, keepdim=True)
182
+ hidden_states = hidden_states * torch.rsqrt(variance + eps)
183
+ return weight * hidden_states.to(input_dtype)
184
+
185
+
186
+ def dsrn_parallel_kernel_legacy(
187
+ model_block: nn.Module,
188
+ x: torch.Tensor,
189
+ h_prev: torch.Tensor,
190
+ c_prev: torch.Tensor,
191
+ eos_mask: Optional[torch.Tensor] = None,
192
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
193
+ """
194
+ Legacy DSRN kernel (Fixed LayerNorm, No Surprise Read).
195
+ Identical to the version that passed verification.
196
+ """
197
+ B, T, D = x.shape
198
+
199
+ # 1. Norm and Projections
200
+ x_norm = F.layer_norm(
201
+ x,
202
+ (D,),
203
+ weight=model_block.norm_fast.weight,
204
+ bias=model_block.norm_fast.bias,
205
+ )
206
+
207
+ # Fast State β€” float32 sigmoid/tanh to avoid bf16 saturation NaN
208
+ gru_proj = F.linear(x_norm, model_block.gru_cell.weight_ih, model_block.gru_cell.bias_ih)
209
+ z_all = torch.sigmoid(gru_proj[:, :, :D].float()).to(x.dtype)
210
+ r_all = torch.tanh(gru_proj[:, :, 2 * D :].float()).to(
211
+ x.dtype
212
+ ) # Optimization: slice instead of chunk
213
+
214
+ # --- EOS RESET LOGIC (Fast State) ---
215
+ if eos_mask is not None:
216
+ reset_mask = torch.roll(eos_mask, shifts=1, dims=1)
217
+ reset_mask[:, 0] = (
218
+ 0 # First token reset depends on previous chunk eos, handled by h_prev/c_prev passing 0
219
+ )
220
+
221
+ # Apply strict reset to z_all
222
+ z_all = torch.where(reset_mask.unsqueeze(-1) > 0, torch.ones_like(z_all), z_all)
223
+
224
+ # h_t = (1 - z_t) * h_{t-1} + z_t * r_t
225
+ h_all = dsrn_parallel_scan(
226
+ z_all, r_all, h_prev, use_triton=getattr(model_block, "use_triton", False)
227
+ )
228
+ h_new = h_all[:, -1]
229
+
230
+ # 2. Slow State Path
231
+ # CAUSAL SHIFT: Predict x[t] using h[t-1]
232
+ # h_all is [h_1, ..., h_T]. We need [h_0, ..., h_{T-1}]
233
+ # Prepend h_prev to shift
234
+ h_shifted = torch.cat([h_prev.unsqueeze(1), h_all[:, :-1, :]], dim=1)
235
+
236
+ x_pred = model_block.linear_pred(h_shifted)
237
+ diff = x - x_pred
238
+ error = torch.clamp((diff * diff).float(), max=10.0).to(x.dtype).mean(dim=-1, keepdim=True)
239
+ # Constrain surprise_lambda strictly positive to guarantee error opens the memory gate
240
+ surprise_signal = error * torch.nn.functional.softplus(model_block.surprise_lambda.float()).to(
241
+ x.dtype
242
+ )
243
+
244
+ # Gates
245
+ gate_logits = model_block.linear_gate(h_all) + surprise_signal
246
+ g_all = torch.sigmoid(gate_logits.float()).to(x.dtype)
247
+ m_all = torch.tanh(model_block.linear_memory(h_all).float()).to(x.dtype)
248
+
249
+ # --- EOS RESET LOGIC (Slow State) ---
250
+ if eos_mask is not None:
251
+ reset_mask = torch.roll(eos_mask, shifts=1, dims=1)
252
+ reset_mask[:, 0] = 0
253
+
254
+ g_all = torch.where(reset_mask.unsqueeze(-1) > 0, torch.zeros_like(g_all), g_all)
255
+
256
+ # c_t
257
+ c_all = dsrn_parallel_scan(
258
+ g_all, m_all, c_prev, use_triton=getattr(model_block, "use_triton", False)
259
+ )
260
+ c_new = c_all[:, -1]
261
+
262
+ # --- Inter-Chunk Reset ---
263
+ # If the LAST token is EOS, then h_new/c_new (which are states FOR NEXT CHUNK) must be 0.
264
+ if eos_mask is not None:
265
+ last_is_eos = eos_mask[:, -1].float() # (B,)
266
+ keep_prob = (1.0 - last_is_eos).unsqueeze(-1) # (B, 1)
267
+ h_new = h_new * keep_prob
268
+ c_new = c_new * keep_prob
269
+ gate_stats = g_all.mean(dim=-1)
270
+
271
+ # 3. Final MLP Path
272
+ h_norm = F.layer_norm(
273
+ h_all, (D,), weight=model_block.norm_ff.weight, bias=model_block.norm_ff.bias
274
+ )
275
+ mlp_out = model_block.mlp_down(model_block.mlp_act(model_block.mlp_up(h_norm)))
276
+
277
+ x_out = x + mlp_out
278
+
279
+ # Continuous Read (Surprise Gate Fix)
280
+ # Enabled on Legacy to fix Disconnected Slow State bug while keeping LayerNorm
281
+ x_out = x_out + model_block.linear_read(c_all)
282
+
283
+ return x_out, h_new, c_new, gate_stats, h_all, c_all
284
+
285
+
286
+ def dsrn_parallel_kernel_hybrid(
287
+ model_block: nn.Module,
288
+ x: torch.Tensor,
289
+ h_prev: torch.Tensor,
290
+ c_prev: torch.Tensor,
291
+ eos_mask: Optional[torch.Tensor] = None,
292
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
293
+ """
294
+ Hybrid DSRN kernel (RMSNorm + Surprise Read).
295
+ """
296
+ B, T, D = x.shape
297
+
298
+ # 1. Norm (RMSNorm hardcoded for Hybrid path)
299
+ x_norm = rms_norm_fn(x, model_block.norm_fast.weight)
300
+
301
+ # Fast State β€” compute sigmoid/tanh in float32 to avoid bf16 saturation
302
+ # producing 0 Γ— inf = NaN in the backward pass.
303
+ gru_proj = F.linear(x_norm, model_block.gru_cell.weight_ih, model_block.gru_cell.bias_ih)
304
+ z_all = torch.sigmoid(gru_proj[:, :, :D].float()).to(x.dtype)
305
+ r_all = torch.tanh(gru_proj[:, :, 2 * D :].float()).to(x.dtype)
306
+
307
+ # --- EOS RESET LOGIC (Fast State) ---
308
+ if eos_mask is not None:
309
+ reset_mask = torch.roll(eos_mask, shifts=1, dims=1)
310
+ reset_mask[:, 0] = 0
311
+ z_all = torch.where(reset_mask.unsqueeze(-1) > 0, torch.ones_like(z_all), z_all)
312
+
313
+ h_all = dsrn_parallel_scan(
314
+ z_all, r_all, h_prev, use_triton=getattr(model_block, "use_triton", False)
315
+ )
316
+ h_new = h_all[:, -1]
317
+
318
+ # 2. Slow State
319
+ # CAUSAL SHIFT: Predict x[t] using h[t-1]
320
+ h_shifted = torch.cat([h_prev.unsqueeze(1), h_all[:, :-1, :]], dim=1)
321
+
322
+ x_pred = model_block.linear_pred(h_shifted)
323
+ diff = x - x_pred
324
+ error = torch.clamp((diff * diff).float(), max=10.0).to(x.dtype).mean(dim=-1, keepdim=True)
325
+ # Constrain surprise_lambda strictly positive to guarantee error opens the memory gate
326
+ surprise_signal = error * torch.nn.functional.softplus(model_block.surprise_lambda.float()).to(
327
+ x.dtype
328
+ )
329
+
330
+ gate_logits = model_block.linear_gate(h_all) + surprise_signal
331
+ g_all = torch.sigmoid(gate_logits.float()).to(x.dtype)
332
+ m_all = torch.tanh(model_block.linear_memory(h_all).float()).to(x.dtype)
333
+
334
+ # --- EOS RESET LOGIC (Slow State) ---
335
+ if eos_mask is not None:
336
+ reset_mask = torch.roll(eos_mask, shifts=1, dims=1)
337
+ reset_mask[:, 0] = 0
338
+ g_all = torch.where(reset_mask.unsqueeze(-1) > 0, torch.zeros_like(g_all), g_all)
339
+
340
+ c_all = dsrn_parallel_scan(
341
+ g_all, m_all, c_prev, use_triton=getattr(model_block, "use_triton", False)
342
+ )
343
+ c_new = c_all[:, -1]
344
+
345
+ # --- Inter-Chunk Reset ---
346
+ if eos_mask is not None:
347
+ last_is_eos = eos_mask[:, -1].float()
348
+ keep_prob = (1.0 - last_is_eos).unsqueeze(-1)
349
+ h_new = h_new * keep_prob
350
+ c_new = c_new * keep_prob
351
+ gate_stats = g_all.mean(dim=-1)
352
+
353
+ # 3. Final MLP
354
+ h_norm = rms_norm_fn(h_all, model_block.norm_ff.weight)
355
+ mlp_out = model_block.mlp_down(model_block.mlp_act(model_block.mlp_up(h_norm)))
356
+ x_out = x + mlp_out
357
+
358
+ # Continuous Read (Hybrid Feature)
359
+ if model_block.use_hybrid_attention:
360
+ x_out = x_out + model_block.linear_read(c_all)
361
+
362
+ return x_out, h_new, c_new, gate_stats, h_all, c_all
363
+
364
+
365
+ def dsrn_parallel_kernel(
366
+ model_block: nn.Module,
367
+ x: torch.Tensor,
368
+ h_prev: torch.Tensor,
369
+ c_prev: torch.Tensor,
370
+ eos_mask: Optional[torch.Tensor] = None,
371
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
372
+ """
373
+ Wrapper for backward compatibility. Dispatches based on config.
374
+ """
375
+ if getattr(model_block, "use_rmsnorm", False):
376
+ return dsrn_parallel_kernel_hybrid(model_block, x, h_prev, c_prev, eos_mask=eos_mask)
377
+ return dsrn_parallel_kernel_legacy(model_block, x, h_prev, c_prev, eos_mask=eos_mask)
378
+
379
+
380
+ class HymbaRMSNorm(nn.Module):
381
+ def __init__(self, hidden_size, eps=1e-6):
382
+ """
383
+ HymbaRMSNorm is equivalent to T5LayerNorm
384
+ """
385
+ super().__init__()
386
+ self.weight = nn.Parameter(torch.ones(hidden_size))
387
+ self.variance_epsilon = eps
388
+
389
+ def forward(self, hidden_states):
390
+ input_dtype = hidden_states.dtype
391
+ hidden_states = hidden_states.to(torch.float32)
392
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
393
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
394
+ return self.weight * hidden_states.to(input_dtype)
395
+
396
+
397
+ class EchoRotaryEmbedding(nn.Module):
398
+ def __init__(self, dim, max_position_embeddings=4096, base=10000.0, device=None):
399
+ super().__init__()
400
+ self.dim = dim
401
+ self.max_position_embeddings = max_position_embeddings
402
+ self.base = base
403
+ self.device = device
404
+
405
+ # We NO LONGER use buffers here because they are being corrupted by
406
+ # Hugging Face's weight loading mechanism for this specific model.
407
+ # We will compute and move them on the first forward pass.
408
+ self._cos_cached = None
409
+ self._sin_cached = None
410
+
411
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
412
+ self.max_seq_len_cached = seq_len
413
+ # Compute inv_freq locally
414
+ inv_freq = 1.0 / (
415
+ self.base
416
+ ** (torch.arange(0, self.dim, 2, dtype=torch.float32, device=device) / self.dim)
417
+ )
418
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
419
+ freqs = torch.einsum("i,j->ij", t, inv_freq)
420
+ emb = torch.cat((freqs, freqs), dim=-1)
421
+
422
+ self._cos_cached = emb.cos().to(dtype)
423
+ self._sin_cached = emb.sin().to(dtype)
424
+
425
+ def forward(self, x, seq_len=None):
426
+ if (
427
+ self._cos_cached is None
428
+ or seq_len > self.max_seq_len_cached
429
+ or self._cos_cached.device != x.device
430
+ ):
431
+ self._set_cos_sin_cache(
432
+ seq_len=max(seq_len, self.max_position_embeddings), device=x.device, dtype=x.dtype
433
+ )
434
+
435
+ return (
436
+ self._cos_cached[:seq_len].to(dtype=x.dtype),
437
+ self._sin_cached[:seq_len].to(dtype=x.dtype),
438
+ )
439
+
440
+
441
+ def rotate_half(x):
442
+ """Rotates half the hidden dims of the input."""
443
+ x1 = x[..., : x.shape[-1] // 2]
444
+ x2 = x[..., x.shape[-1] // 2 :]
445
+ return torch.cat((-x2, x1), dim=-1)
446
+
447
+
448
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
449
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # (B, 1, T, D)
450
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # (B, 1, T, D)
451
+ q_embed = (q * cos) + (rotate_half(q) * sin)
452
+ k_embed = (k * cos) + (rotate_half(k) * sin)
453
+ return q_embed, k_embed
454
+
455
+
456
+ class SlidingWindowAttention(nn.Module):
457
+ def __init__(self, config: EchoConfig):
458
+ super().__init__()
459
+ self.hidden_size = config.hidden_size
460
+ self.num_heads = config.num_heads
461
+ self.head_dim = self.hidden_size // self.num_heads
462
+ self.window_size = getattr(config, "window_size", 128)
463
+ self.attention_masking = getattr(config, "attention_masking", "causal")
464
+
465
+ self.qkv_proj = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
466
+ self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
467
+
468
+ self.rotary_emb = EchoRotaryEmbedding(
469
+ self.head_dim,
470
+ base=getattr(config, "rope_theta", 10000.0),
471
+ )
472
+
473
+ def forward(
474
+ self,
475
+ x,
476
+ past_key_values: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
477
+ position_ids: Optional[torch.LongTensor] = None,
478
+ **kwargs,
479
+ ):
480
+ B, T, C = x.shape
481
+ qkv = self.qkv_proj(x)
482
+ q, k, v = qkv.chunk(3, dim=-1)
483
+
484
+ # Reshape for multi-head attention
485
+ q = q.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
486
+ k = k.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
487
+ v = v.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
488
+
489
+ # --- RoPE Injection ---
490
+ if position_ids is None:
491
+ # Fallback if position_ids was not passed
492
+ seq_length_with_past = T
493
+ if past_key_values is not None:
494
+ seq_length_with_past += past_key_values[0].shape[2]
495
+ position_ids = (
496
+ torch.arange(
497
+ seq_length_with_past - T,
498
+ seq_length_with_past,
499
+ dtype=torch.long,
500
+ device=x.device,
501
+ )
502
+ .unsqueeze(0)
503
+ .view(-1, T)
504
+ )
505
+
506
+ kv_seq_len = k.shape[2]
507
+ if past_key_values is not None:
508
+ kv_seq_len += past_key_values[0].shape[2]
509
+
510
+ cos, sin = self.rotary_emb(v, seq_len=kv_seq_len)
511
+ q, k = apply_rotary_pos_emb(q, k, cos, sin, position_ids)
512
+ # ----------------------
513
+
514
+ if past_key_values is not None:
515
+ k_past, v_past = past_key_values
516
+ k = torch.cat([k_past, k], dim=2)
517
+ v = torch.cat([v_past, v], dim=2)
518
+
519
+ # The cache MUST store the full history, do not overwrite it with truncated slices
520
+ current_key_value = (k, v)
521
+
522
+ # Create slices for attention computation
523
+ k_attn = k
524
+ v_attn = v
525
+
526
+ # Enforce Sliding Window (Truncate oldest tokens for attention ONLY)
527
+ if self.window_size is not None and k_attn.shape[2] > self.window_size:
528
+ k_attn = k_attn[:, :, -self.window_size :, :]
529
+ v_attn = v_attn[:, :, -self.window_size :, :]
530
+
531
+ attn_fn = ALL_ATTENTION_FUNCTIONS.get(
532
+ kwargs.get("attn_implementation", "sdpa"), F.scaled_dot_product_attention
533
+ )
534
+
535
+ # Determining causality and windowing:
536
+ # 1. Training (T > 1): Use sliding window causal mask.
537
+ # 2. Decoding (T = 1): Use sliding window and NO CAUSAL MASK
538
+ if T > 1:
539
+ # Training/Prefill: Attend to full k, v but apply band-limited causal mask
540
+ # Build sliding window causal mask (T, kv_seq_len)
541
+ kv_all_seq_len = k.shape[2]
542
+ past_seq_len = kv_all_seq_len - T
543
+
544
+ mask = torch.zeros((T, kv_all_seq_len), device=x.device, dtype=x.dtype)
545
+
546
+ row_idx = torch.arange(T, device=x.device).view(-1, 1)
547
+ col_idx = torch.arange(kv_all_seq_len, device=x.device).view(1, -1)
548
+ abs_pos = row_idx + past_seq_len
549
+
550
+ if self.attention_masking == "non_causal_window":
551
+ w_half = self.window_size // 2 if self.window_size is not None else None
552
+ if w_half is not None:
553
+ # Keep tokens in range [abs_pos - w_half, abs_pos + w_half]
554
+ mask = torch.where(torch.abs(abs_pos - col_idx) > w_half, float("-inf"), mask)
555
+ else:
556
+ # Causal upper triangle = -inf
557
+ mask = torch.where(col_idx > abs_pos, float("-inf"), mask)
558
+
559
+ # Keep tokens in range [abs_pos - self.window_size, abs_pos]
560
+ if self.window_size is not None:
561
+ mask = torch.where((abs_pos - col_idx) >= self.window_size, float("-inf"), mask)
562
+
563
+ # Replace -inf with 0 for the permitted window (float mask expected by sdpa)
564
+ mask = torch.where(mask == float("-inf"), mask, torch.zeros_like(mask))
565
+
566
+ y = attn_fn(q, k, v, attn_mask=mask.unsqueeze(0).unsqueeze(0))
567
+ else:
568
+ # Decoding: Recurrent step, attend only to the last window_size tokens
569
+ y = attn_fn(q, k_attn, v_attn, is_causal=False)
570
+
571
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
572
+ return self.out_proj(y), current_key_value
573
+
574
+
575
+ class DSRNBlock(nn.Module):
576
+ def __init__(self, config: EchoConfig):
577
+ super().__init__()
578
+ self.config = config
579
+ self.hidden_size = config.hidden_size
580
+ self.state_size = config.hidden_size * config.num_heads
581
+ self.use_triton = getattr(config, "use_triton", True)
582
+ self.use_hybrid_attention = getattr(config, "use_hybrid_attention", True)
583
+ self.use_rmsnorm = getattr(config, "use_rmsnorm", True)
584
+
585
+ # Fast State (GRU)
586
+ if self.use_rmsnorm:
587
+ self.norm_fast = HymbaRMSNorm(config.hidden_size)
588
+ else:
589
+ self.norm_fast = nn.LayerNorm(config.hidden_size)
590
+
591
+ self.gru_cell = nn.GRUCell(config.hidden_size, config.hidden_size)
592
+
593
+ # Hybrid Attention
594
+ if self.use_hybrid_attention:
595
+ self.attn = SlidingWindowAttention(config)
596
+
597
+ # Slow State (DSRN)
598
+ self.linear_read = nn.Linear(self.state_size, config.hidden_size, bias=False)
599
+ self.linear_gate = nn.Linear(config.hidden_size, self.state_size)
600
+ self.linear_memory = nn.Linear(config.hidden_size, self.state_size)
601
+
602
+ # -- Surprise Mechanism --
603
+ self.linear_pred = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
604
+ self.surprise_lambda = nn.Parameter(torch.zeros(self.state_size))
605
+
606
+ # Feed-Forward
607
+ if self.use_rmsnorm:
608
+ self.norm_ff = HymbaRMSNorm(config.hidden_size)
609
+ else:
610
+ self.norm_ff = nn.LayerNorm(config.hidden_size)
611
+
612
+ # Simple MLP: Linear -> GELU -> Linear
613
+ # mlp_up / mlp_act / mlp_down are the ONLY registered submodules.
614
+ # No self.mlp alias β€” that caused double-registration and spurious "missing keys".
615
+ intermediate_size = getattr(
616
+ config, "intermediate_size", int(config.hidden_size * getattr(config, "mlp_ratio", 4.0))
617
+ )
618
+ # Use getattr guard so configs loaded from old JSON (pre-mlp_bias field) default safely.
619
+ _mlp_bias = getattr(config, "mlp_bias", False)
620
+ self.mlp_up = nn.Linear(config.hidden_size, intermediate_size, bias=_mlp_bias)
621
+ self.mlp_act = nn.GELU()
622
+ self.mlp_down = nn.Linear(intermediate_size, config.hidden_size, bias=_mlp_bias)
623
+
624
+ def forward(
625
+ self, x: torch.Tensor, state_prev: Tuple[torch.Tensor, ...], **kwargs
626
+ ) -> Tuple[torch.Tensor, Tuple[torch.Tensor, ...], ...]:
627
+
628
+ # Unpack state
629
+ # Supports (h, c) or (h, c, k_attn, v_attn)
630
+ h_prev = state_prev[0]
631
+ c_prev = state_prev[1]
632
+
633
+ if self.use_triton and x.is_cuda:
634
+ # Placeholder for Triton
635
+ pass
636
+
637
+ # Use Parallel Kernel
638
+ x_out, h_new, c_new, gate_stats, h_all, c_all = dsrn_parallel_kernel(
639
+ self, x, h_prev, c_prev
640
+ )
641
+
642
+ if self.use_hybrid_attention:
643
+ # Re-apply norm for attention branch (cleanest for surgical transplant)
644
+ x_norm = self.norm_fast(x)
645
+
646
+ # Extract attention state from tuple if present (h, c, k_attn, v_attn)
647
+ # HF state structure is now: (h, c, k_attn, v_attn)
648
+ # But wait, past_key_values in forward loop is just (h,c) from legacy code.
649
+ # We need to expand the state tuple to include attention KV.
650
+
651
+ attn_kv = None
652
+ if len(state_prev) == 4:
653
+ attn_kv = (state_prev[2], state_prev[3])
654
+
655
+ attn_out, new_attn_kv = self.attn(x_norm, past_key_values=attn_kv, **kwargs)
656
+ x_out = x_out + attn_out
657
+
658
+ # Update state with new KV
659
+ if new_attn_kv is not None:
660
+ h_new_full = (h_new, c_new, new_attn_kv[0], new_attn_kv[1])
661
+ else:
662
+ h_new_full = (h_new, c_new)
663
+ else:
664
+ h_new_full = (h_new, c_new)
665
+
666
+ if kwargs.get("output_all_states", False):
667
+ return x_out, h_new_full, gate_stats, h_all, c_all
668
+ return x_out, h_new_full, gate_stats
669
+
670
+
671
+ class EchoPreTrainedModel(PreTrainedModel):
672
+ config_class = EchoConfig
673
+ base_model_prefix = "model"
674
+ _no_split_modules = ["DSRNBlock"]
675
+
676
+ # Silently drop legacy mlp.0.*/mlp.1.*/mlp.2.* alias keys if they exist in old
677
+ # local training checkpoints from before the self.mlp aliasing was removed.
678
+ # The canonical names are mlp_up.* / mlp_act.* / mlp_down.* which load fine.
679
+ _keys_to_ignore_on_load_unexpected = [
680
+ r".*\.mlp\.0\..*",
681
+ r".*\.mlp\.1\..*",
682
+ r".*\.mlp\.2\..*",
683
+ ]
684
+
685
+ def _init_weights(self, module):
686
+ if isinstance(module, nn.Linear):
687
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
688
+ if module.bias is not None:
689
+ torch.nn.init.zeros_(module.bias)
690
+ elif isinstance(module, nn.Embedding):
691
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
692
+ elif isinstance(module, nn.LayerNorm):
693
+ torch.nn.init.zeros_(module.bias)
694
+ torch.nn.init.ones_(module.weight)
695
+
696
+
697
+ class EchoModel(EchoPreTrainedModel):
698
+ supports_gradient_checkpointing = True
699
+ _supports_attention_backend = True
700
+
701
+ def __init__(self, config: EchoConfig):
702
+ super().__init__(config)
703
+ self.embed_dim = config.embed_dim
704
+ self.num_layers = config.num_layers
705
+ self.num_heads = config.num_heads
706
+ self.state_dim = config.embed_dim * config.num_heads
707
+
708
+ self.embedding = nn.Embedding(config.vocab_size, config.embed_dim)
709
+ self.blocks = nn.ModuleList([DSRNBlock(config) for _ in range(config.num_layers)])
710
+
711
+ if getattr(config, "use_rmsnorm", False):
712
+ self.final_norm = HymbaRMSNorm(config.hidden_size)
713
+ else:
714
+ self.final_norm = nn.LayerNorm(config.hidden_size)
715
+
716
+ self.gradient_checkpointing = False
717
+
718
+ self.post_init()
719
+
720
+ # --- ZOMBIE GRADIENT PATCH (FIXED) ---
721
+ # Fixed: Now using controlled bias defaults to 1.0 to encourage open gates initially
722
+ bias_val = getattr(config, "gate_bias_init", 1.0)
723
+ for block in self.blocks:
724
+ nn.init.constant_(block.linear_gate.bias, bias_val)
725
+ # Init Surprise
726
+ if (
727
+ block.linear_pred.weight.dtype in (torch.bfloat16, torch.float16)
728
+ and block.linear_pred.weight.is_cuda
729
+ ):
730
+ _device = block.linear_pred.weight.device
731
+ _dtype = block.linear_pred.weight.dtype
732
+ temp_w = torch.empty_like(
733
+ block.linear_pred.weight, dtype=torch.float32, device="cpu"
734
+ )
735
+ nn.init.orthogonal_(temp_w, gain=0.1)
736
+ with torch.no_grad():
737
+ block.linear_pred.weight.copy_(temp_w.to(device=_device, dtype=_dtype))
738
+ else:
739
+ nn.init.orthogonal_(block.linear_pred.weight, gain=0.1)
740
+
741
+ nn.init.zeros_(block.surprise_lambda)
742
+ # CRITICAL: Zero-Init Residual Output (Identity Start)
743
+ nn.init.zeros_(block.mlp_down.weight)
744
+ if block.mlp_down.bias is not None:
745
+ nn.init.zeros_(block.mlp_down.bias)
746
+
747
+ def _set_gradient_checkpointing(self, enable=True, gradient_checkpointing_func=None):
748
+ """Enable/disable gradient checkpointing."""
749
+ self.gradient_checkpointing = enable
750
+
751
+ def get_input_embeddings(self):
752
+ return self.embedding
753
+
754
+ def set_input_embeddings(self, value):
755
+ self.embedding = value
756
+
757
+ def forward(
758
+ self,
759
+ input_ids: Optional[torch.LongTensor] = None,
760
+ past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
761
+ inputs_embeds: Optional[torch.FloatTensor] = None,
762
+ position_ids: Optional[torch.LongTensor] = None,
763
+ output_dsrn_telemetry: Optional[bool] = False,
764
+ output_attentions: Optional[bool] = None,
765
+ output_hidden_states: Optional[bool] = None,
766
+ return_dict: Optional[bool] = None,
767
+ output_all_states: Optional[bool] = False,
768
+ **kwargs,
769
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
770
+
771
+ return_dict = (
772
+ return_dict
773
+ if return_dict is not None
774
+ else getattr(self.config, "use_return_dict", True)
775
+ )
776
+
777
+ if input_ids is not None and inputs_embeds is not None:
778
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
779
+ elif input_ids is not None:
780
+ batch_size, seq_len = input_ids.shape
781
+ x = self.embedding(input_ids)
782
+ elif inputs_embeds is not None:
783
+ batch_size, seq_len, _ = inputs_embeds.shape
784
+ x = inputs_embeds
785
+ else:
786
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
787
+
788
+ device = x.device
789
+
790
+ # Initialize states if not provided or if it's an empty Cache object
791
+ is_empty_cache = (
792
+ hasattr(past_key_values, "get_seq_length") and past_key_values.get_seq_length() == 0
793
+ )
794
+ if past_key_values is None or is_empty_cache:
795
+ past_key_values = []
796
+ for _ in range(self.num_layers):
797
+ h = torch.zeros(batch_size, self.embed_dim, device=device, dtype=x.dtype)
798
+ c = torch.zeros(batch_size, self.state_dim, device=device, dtype=x.dtype)
799
+ past_key_values.append((h, c))
800
+
801
+ current_states = past_key_values
802
+ next_states = []
803
+
804
+ all_gate_stats = [] if output_dsrn_telemetry else None
805
+ all_c_states = [] if output_dsrn_telemetry else None
806
+ all_h_all = [] if output_all_states else None
807
+ all_c_all = [] if output_all_states else None
808
+
809
+ # Layer-Major Execution
810
+ for i, block in enumerate(self.blocks):
811
+
812
+ # Handle potential DynamicCache structure or list of tuples
813
+ if hasattr(current_states, "__getitem__"):
814
+ state_i = current_states[i]
815
+ else:
816
+ state_i = current_states[i]
817
+
818
+ if len(state_i) == 2:
819
+ # DSRN Only
820
+ pass
821
+ elif len(state_i) == 4:
822
+ # DSRN + Attention State
823
+ pass
824
+ else:
825
+ # Fallback for empty/malformed states
826
+ h_prev = torch.zeros(batch_size, self.embed_dim, device=device)
827
+ c_prev = torch.zeros(batch_size, self.state_dim, device=device)
828
+ state_i = (h_prev, c_prev)
829
+
830
+ # Use gradient checkpointing if enabled
831
+ if self.gradient_checkpointing and self.training:
832
+ # Checkpointing complex states is tricky, usually just pass h/c
833
+ out = torch.utils.checkpoint.checkpoint(
834
+ block,
835
+ x,
836
+ state_i,
837
+ use_reentrant=False,
838
+ output_all_states=output_all_states,
839
+ **kwargs,
840
+ )
841
+ else:
842
+ out = block(x, state_i, output_all_states=output_all_states, **kwargs)
843
+
844
+ x = out[0]
845
+ next_states.append(out[1])
846
+
847
+ if output_dsrn_telemetry:
848
+ all_gate_stats.append(out[2])
849
+ all_c_states.append(out[1][1])
850
+
851
+ if output_all_states:
852
+ all_h_all.append(out[3])
853
+ all_c_all.append(out[4])
854
+
855
+ x = self.final_norm(x)
856
+
857
+ if isinstance(current_states, EchoCache):
858
+ current_states.states = next_states
859
+ next_states = current_states
860
+ elif EchoCache is not None:
861
+ next_states = EchoCache(next_states)
862
+
863
+ # Revert to raw tuple outputs if return_dict=False is requested
864
+ if not return_dict:
865
+ if output_dsrn_telemetry:
866
+ if output_all_states:
867
+ return x, next_states, all_c_states, all_gate_stats, all_h_all, all_c_all
868
+ return x, next_states, all_c_states, all_gate_stats
869
+ if output_all_states:
870
+ return x, next_states, all_h_all, all_c_all
871
+ return x, next_states
872
+
873
+ # Standard HF Object wrapper containing last_hidden_state
874
+ output_obj = BaseModelOutputWithPast(
875
+ last_hidden_state=x,
876
+ past_key_values=next_states,
877
+ hidden_states=(x,) if output_hidden_states else None,
878
+ attentions=None,
879
+ )
880
+ if output_dsrn_telemetry:
881
+ output_obj.all_c_states = all_c_states
882
+ output_obj.all_gate_stats = all_gate_stats
883
+ if output_all_states:
884
+ output_obj.all_h_all = all_h_all
885
+ output_obj.all_c_all = all_c_all
886
+ return output_obj
887
+
888
+
889
+ class EchoForCausalLM(EchoPreTrainedModel, GenerationMixin):
890
+ _is_causal = True
891
+ supports_gradient_checkpointing = True
892
+ _supports_cache_class = False
893
+ _supports_static_cache = False
894
+ main_input_name = "input_ids"
895
+ # Required by the modern HF tie_weights() mechanism (transformers β‰₯ 4.47).
896
+ # Without this dict being non-None, tie_weights() returns early even when
897
+ # tie_word_embeddings=True and get_input/output_embeddings() are both defined.
898
+ _tied_weights_keys = {"lm_head.weight": "model.embedding.weight"}
899
+
900
+ @property
901
+ def _keys_to_ignore_on_load_missing(self):
902
+ # When mlp_bias=False (the default, and the setting for all v0.1.2 checkpoints),
903
+ # bias tensors are not present in the checkpoint and should not trigger warnings.
904
+ # When mlp_bias=True, these keys WILL exist in the checkpoint β€” do not silence them.
905
+ if not getattr(self.config, "mlp_bias", False):
906
+ return [r"model\.blocks\.\d+\.mlp_(up|down)\.bias"]
907
+ return []
908
+
909
+ @classmethod
910
+ def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
911
+ model = super().from_pretrained(pretrained_model_name_or_path, *args, **kwargs)
912
+
913
+ # Defense-in-depth: if mlp_bias=False but bias tensors were somehow initialized
914
+ # (e.g. an old code path created them), zero them out to prevent NaN/Inf
915
+ # corruption when running in bfloat16.
916
+ if not getattr(model.config, "mlp_bias", False):
917
+ zeroed = 0
918
+ with torch.no_grad():
919
+ for name, param in model.named_parameters():
920
+ if "mlp_up.bias" in name or "mlp_down.bias" in name:
921
+ param.zero_()
922
+ zeroed += 1
923
+ if zeroed:
924
+ import warnings
925
+
926
+ warnings.warn(
927
+ f"Zeroed {zeroed} MLP bias tensor(s) that were missing from the "
928
+ f"checkpoint. This indicates a config/checkpoint mismatch. "
929
+ f"Ensure mlp_bias=False in EchoConfig for v0.1.2 checkpoints.",
930
+ UserWarning,
931
+ )
932
+
933
+ return model
934
+
935
+ def __init__(self, config: EchoConfig):
936
+ super().__init__(config)
937
+ self.model = EchoModel(config)
938
+ self.lm_head = nn.Linear(config.embed_dim, config.vocab_size, bias=False)
939
+ self._latest_c_states = None
940
+ self._latest_gate_stats = None
941
+
942
+ # Initialize weights and apply final processing
943
+ self.post_init()
944
+
945
+ def get_input_embeddings(self):
946
+ return self.model.embedding
947
+
948
+ def set_input_embeddings(self, value):
949
+ self.model.embedding = value
950
+
951
+ def _set_gradient_checkpointing(self, enable=True, gradient_checkpointing_func=None):
952
+ """Enable/disable gradient checkpointing."""
953
+ self.model._set_gradient_checkpointing(enable, gradient_checkpointing_func)
954
+
955
+ def get_output_embeddings(self):
956
+ return self.lm_head
957
+
958
+ def set_output_embeddings(self, new_embeddings):
959
+ self.lm_head = new_embeddings
960
+
961
+ def forward(
962
+ self,
963
+ input_ids: torch.LongTensor,
964
+ attention_mask: Optional[torch.LongTensor] = None,
965
+ position_ids: Optional[torch.LongTensor] = None,
966
+ past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
967
+ inputs_embeds: Optional[torch.FloatTensor] = None,
968
+ labels: Optional[torch.LongTensor] = None,
969
+ use_cache: Optional[bool] = None,
970
+ output_attentions: Optional[bool] = None,
971
+ output_hidden_states: Optional[bool] = None,
972
+ return_dict: Optional[bool] = None,
973
+ output_dsrn_telemetry: Optional[bool] = False,
974
+ **kwargs,
975
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
976
+
977
+ output_attentions = (
978
+ output_attentions
979
+ if output_attentions is not None
980
+ else getattr(self.config, "output_attentions", False)
981
+ )
982
+ output_hidden_states = (
983
+ output_hidden_states
984
+ if output_hidden_states is not None
985
+ else getattr(self.config, "output_hidden_states", False)
986
+ )
987
+ use_cache = use_cache if use_cache is not None else getattr(self.config, "use_cache", True)
988
+
989
+ return_dict = (
990
+ return_dict
991
+ if return_dict is not None
992
+ else getattr(self.config, "use_return_dict", True)
993
+ )
994
+
995
+ '''
996
+ If kwargs is getting overloaded with extra args HF generate passes,
997
+ we safely extract kwargs here.
998
+ '''
999
+ # Pass position_ids explicitly alongside **kwargs
1000
+ kwargs["position_ids"] = position_ids
1001
+
1002
+ # Call the base EchoModel
1003
+ model_out = self.model(
1004
+ input_ids=input_ids,
1005
+ past_key_values=past_key_values,
1006
+ inputs_embeds=inputs_embeds,
1007
+ output_dsrn_telemetry=output_dsrn_telemetry,
1008
+ output_attentions=output_attentions,
1009
+ output_hidden_states=output_hidden_states,
1010
+ return_dict=return_dict, # Pass return_dict explicitly
1011
+ **kwargs,
1012
+ )
1013
+
1014
+ # Handle BaseModelOutputWithPast or raw tuple output gracefully
1015
+ if hasattr(model_out, "last_hidden_state"):
1016
+ hidden_states = model_out.last_hidden_state
1017
+ new_states = model_out.past_key_values
1018
+ else:
1019
+ hidden_states = model_out[0]
1020
+ new_states = model_out[1]
1021
+
1022
+ # Extract telemetry if model returned raw tuple (or via custom properties)
1023
+ if hasattr(model_out, "all_c_states"):
1024
+ self._latest_c_states = model_out.all_c_states
1025
+ self._latest_gate_stats = model_out.all_gate_stats
1026
+ elif isinstance(model_out, tuple) and len(model_out) > 2:
1027
+ self._latest_c_states = model_out[2]
1028
+ self._latest_gate_stats = model_out[3]
1029
+
1030
+ # Project using Causal LM head
1031
+ logits = self.lm_head(hidden_states)
1032
+
1033
+ loss = None
1034
+ if labels is not None:
1035
+ # Shift so that tokens < n predict n
1036
+ shift_logits = logits[..., :-1, :].contiguous()
1037
+ shift_labels = labels[..., 1:].contiguous()
1038
+ loss_fct = nn.CrossEntropyLoss()
1039
+ loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
1040
+
1041
+ if not return_dict:
1042
+ output = (logits, new_states)
1043
+ return ((loss,) + output) if loss is not None else output
1044
+
1045
+ return CausalLMOutputWithPast(
1046
+ loss=loss,
1047
+ logits=logits,
1048
+ past_key_values=new_states if use_cache else None,
1049
+ hidden_states=(hidden_states,) if output_hidden_states else None,
1050
+ attentions=None,
1051
+ )
1052
+
1053
+ def prepare_inputs_for_generation(
1054
+ self, input_ids, past_key_values=None, attention_mask=None, **kwargs
1055
+ ):
1056
+ # If past_key_values is a DynamicCache, we need to extract the underlying list of tuples
1057
+ # if the custom cache hasn't taken over yet. But actually, HF doesn't know about our 4-tuples.
1058
+ # So we should just let EchoModel handle it. If HF gave us a DynamicCache, it might be empty
1059
+ # or mangled.
1060
+ if (
1061
+ past_key_values is not None
1062
+ and not isinstance(past_key_values, (list, tuple))
1063
+ and not isinstance(past_key_values, EchoCache)
1064
+ ):
1065
+ # It's a DynamicCache. It's likely from the first generation step.
1066
+ # We can't use it directly because it stripped our (h,c).
1067
+ # But wait, on the VERY first generation step, past_key_values is None, then EchoModel returns EchoCache.
1068
+ # On subsequent steps we get EchoCache.
1069
+ # So if we get a DynamicCache, it means someone passed past_key_values explicitly to generate(),
1070
+ # or HF auto-created it on step 0 and passed it to step 1 incorrectly.
1071
+ pass
1072
+
1073
+ # In newer transformers, past_key_values could be a DynamicCache.
1074
+ # Check if it's effectively empty.
1075
+ is_empty = False
1076
+ if past_key_values is None:
1077
+ is_empty = True
1078
+ elif hasattr(past_key_values, "get_seq_length") and past_key_values.get_seq_length() == 0:
1079
+ is_empty = True
1080
+ elif isinstance(past_key_values, list) and len(past_key_values) == 0:
1081
+ is_empty = True
1082
+
1083
+ # If past_key_values is used, we only need the last token
1084
+ if not is_empty:
1085
+ input_ids = input_ids[:, -1:]
1086
+
1087
+ model_inputs = {
1088
+ "input_ids": input_ids,
1089
+ "past_key_values": past_key_values,
1090
+ "attention_mask": attention_mask,
1091
+ "use_cache": kwargs.get("use_cache"),
1092
+ }
1093
+
1094
+ # Pass through extra kwargs like output_dsrn_telemetry
1095
+ model_inputs.update({k: v for k, v in kwargs.items() if k not in model_inputs})
1096
+
1097
+ return model_inputs
1098
+
1099
+ def _reorder_cache(self, past_key_values, beam_idx):
1100
+ """
1101
+ Reorders cache for beam search or contrastive search.
1102
+ past_key_values: List[Tuple(h, c, ...)]
1103
+ """
1104
+ if past_key_values is None:
1105
+ return None
1106
+
1107
+ reordered_past = []
1108
+ for layer_past in past_key_values:
1109
+ # Each layer_past is a tuple of tensors (h, c) or (h, c, k, v)
1110
+ reordered_layer_past = tuple(
1111
+ p.index_select(0, beam_idx.to(p.device)) for p in layer_past
1112
+ )
1113
+ reordered_past.append(reordered_layer_past)
1114
+ return reordered_past
1115
+
1116
+
1117
+ class EchoClassifier(nn.Linear):
1118
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
1119
+ res = super().forward(input)
1120
+ if res.ndim == 3 and res.size(1) == 1:
1121
+ res = res.squeeze(1)
1122
+ return res
1123
+
1124
+
1125
+ class EchoForSequenceClassification(EchoPreTrainedModel):
1126
+ """
1127
+ Echo-DSRN with a sequence-level classification head.
1128
+
1129
+ This model is the *terminal* form of a fine-tuned classifier: it exposes
1130
+ only a ``classify()`` convenience method and a standard HF ``forward()``
1131
+ that returns :class:`~transformers.modeling_outputs.SequenceClassifierOutputWithPast`.
1132
+ It intentionally does **not** inherit :class:`~transformers.GenerationMixin` so
1133
+ chat-completion endpoints cannot be used accidentally.
1134
+
1135
+ Typical construction path
1136
+ -------------------------
1137
+ 1. Load ``EchoForCausalLM`` + LoRA adapter via :func:`merge_and_export`
1138
+ (see ``scripts/merge_clf_adapter.py``).
1139
+ 2. The resulting merged weights are saved as ``EchoForSequenceClassification``
1140
+ alongside a ``config.json`` that carries ``num_labels``, ``id2label``, and
1141
+ ``label2id``.
1142
+ 3. End-users load with::
1143
+
1144
+ from echo_dsrn import EchoForSequenceClassification
1145
+ model = EchoForSequenceClassification.from_pretrained("your/hub-id")
1146
+ label, probs = model.classify("some text")
1147
+ """
1148
+
1149
+ # Do NOT add GenerationMixin β€” this model must not generate text.
1150
+ main_input_name = "input_ids"
1151
+
1152
+ def __init__(self, config: EchoConfig):
1153
+ super().__init__(config)
1154
+ self.num_labels = getattr(config, "num_labels", 2)
1155
+ self.model = EchoModel(config)
1156
+
1157
+ classifier_dropout = getattr(config, "classifier_dropout", 0.0)
1158
+ self.dropout = nn.Dropout(classifier_dropout) if classifier_dropout > 0.0 else nn.Identity()
1159
+ self.classifier = EchoClassifier(config.embed_dim, self.num_labels, bias=True)
1160
+
1161
+ self.post_init()
1162
+
1163
+ @property
1164
+ def score(self) -> EchoClassifier:
1165
+ return self.classifier
1166
+
1167
+ @score.setter
1168
+ def score(self, value: EchoClassifier):
1169
+ self.classifier = value
1170
+
1171
+ # ------------------------------------------------------------------
1172
+ # HF embedding hooks (required by PreTrainedModel)
1173
+ # ------------------------------------------------------------------
1174
+ def get_input_embeddings(self):
1175
+ return self.model.embedding
1176
+
1177
+ def set_input_embeddings(self, value):
1178
+ self.model.embedding = value
1179
+
1180
+ def _set_gradient_checkpointing(self, enable=True, gradient_checkpointing_func=None):
1181
+ self.model._set_gradient_checkpointing(enable, gradient_checkpointing_func)
1182
+
1183
+ # ------------------------------------------------------------------
1184
+ # Forward
1185
+ # ------------------------------------------------------------------
1186
+ def forward(
1187
+ self,
1188
+ input_ids: Optional[torch.LongTensor] = None,
1189
+ attention_mask: Optional[torch.LongTensor] = None,
1190
+ position_ids: Optional[torch.LongTensor] = None,
1191
+ past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
1192
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1193
+ labels: Optional[torch.LongTensor] = None,
1194
+ use_cache: Optional[bool] = None,
1195
+ output_hidden_states: Optional[bool] = None,
1196
+ return_dict: Optional[bool] = None,
1197
+ **kwargs,
1198
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1199
+ """
1200
+ Parameters
1201
+ ----------
1202
+ labels:
1203
+ - ``num_labels == 1``: regression target (``torch.float``).
1204
+ - ``num_labels > 1``, single integer per sample: cross-entropy class index.
1205
+ - ``num_labels > 1``, float vector per sample: multi-label BCE.
1206
+ """
1207
+ return_dict = (
1208
+ return_dict
1209
+ if return_dict is not None
1210
+ else getattr(self.config, "use_return_dict", True)
1211
+ )
1212
+
1213
+ kwargs["position_ids"] = position_ids
1214
+
1215
+ model_out = self.model(
1216
+ input_ids=input_ids,
1217
+ past_key_values=past_key_values,
1218
+ inputs_embeds=inputs_embeds,
1219
+ **kwargs,
1220
+ )
1221
+
1222
+ hidden_states = model_out[0] # (B, T, D)
1223
+ new_states = model_out[1]
1224
+
1225
+ # --- Pooling: last non-padding token ---
1226
+ if attention_mask is not None:
1227
+ # Find the index of the last 1 in each row of attention_mask
1228
+ seq_lengths = attention_mask.sum(dim=1) - 1 # (B,)
1229
+ seq_lengths = seq_lengths.clamp(min=0)
1230
+ else:
1231
+ # No mask: use the true last token
1232
+ if input_ids is not None:
1233
+ seq_lengths = torch.full(
1234
+ (hidden_states.size(0),),
1235
+ hidden_states.size(1) - 1,
1236
+ dtype=torch.long,
1237
+ device=hidden_states.device,
1238
+ )
1239
+ else:
1240
+ seq_lengths = torch.full(
1241
+ (hidden_states.size(0),),
1242
+ hidden_states.size(1) - 1,
1243
+ dtype=torch.long,
1244
+ device=hidden_states.device,
1245
+ )
1246
+
1247
+ # Gather last-token hidden states: (B, D)
1248
+ pooled = hidden_states[
1249
+ torch.arange(hidden_states.size(0), device=hidden_states.device), seq_lengths
1250
+ ]
1251
+ pooled = self.dropout(pooled)
1252
+ logits = self.classifier(pooled) # (B, num_labels)
1253
+
1254
+ # --- Loss ---
1255
+ loss = None
1256
+ if labels is not None:
1257
+ if self.num_labels == 1:
1258
+ # Regression
1259
+ loss_fct = nn.MSELoss()
1260
+ loss = loss_fct(logits.squeeze(-1), labels.float())
1261
+ elif labels.dtype in (torch.float, torch.float16, torch.bfloat16):
1262
+ # Multi-label binary classification
1263
+ loss_fct = nn.BCEWithLogitsLoss()
1264
+ loss = loss_fct(logits, labels.float())
1265
+ else:
1266
+ # Standard multi-class
1267
+ loss_fct = nn.CrossEntropyLoss()
1268
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1269
+
1270
+ if not return_dict:
1271
+ output = (logits, new_states)
1272
+ return ((loss,) + output) if loss is not None else output
1273
+
1274
+ return SequenceClassifierOutputWithPast(
1275
+ loss=loss,
1276
+ logits=logits,
1277
+ past_key_values=new_states if use_cache else None,
1278
+ hidden_states=None,
1279
+ attentions=None,
1280
+ )
1281
+
1282
+ # ------------------------------------------------------------------
1283
+ # Convenience inference API
1284
+ # ------------------------------------------------------------------
1285
+ @torch.inference_mode()
1286
+ def classify(
1287
+ self,
1288
+ text: str,
1289
+ tokenizer,
1290
+ device: Optional[str] = None,
1291
+ return_probabilities: bool = True,
1292
+ ) -> Tuple[str, Optional[torch.Tensor]]:
1293
+ """
1294
+ High-level classification helper.
1295
+
1296
+ Parameters
1297
+ ----------
1298
+ text:
1299
+ Raw string to classify.
1300
+ tokenizer:
1301
+ A HuggingFace ``PreTrainedTokenizer`` compatible with the model.
1302
+ device:
1303
+ Optional device string (e.g. ``"cuda"``). Defaults to the device
1304
+ of the model's first parameter.
1305
+ return_probabilities:
1306
+ If ``True`` (default), also return a probability tensor (softmax
1307
+ for multi-class, sigmoid for binary/multi-label).
1308
+
1309
+ Returns
1310
+ -------
1311
+ label : str
1312
+ The predicted label string from ``config.id2label``.
1313
+ probabilities : Tensor or None
1314
+ Shape ``(num_labels,)`` probability vector, or ``None`` if
1315
+ ``return_probabilities=False``.
1316
+ """
1317
+ if device is None:
1318
+ try:
1319
+ device = str(next(self.parameters()).device)
1320
+ except StopIteration:
1321
+ device = "cpu"
1322
+
1323
+ self.eval()
1324
+
1325
+ # Format text if baked-in templates exist
1326
+ sys_prompt = getattr(self.config, "system_prompt", None)
1327
+ usr_template = getattr(self.config, "user_template", None)
1328
+
1329
+ if sys_prompt and usr_template:
1330
+ messages = [{"role": "system", "content": sys_prompt}]
1331
+ messages.append({"role": "user", "content": usr_template.format(text=text)})
1332
+ # Format using the tokenizer's chat template
1333
+ try:
1334
+ formatted_text = tokenizer.apply_chat_template(
1335
+ messages, add_generation_prompt=True, tokenize=False
1336
+ )
1337
+ except Exception:
1338
+ formatted_text = text
1339
+ else:
1340
+ formatted_text = text
1341
+
1342
+ enc = tokenizer(formatted_text, return_tensors="pt", truncation=True)
1343
+ enc = {k: v.to(device) for k, v in enc.items()}
1344
+
1345
+ output = self(**enc)
1346
+ logits = output.logits # (1, num_labels)
1347
+
1348
+ if self.num_labels == 1:
1349
+ # Regression: return raw value
1350
+ pred_label = str(logits.squeeze().item())
1351
+ probs = None
1352
+ elif self.num_labels == 2:
1353
+ probs_t = torch.softmax(logits, dim=-1).squeeze(0) if return_probabilities else None
1354
+ pred_id = int(logits.argmax(dim=-1).item())
1355
+ pred_label = getattr(self.config, "id2label", {0: "0", 1: "1"}).get(
1356
+ pred_id, str(pred_id)
1357
+ )
1358
+ probs = probs_t
1359
+ else:
1360
+ probs_t = torch.softmax(logits, dim=-1).squeeze(0) if return_probabilities else None
1361
+ pred_id = int(logits.argmax(dim=-1).item())
1362
+ pred_label = getattr(self.config, "id2label", {}).get(pred_id, str(pred_id))
1363
+ probs = probs_t
1364
+
1365
+ return pred_label, probs
1366
+
1367
+ @classmethod
1368
+ def from_causal_lm(
1369
+ cls,
1370
+ causal_lm_model,
1371
+ num_labels: int = 2,
1372
+ id2label: Optional[dict] = None,
1373
+ label2id: Optional[dict] = None,
1374
+ classifier_dropout: float = 0.0,
1375
+ label_token_ids: Optional[List[int]] = None,
1376
+ system_prompt: Optional[str] = None,
1377
+ user_template: Optional[str] = None,
1378
+ ) -> "EchoForSequenceClassification":
1379
+ """
1380
+ Construct an :class:`EchoForSequenceClassification` from a fully
1381
+ merged :class:`EchoForCausalLM` instance (i.e. after LoRA weights
1382
+ have been merged via ``peft.merge_adapter``).
1383
+
1384
+ The backbone weights are copied; the ``lm_head`` is discarded.
1385
+
1386
+ Classifier head initialisation
1387
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1388
+ If ``label_token_ids`` is provided (one token ID per class), the
1389
+ classifier weight rows are seeded directly from the corresponding
1390
+ ``lm_head`` weight rows. This is the correct initialisation for
1391
+ **generative** adapters that were fine-tuned to emit a label token
1392
+ (e.g. ``"0"`` or ``"1"``): the backbone already knows how to push
1393
+ the last hidden state toward those tokens, so we preserve that signal
1394
+ instead of starting from random.
1395
+
1396
+ Parameters
1397
+ ----------
1398
+ causal_lm_model:
1399
+ A loaded (and optionally LoRA-merged) ``EchoForCausalLM`` instance.
1400
+ num_labels:
1401
+ Number of output classes.
1402
+ id2label:
1403
+ Optional mapping ``{int -> str}`` for label names.
1404
+ label2id:
1405
+ Optional reverse mapping ``{str -> int}``.
1406
+ classifier_dropout:
1407
+ Dropout probability before the classification head.
1408
+ label_token_ids:
1409
+ Optional list of ``num_labels`` token IDs. When supplied, row
1410
+ ``i`` of the ``lm_head`` weight matrix is copied into row ``i``
1411
+ of the classifier weight matrix, seeding the head from the
1412
+ causal model's learned token distributions.
1413
+ Example for Echo-DSRN NSFW adapter::
1414
+
1415
+ label_token_ids=[29900, 29896] # token IDs for "0" and "1"
1416
+
1417
+ Returns
1418
+ -------
1419
+ EchoForSequenceClassification
1420
+ """
1421
+ if id2label is None:
1422
+ id2label = {i: str(i) for i in range(num_labels)}
1423
+ if label2id is None:
1424
+ label2id = {v: k for k, v in id2label.items()}
1425
+
1426
+ # Validate label_token_ids length
1427
+ if label_token_ids is not None and len(label_token_ids) != num_labels:
1428
+ raise ValueError(
1429
+ f"label_token_ids has {len(label_token_ids)} entries but num_labels={num_labels}. "
1430
+ "Must provide exactly one token ID per class."
1431
+ )
1432
+
1433
+ # Clone config and inject classification fields
1434
+ config = causal_lm_model.config
1435
+ config.num_labels = num_labels
1436
+ config.id2label = {int(k): v for k, v in id2label.items()}
1437
+ config.label2id = label2id
1438
+ config.classifier_dropout = classifier_dropout
1439
+
1440
+ if system_prompt is not None:
1441
+ config.system_prompt = system_prompt
1442
+ if user_template is not None:
1443
+ config.user_template = user_template
1444
+
1445
+ # Carry dtype forward so save_pretrained serialises it correctly
1446
+ if hasattr(causal_lm_model, "dtype"):
1447
+ config.torch_dtype = str(causal_lm_model.dtype).replace("torch.", "")
1448
+ # Update auto_map so Hub users get the right class on from_pretrained
1449
+ config.auto_map = {
1450
+ "AutoConfig": "configuration_echo.EchoConfig",
1451
+ "AutoModel": "modeling_echo.EchoModel",
1452
+ "AutoModelForSequenceClassification": ("modeling_echo.EchoForSequenceClassification"),
1453
+ }
1454
+
1455
+ # Build the classifier wrapper
1456
+ clf_model = cls(config)
1457
+
1458
+ # Copy backbone weights
1459
+ backbone_sd = causal_lm_model.model.state_dict()
1460
+ missing, unexpected = clf_model.model.load_state_dict(backbone_sd, strict=True)
1461
+ if missing:
1462
+ import warnings
1463
+
1464
+ warnings.warn(
1465
+ f"EchoForSequenceClassification.from_causal_lm: "
1466
+ f"missing backbone keys: {missing}",
1467
+ UserWarning,
1468
+ )
1469
+ if unexpected:
1470
+ import warnings
1471
+
1472
+ warnings.warn(
1473
+ f"EchoForSequenceClassification.from_causal_lm: "
1474
+ f"unexpected backbone keys: {unexpected}",
1475
+ UserWarning,
1476
+ )
1477
+
1478
+ # --- Seed classifier head from lm_head rows (generative adapter path) ---
1479
+ if label_token_ids is not None:
1480
+ lm_head_weight = causal_lm_model.lm_head.weight # (vocab_size, embed_dim)
1481
+ with torch.no_grad():
1482
+ for label_idx, token_id in enumerate(label_token_ids):
1483
+ clf_model.classifier.weight[label_idx].copy_(lm_head_weight[token_id])
1484
+ # Zero-init bias so initial scores are purely from the weight rows
1485
+ torch.nn.init.zeros_(clf_model.classifier.bias)
1486
+
1487
+ # --- Cast entire model to the source dtype ---
1488
+ # cls(config) initialises weights in float32 by default.
1489
+ # We cast everything uniformly AFTER all weight copies so that both
1490
+ # the backbone and the seeded classifier head end up in the same precision.
1491
+ src_dtype = causal_lm_model.dtype # e.g. torch.bfloat16
1492
+ if src_dtype != torch.float32:
1493
+ clf_model = clf_model.to(src_dtype)
1494
+ # Persist in config using the current (non-deprecated) field name
1495
+ config.dtype = str(src_dtype).replace("torch.", "")
1496
+
1497
+ return clf_model
modeling_embedding.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from transformers.modeling_outputs import BaseModelOutputWithPast
6
+
7
+ try:
8
+ # pyrefly: ignore [missing-import]
9
+ from .configuration_echo import EchoConfig
10
+
11
+ # pyrefly: ignore [missing-import]
12
+ from .modeling_echo import EchoModel, EchoPreTrainedModel
13
+ except ImportError:
14
+ from echo_dsrn.configuration_echo import EchoConfig
15
+ from echo_dsrn.modeling_echo import EchoModel, EchoPreTrainedModel
16
+
17
+
18
+ class EchoModelForSentenceEmbedding(EchoPreTrainedModel):
19
+ """
20
+ Sentence embedding adapter for Echo-DSRN.
21
+ Extracts the recurrent state 'c' or sequences from layers and shapes them
22
+ for sentence-transformers compatibility.
23
+ """
24
+
25
+ def __init__(self, config: EchoConfig):
26
+ super().__init__(config)
27
+ self.model = EchoModel(config)
28
+ self.pooling_mode = getattr(config, "pooling_mode", "c_T")
29
+
30
+ # Determine target dimension for the projection input
31
+ if self.pooling_mode == "hybrid":
32
+ proj_in_dim = config.hidden_size * (config.num_heads + 1)
33
+ elif self.pooling_mode == "mean_x_out":
34
+ proj_in_dim = config.hidden_size
35
+ else: # "c_T" or "mean_c_all"
36
+ proj_in_dim = config.hidden_size * config.num_heads
37
+
38
+ # Optional projection layer to map back to a specific target embedding dimension.
39
+ self.project_embeddings = getattr(config, "project_embeddings", False)
40
+ self.projection_mlp = getattr(config, "projection_mlp", False)
41
+ if self.projection_mlp:
42
+ target_dim = getattr(config, "embedding_dim", config.hidden_size)
43
+ hidden_dim = getattr(config, "projection_hidden_dim", 1024)
44
+ self.projection = nn.Sequential(
45
+ nn.Linear(proj_in_dim, hidden_dim),
46
+ nn.GELU(),
47
+ nn.Linear(hidden_dim, target_dim, bias=False),
48
+ )
49
+ elif self.project_embeddings:
50
+ target_dim = getattr(config, "embedding_dim", config.hidden_size)
51
+ self.projection = nn.Linear(proj_in_dim, target_dim, bias=False)
52
+ else:
53
+ self.projection = None
54
+
55
+ self.post_init()
56
+
57
+ def get_input_embeddings(self):
58
+ return self.model.embedding
59
+
60
+ def set_input_embeddings(self, value):
61
+ self.model.embedding = value
62
+
63
+ def forward(
64
+ self,
65
+ input_ids: Optional[torch.LongTensor] = None,
66
+ attention_mask: Optional[torch.LongTensor] = None,
67
+ position_ids: Optional[torch.LongTensor] = None,
68
+ past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
69
+ inputs_embeds: Optional[torch.FloatTensor] = None,
70
+ output_attentions: Optional[bool] = None,
71
+ output_hidden_states: Optional[bool] = None,
72
+ return_dict: Optional[bool] = None,
73
+ **kwargs,
74
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
75
+
76
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
77
+
78
+ pooling_mode = getattr(self.config, "pooling_mode", "c_T")
79
+ output_all_states = pooling_mode in ["mean_c_all", "hybrid"]
80
+
81
+ # 1. Base model forward pass
82
+ outputs = self.model(
83
+ input_ids=input_ids,
84
+ past_key_values=past_key_values,
85
+ inputs_embeds=inputs_embeds,
86
+ position_ids=position_ids,
87
+ output_attentions=output_attentions,
88
+ output_hidden_states=output_hidden_states,
89
+ return_dict=True,
90
+ output_all_states=output_all_states,
91
+ **kwargs,
92
+ )
93
+
94
+ # Determine sequence length for broadcasting
95
+ if input_ids is not None:
96
+ seq_len = input_ids.shape[1]
97
+ elif inputs_embeds is not None:
98
+ seq_len = inputs_embeds.shape[1]
99
+ else:
100
+ seq_len = 1
101
+
102
+ def mean_pooling(token_embeddings, mask):
103
+ input_mask_expanded = mask.unsqueeze(-1).expand(token_embeddings.size()).float()
104
+ sum_embeddings = torch.sum(token_embeddings * input_mask_expanded, 1)
105
+ sum_mask = input_mask_expanded.sum(1)
106
+ sum_mask = torch.clamp(sum_mask, min=1e-9)
107
+ return sum_embeddings / sum_mask
108
+
109
+ # 2. Extract and pool representations according to pooling_mode
110
+ if pooling_mode == "mean_c_all":
111
+ # Extract full sequence of recurrent slow states c_all from last layer
112
+ c_all = outputs.all_c_all[-1] # shape: (Batch, Seq_Len, State_Dim)
113
+ if attention_mask is not None:
114
+ pooled = mean_pooling(c_all, attention_mask)
115
+ else:
116
+ pooled = c_all.mean(dim=1)
117
+ elif pooling_mode == "mean_x_out":
118
+ # Mean pool the final hidden state
119
+ last_hidden_state = outputs.last_hidden_state # shape: (Batch, Seq_Len, hidden_size)
120
+ if attention_mask is not None:
121
+ pooled = mean_pooling(last_hidden_state, attention_mask)
122
+ else:
123
+ pooled = last_hidden_state.mean(dim=1)
124
+ elif pooling_mode == "hybrid":
125
+ # Concatenate pooled fast states (h_all) and slow states (c_all) from last layer
126
+ h_all = outputs.all_h_all[-1] # shape: (Batch, Seq_Len, hidden_size)
127
+ c_all = outputs.all_c_all[-1] # shape: (Batch, Seq_Len, State_Dim)
128
+ if attention_mask is not None:
129
+ pooled_h = mean_pooling(h_all, attention_mask)
130
+ pooled_c = mean_pooling(c_all, attention_mask)
131
+ else:
132
+ pooled_h = h_all.mean(dim=1)
133
+ pooled_c = c_all.mean(dim=1)
134
+ pooled = torch.cat(
135
+ [pooled_h, pooled_c], dim=-1
136
+ ) # shape: (Batch, hidden_size + State_Dim)
137
+ else: # "c_T" (default baseline behavior)
138
+ past = outputs.past_key_values
139
+ if hasattr(past, "__getitem__"):
140
+ last_layer_state = past[-1]
141
+ elif hasattr(past, "states"): # EchoCache support
142
+ last_layer_state = past.states[-1]
143
+ else:
144
+ raise ValueError("Could not extract recurrent state from model cache.")
145
+ pooled = last_layer_state[1] # shape: (Batch, State_Dim)
146
+
147
+ # 3. Apply optional projection
148
+ if self.projection is not None:
149
+ embeddings = self.projection(pooled)
150
+ else:
151
+ embeddings = pooled
152
+
153
+ # 4. Broadcast to shape (Batch, Seq_Len, Dim) for pooling safety
154
+ embeddings_3d = embeddings.unsqueeze(1).expand(-1, seq_len, -1)
155
+
156
+ if not return_dict:
157
+ return (embeddings_3d, outputs.past_key_values)
158
+
159
+ return BaseModelOutputWithPast(
160
+ last_hidden_state=embeddings_3d,
161
+ past_key_values=outputs.past_key_values,
162
+ hidden_states=outputs.hidden_states,
163
+ attentions=outputs.attentions,
164
+ )
modules.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.base.modules.transformer.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.sentence_transformer.modules.pooling.Pooling"
13
+ }
14
+ ]
sentence_bert_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "transformer_task": "feature-extraction",
3
+ "modality_config": {
4
+ "text": {
5
+ "method": "forward",
6
+ "method_output_name": "last_hidden_state"
7
+ }
8
+ },
9
+ "module_output_name": "token_embeddings"
10
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<s>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "eos_token": "<|endoftext|>",
6
+ "extra_special_tokens": [
7
+ "<tool_call>",
8
+ "</tool_call>",
9
+ "<tool_response>",
10
+ "</tool_response>",
11
+ "<tools>",
12
+ "</tools>"
13
+ ],
14
+ "fix_mistral_regex": true,
15
+ "is_local": true,
16
+ "legacy": false,
17
+ "max_length": 2048,
18
+ "model_max_length": 2048,
19
+ "pad_to_multiple_of": null,
20
+ "pad_token": "<|endoftext|>",
21
+ "pad_token_type_id": 0,
22
+ "padding_side": "left",
23
+ "sp_model_kwargs": {},
24
+ "stride": 0,
25
+ "tokenizer_class": "TokenizersBackend",
26
+ "truncation_side": "right",
27
+ "truncation_strategy": "longest_first",
28
+ "unk_token": "<unk>",
29
+ "use_default_system_prompt": false
30
+ }
triton_scan.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import triton
3
+ import triton.language as tl
4
+
5
+ # ──────────────────────────────────────────────────────────────
6
+ # FORWARD PASS KERNELS
7
+ # ──────────────────────────────────────────────────────────────
8
+
9
+
10
+ @triton.jit
11
+ def fwd_accumulate_kernel(
12
+ a_ptr,
13
+ b_ptr,
14
+ chunk_a_ptr,
15
+ chunk_c_ptr,
16
+ T,
17
+ D,
18
+ stride_a_b,
19
+ stride_a_t,
20
+ stride_a_d,
21
+ stride_b_b,
22
+ stride_b_t,
23
+ stride_b_d,
24
+ BLOCK_SIZE_D: tl.constexpr,
25
+ BLOCK_SIZE_T: tl.constexpr,
26
+ ):
27
+ pid_b = tl.program_id(0)
28
+ pid_d = tl.program_id(1)
29
+ pid_t = tl.program_id(2)
30
+
31
+ d_offsets = pid_d * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
32
+ d_mask = d_offsets < D
33
+
34
+ # Chunk boundaries
35
+ t_start = pid_t * BLOCK_SIZE_T
36
+
37
+ # Initialize local carries
38
+ a_acc = tl.full((BLOCK_SIZE_D,), 1.0, dtype=tl.float32)
39
+ c_acc = tl.zeros((BLOCK_SIZE_D,), dtype=tl.float32)
40
+
41
+ a_base = a_ptr + pid_b * stride_a_b + d_offsets * stride_a_d
42
+ b_base = b_ptr + pid_b * stride_b_b + d_offsets * stride_b_d
43
+
44
+ for i in range(BLOCK_SIZE_T):
45
+ t = t_start + i
46
+ if t < T:
47
+ a = tl.load(a_base + t * stride_a_t, mask=d_mask, other=1.0).to(tl.float32)
48
+ b = tl.load(b_base + t * stride_b_t, mask=d_mask, other=0.0).to(tl.float32)
49
+
50
+ # Combine: (a_acc, c_acc) o (a, b) = (a * a_acc, a * c_acc + b)
51
+ c_acc = a * c_acc + b
52
+ a_acc = a * a_acc
53
+
54
+ # Store chunk summaries
55
+ # chunk_ptr: [B, num_chunks, D]
56
+ num_chunks = (T + BLOCK_SIZE_T - 1) // BLOCK_SIZE_T
57
+ summary_idx = pid_b * (num_chunks * D) + pid_t * D + d_offsets
58
+ tl.store(chunk_a_ptr + summary_idx, a_acc, mask=d_mask)
59
+ tl.store(chunk_c_ptr + summary_idx, c_acc, mask=d_mask)
60
+
61
+
62
+ @triton.jit
63
+ def fwd_global_scan_kernel(
64
+ chunk_a_ptr,
65
+ chunk_c_ptr,
66
+ chunk_carries_ptr,
67
+ c_0_ptr,
68
+ num_chunks,
69
+ D,
70
+ stride_c0_b,
71
+ stride_c0_d,
72
+ HAS_C_0: tl.constexpr,
73
+ BLOCK_SIZE_D: tl.constexpr,
74
+ ):
75
+ pid_b = tl.program_id(0)
76
+ pid_d = tl.program_id(1)
77
+
78
+ d_offsets = pid_d * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
79
+ d_mask = d_offsets < D
80
+
81
+ # Initial carry
82
+ carry = tl.zeros((BLOCK_SIZE_D,), dtype=tl.float32)
83
+ if HAS_C_0:
84
+ c0_ptrs = c_0_ptr + pid_b * stride_c0_b + d_offsets * stride_c0_d
85
+ carry = tl.load(c0_ptrs, mask=d_mask, other=0.0).to(tl.float32)
86
+
87
+ # Base pointers for chunk summaries
88
+ chunk_base = pid_b * (num_chunks * D) + d_offsets
89
+
90
+ for j in range(num_chunks):
91
+ # Store carry into chunk j (this is c_{j-1})
92
+ tl.store(chunk_carries_ptr + chunk_base + j * D, carry, mask=d_mask)
93
+
94
+ # Load chunk summary
95
+ a_sum = tl.load(chunk_a_ptr + chunk_base + j * D, mask=d_mask, other=1.0).to(tl.float32)
96
+ c_sum = tl.load(chunk_c_ptr + chunk_base + j * D, mask=d_mask, other=0.0).to(tl.float32)
97
+
98
+ # Update carry for chunk j+1
99
+ carry = a_sum * carry + c_sum
100
+
101
+
102
+ @triton.jit
103
+ def fwd_combine_kernel(
104
+ a_ptr,
105
+ b_ptr,
106
+ chunk_carries_ptr,
107
+ c_out_ptr,
108
+ T,
109
+ D,
110
+ stride_a_b,
111
+ stride_a_t,
112
+ stride_a_d,
113
+ stride_b_b,
114
+ stride_b_t,
115
+ stride_b_d,
116
+ stride_c_b,
117
+ stride_c_t,
118
+ stride_c_d,
119
+ BLOCK_SIZE_D: tl.constexpr,
120
+ BLOCK_SIZE_T: tl.constexpr,
121
+ ):
122
+ pid_b = tl.program_id(0)
123
+ pid_d = tl.program_id(1)
124
+ pid_t = tl.program_id(2)
125
+
126
+ d_offsets = pid_d * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
127
+ d_mask = d_offsets < D
128
+
129
+ num_chunks = (T + BLOCK_SIZE_T - 1) // BLOCK_SIZE_T
130
+ t_start = pid_t * BLOCK_SIZE_T
131
+
132
+ # Load initial carry for this chunk
133
+ carry_idx = pid_b * (num_chunks * D) + pid_t * D + d_offsets
134
+ carry = tl.load(chunk_carries_ptr + carry_idx, mask=d_mask, other=0.0).to(tl.float32)
135
+
136
+ a_base = a_ptr + pid_b * stride_a_b + d_offsets * stride_a_d
137
+ b_base = b_ptr + pid_b * stride_b_b + d_offsets * stride_b_d
138
+ c_out_base = c_out_ptr + pid_b * stride_c_b + d_offsets * stride_c_d
139
+
140
+ for i in range(BLOCK_SIZE_T):
141
+ t = t_start + i
142
+ if t < T:
143
+ a = tl.load(a_base + t * stride_a_t, mask=d_mask, other=1.0).to(tl.float32)
144
+ b = tl.load(b_base + t * stride_b_t, mask=d_mask, other=0.0).to(tl.float32)
145
+
146
+ carry = a * carry + b
147
+ tl.store(c_out_base + t * stride_c_t, carry, mask=d_mask)
148
+
149
+
150
+ # ──────────────────────────────────────────────────────────────
151
+ # BACKWARD PASS KERNELS
152
+ # ──────────────────────────────────────────────────────────────
153
+
154
+
155
+ @triton.jit
156
+ def bwd_accumulate_kernel(
157
+ a_ptr,
158
+ grad_c_out_ptr,
159
+ chunk_a_prod_ptr,
160
+ chunk_g_sum_ptr,
161
+ T,
162
+ D,
163
+ stride_a_b,
164
+ stride_a_t,
165
+ stride_a_d,
166
+ stride_g_b,
167
+ stride_g_t,
168
+ stride_g_d,
169
+ BLOCK_SIZE_D: tl.constexpr,
170
+ BLOCK_SIZE_T: tl.constexpr,
171
+ ):
172
+ pid_b = tl.program_id(0)
173
+ pid_d = tl.program_id(1)
174
+ pid_t = tl.program_id(2)
175
+
176
+ d_offsets = pid_d * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
177
+ d_mask = d_offsets < D
178
+
179
+ t_start = pid_t * BLOCK_SIZE_T
180
+ t_end = tl.minimum(t_start + BLOCK_SIZE_T, T)
181
+
182
+ a_prod = tl.full((BLOCK_SIZE_D,), 1.0, dtype=tl.float32)
183
+ g_sum = tl.zeros((BLOCK_SIZE_D,), dtype=tl.float32)
184
+
185
+ a_base = a_ptr + pid_b * stride_a_b + d_offsets * stride_a_d
186
+ g_base = grad_c_out_ptr + pid_b * stride_g_b + d_offsets * stride_g_d
187
+
188
+ # Reverse sequential accumulation for chunk summary
189
+ # grad_c_start = (g_start + a_start+1*g_start+1 + ...) + (a_start+1*...*a_end) * grad_c_end
190
+ # We iterate from t_end-1 down to t_start
191
+ for i in range(t_end - t_start - 1, -1, -1):
192
+ t = t_start + i
193
+ g = tl.load(g_base + t * stride_g_t, mask=d_mask, other=0.0).to(tl.float32)
194
+
195
+ # Multiplier is a_{t+1}. If t is T-1, multiplier is 1.0 (or 0 if we assume grad_c_T=0)
196
+ # Actually, for the very last token in sequence, grad_c_T is 0.
197
+ a_next = tl.full((BLOCK_SIZE_D,), 1.0, dtype=tl.float32)
198
+ if t + 1 < T:
199
+ a_next = tl.load(a_base + (t + 1) * stride_a_t, mask=d_mask, other=1.0).to(tl.float32)
200
+
201
+ # combine: g_sum = g + a_next * g_sum, a_prod = a_next * a_prod
202
+ g_sum = g + a_next * g_sum
203
+ a_prod = a_next * a_prod
204
+
205
+ num_chunks = (T + BLOCK_SIZE_T - 1) // BLOCK_SIZE_T
206
+ summary_idx = pid_b * (num_chunks * D) + pid_t * D + d_offsets
207
+ tl.store(chunk_a_prod_ptr + summary_idx, a_prod, mask=d_mask)
208
+ tl.store(chunk_g_sum_ptr + summary_idx, g_sum, mask=d_mask)
209
+
210
+
211
+ @triton.jit
212
+ def bwd_global_scan_kernel(
213
+ chunk_a_prod_ptr,
214
+ chunk_g_sum_ptr,
215
+ chunk_grad_carries_ptr,
216
+ num_chunks,
217
+ D,
218
+ BLOCK_SIZE_D: tl.constexpr,
219
+ ):
220
+ pid_b = tl.program_id(0)
221
+ pid_d = tl.program_id(1)
222
+
223
+ d_offsets = pid_d * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
224
+ d_mask = d_offsets < D
225
+
226
+ grad_carry = tl.zeros((BLOCK_SIZE_D,), dtype=tl.float32)
227
+ chunk_base = pid_b * (num_chunks * D) + d_offsets
228
+
229
+ # Scan from last chunk to first
230
+ for j in range(num_chunks - 1, -1, -1):
231
+ # Store carry into chunk j (this is grad_c_{chunk_j_end})
232
+ tl.store(chunk_grad_carries_ptr + chunk_base + j * D, grad_carry, mask=d_mask)
233
+
234
+ a_prod = tl.load(chunk_a_prod_ptr + chunk_base + j * D, mask=d_mask, other=1.0).to(
235
+ tl.float32
236
+ )
237
+ g_sum = tl.load(chunk_g_sum_ptr + chunk_base + j * D, mask=d_mask, other=0.0).to(tl.float32)
238
+
239
+ # Update carry for chunk j-1
240
+ # grad_c_{t_start_of_chunk_j} = g_sum_chunk_j + a_prod_chunk_j * grad_c_{t_end_of_chunk_j}
241
+ grad_carry = g_sum + a_prod * grad_carry
242
+
243
+
244
+ @triton.jit
245
+ def bwd_combine_kernel(
246
+ a_ptr,
247
+ c_out_ptr,
248
+ c_0_ptr,
249
+ grad_c_out_ptr,
250
+ chunk_grad_carries_ptr,
251
+ grad_a_ptr,
252
+ grad_b_ptr,
253
+ grad_c_0_ptr,
254
+ T,
255
+ D,
256
+ stride_a_b,
257
+ stride_a_t,
258
+ stride_a_d,
259
+ stride_c_b,
260
+ stride_c_t,
261
+ stride_c_d,
262
+ stride_g_b,
263
+ stride_g_t,
264
+ stride_g_d,
265
+ stride_gb_b,
266
+ stride_gb_t,
267
+ stride_gb_d,
268
+ stride_c0_b,
269
+ stride_c0_d,
270
+ HAS_C_0: tl.constexpr,
271
+ BLOCK_SIZE_D: tl.constexpr,
272
+ BLOCK_SIZE_T: tl.constexpr,
273
+ ):
274
+ pid_b = tl.program_id(0)
275
+ pid_d = tl.program_id(1)
276
+ pid_t = tl.program_id(2)
277
+
278
+ d_offsets = pid_d * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
279
+ d_mask = d_offsets < D
280
+
281
+ num_chunks = (T + BLOCK_SIZE_T - 1) // BLOCK_SIZE_T
282
+ t_start = pid_t * BLOCK_SIZE_T
283
+ t_end = tl.minimum(t_start + BLOCK_SIZE_T, T)
284
+
285
+ # Load initial gradient carry (this is grad_c_{t_end})
286
+ # This was computed as grad_c_end in Pass 2.
287
+ grad_at_tend = tl.load(
288
+ chunk_grad_carries_ptr + pid_b * (num_chunks * D) + pid_t * D + d_offsets,
289
+ mask=d_mask,
290
+ other=0.0,
291
+ ).to(tl.float32)
292
+
293
+ a_base = a_ptr + pid_b * stride_a_b + d_offsets * stride_a_d
294
+ c_out_base = c_out_ptr + pid_b * stride_c_b + d_offsets * stride_c_d
295
+ g_base = grad_c_out_ptr + pid_b * stride_g_b + d_offsets * stride_g_d
296
+ ga_base = grad_a_ptr + pid_b * stride_a_b + d_offsets * stride_a_d
297
+ gb_base = grad_b_ptr + pid_b * stride_gb_b + d_offsets * stride_gb_d
298
+
299
+ # running_grad enters index t as a_{t+1} * grad_c_{t+1}
300
+ # For the very last token in chunk t=t_end-1, we need a_{t_end} * grad_c_{t_end}
301
+ a_tend = tl.full((BLOCK_SIZE_D,), 1.0, dtype=tl.float32)
302
+ if t_end < T:
303
+ a_tend = tl.load(a_base + t_end * stride_a_t, mask=d_mask, other=1.0).to(tl.float32)
304
+
305
+ running_grad = a_tend * grad_at_tend
306
+
307
+ # Reverse scan within chunk
308
+ for i in range(t_end - t_start - 1, -1, -1):
309
+ t = t_start + i
310
+ g_out_t = tl.load(g_base + t * stride_g_t, mask=d_mask, other=0.0).to(tl.float32)
311
+
312
+ # grad_c_t = g_out_t + a_{t+1} * grad_c_{t+1}
313
+ # In our loop, running_grad is always (a_{t+1} * grad_c_{t+1})
314
+ grad_c_t = g_out_t + running_grad
315
+
316
+ # Store results
317
+ # grad_b_t = grad_c_t
318
+ tl.store(gb_base + t * stride_gb_t, grad_c_t, mask=d_mask)
319
+
320
+ # grad_a_t = c_{t-1} * grad_c_t
321
+ c_prev = tl.zeros((BLOCK_SIZE_D,), dtype=tl.float32)
322
+ if t > 0:
323
+ c_prev = tl.load(c_out_base + (t - 1) * stride_c_t, mask=d_mask, other=0.0).to(
324
+ tl.float32
325
+ )
326
+ elif HAS_C_0:
327
+ c_prev = tl.load(
328
+ c_0_ptr + pid_b * stride_c0_b + d_offsets * stride_c0_d, mask=d_mask, other=0.0
329
+ ).to(tl.float32)
330
+
331
+ tl.store(ga_base + t * stride_a_t, c_prev * grad_c_t, mask=d_mask)
332
+
333
+ # update running_grad for the next iteration (t-1)
334
+ # new running_grad = a_t * grad_c_t
335
+ a_t = tl.load(a_base + t * stride_a_t, mask=d_mask, other=1.0).to(tl.float32)
336
+ running_grad = a_t * grad_c_t
337
+
338
+ # Final carry for d_c0 if pid_t == 0
339
+ if pid_t == 0 and HAS_C_0:
340
+ # After loop for t=0, running_grad is a_0 * grad_c_0
341
+ tl.store(
342
+ grad_c_0_ptr + pid_b * stride_c0_b + d_offsets * stride_c0_d, running_grad, mask=d_mask
343
+ )
344
+
345
+
346
+ # ──────────────────────────────────────────────────────────────
347
+ # PYTORCH WRAPPER
348
+ # ──────────────────────────────────────────────────────────────
349
+
350
+
351
+ class DSRNScanTriton(torch.autograd.Function):
352
+ @staticmethod
353
+ def forward(ctx, a, b, c_0=None):
354
+ B, T, D = a.shape
355
+ device = a.device
356
+
357
+ a = a.contiguous()
358
+ b = b.contiguous()
359
+ if c_0 is not None:
360
+ c_0 = c_0.contiguous()
361
+
362
+ c_out = torch.empty_like(a)
363
+
364
+ BLOCK_SIZE_T = 64
365
+ BLOCK_SIZE_D = triton.next_power_of_2(min(128, D))
366
+ num_chunks = (T + BLOCK_SIZE_T - 1) // BLOCK_SIZE_T
367
+
368
+ # Temporary workspace
369
+ chunk_a = torch.empty((B, num_chunks, D), device=device, dtype=torch.float32)
370
+ chunk_c = torch.empty((B, num_chunks, D), device=device, dtype=torch.float32)
371
+ chunk_carries = torch.empty((B, num_chunks, D), device=device, dtype=torch.float32)
372
+
373
+ # Pass 1: Accumulate
374
+ grid1 = (B, triton.cdiv(D, BLOCK_SIZE_D), num_chunks)
375
+ fwd_accumulate_kernel[grid1](
376
+ a,
377
+ b,
378
+ chunk_a,
379
+ chunk_c,
380
+ T,
381
+ D,
382
+ a.stride(0),
383
+ a.stride(1),
384
+ a.stride(2),
385
+ b.stride(0),
386
+ b.stride(1),
387
+ b.stride(2),
388
+ BLOCK_SIZE_D,
389
+ BLOCK_SIZE_T,
390
+ )
391
+
392
+ # Pass 2: Global Scan
393
+ grid2 = (B, triton.cdiv(D, BLOCK_SIZE_D))
394
+ fwd_global_scan_kernel[grid2](
395
+ chunk_a,
396
+ chunk_c,
397
+ chunk_carries,
398
+ c_0,
399
+ num_chunks,
400
+ D,
401
+ c_0.stride(0) if c_0 is not None else 0,
402
+ c_0.stride(1) if c_0 is not None else 0,
403
+ HAS_C_0=(c_0 is not None),
404
+ BLOCK_SIZE_D=BLOCK_SIZE_D,
405
+ )
406
+
407
+ # Pass 3: Combine
408
+ fwd_combine_kernel[grid1](
409
+ a,
410
+ b,
411
+ chunk_carries,
412
+ c_out,
413
+ T,
414
+ D,
415
+ a.stride(0),
416
+ a.stride(1),
417
+ a.stride(2),
418
+ b.stride(0),
419
+ b.stride(1),
420
+ b.stride(2),
421
+ c_out.stride(0),
422
+ c_out.stride(1),
423
+ c_out.stride(2),
424
+ BLOCK_SIZE_D,
425
+ BLOCK_SIZE_T,
426
+ )
427
+
428
+ ctx.save_for_backward(a, c_out, c_0)
429
+ ctx.BLOCK_SIZE_T = BLOCK_SIZE_T
430
+ ctx.BLOCK_SIZE_D = BLOCK_SIZE_D
431
+
432
+ return c_out
433
+
434
+ @staticmethod
435
+ def backward(ctx, grad_c_out):
436
+ a, c_out, c_0 = ctx.saved_tensors
437
+ B, T, D = a.shape
438
+ device = a.device
439
+
440
+ grad_c_out = grad_c_out.contiguous()
441
+ grad_a = torch.empty_like(a)
442
+ grad_b = torch.empty_like(a)
443
+ grad_c_0 = torch.zeros_like(c_0) if c_0 is not None else None
444
+
445
+ BLOCK_SIZE_T = ctx.BLOCK_SIZE_T
446
+ BLOCK_SIZE_D = ctx.BLOCK_SIZE_D
447
+ num_chunks = (T + BLOCK_SIZE_T - 1) // BLOCK_SIZE_T
448
+
449
+ chunk_grad_a = torch.empty((B, num_chunks, D), device=device, dtype=torch.float32)
450
+ chunk_grad_x = torch.empty((B, num_chunks, D), device=device, dtype=torch.float32)
451
+ chunk_grad_carries = torch.empty((B, num_chunks, D), device=device, dtype=torch.float32)
452
+
453
+ grid1 = (B, triton.cdiv(D, BLOCK_SIZE_D), num_chunks)
454
+
455
+ # Pass 1: Accumulate
456
+ bwd_accumulate_kernel[grid1](
457
+ a,
458
+ grad_c_out,
459
+ chunk_grad_a,
460
+ chunk_grad_x,
461
+ T,
462
+ D,
463
+ a.stride(0),
464
+ a.stride(1),
465
+ a.stride(2),
466
+ grad_c_out.stride(0),
467
+ grad_c_out.stride(1),
468
+ grad_c_out.stride(2),
469
+ BLOCK_SIZE_D,
470
+ BLOCK_SIZE_T,
471
+ )
472
+
473
+ # Pass 2: Global Scan
474
+ grid2 = (B, triton.cdiv(D, BLOCK_SIZE_D))
475
+ bwd_global_scan_kernel[grid2](
476
+ chunk_grad_a, chunk_grad_x, chunk_grad_carries, num_chunks, D, BLOCK_SIZE_D
477
+ )
478
+
479
+ # Pass 3: Combine
480
+ bwd_combine_kernel[grid1](
481
+ a,
482
+ c_out,
483
+ c_0,
484
+ grad_c_out,
485
+ chunk_grad_carries,
486
+ grad_a,
487
+ grad_b,
488
+ grad_c_0,
489
+ T,
490
+ D,
491
+ a.stride(0),
492
+ a.stride(1),
493
+ a.stride(2),
494
+ c_out.stride(0),
495
+ c_out.stride(1),
496
+ c_out.stride(2),
497
+ grad_c_out.stride(0),
498
+ grad_c_out.stride(1),
499
+ grad_c_out.stride(2),
500
+ grad_b.stride(0),
501
+ grad_b.stride(1),
502
+ grad_b.stride(2),
503
+ c_0.stride(0) if c_0 is not None else 0,
504
+ c_0.stride(1) if c_0 is not None else 0,
505
+ HAS_C_0=(c_0 is not None),
506
+ BLOCK_SIZE_D=BLOCK_SIZE_D,
507
+ BLOCK_SIZE_T=BLOCK_SIZE_T,
508
+ )
509
+
510
+ return grad_a, grad_b, grad_c_0
511
+
512
+
513
+ def triton_dsrn_parallel_scan(g_t, m_t, c_0=None):
514
+ orig_dtype = g_t.dtype
515
+ a = (1.0 - g_t).float()
516
+ b = (g_t * m_t).float()
517
+ if c_0 is not None:
518
+ c_0 = c_0.float()
519
+
520
+ out = DSRNScanTriton.apply(a, b, c_0)
521
+ return out.to(orig_dtype)