cijov commited on
Commit
b5fcd7c
·
verified ·
1 Parent(s): 9c65f16

Sienna-v2.0: initial release (LoRA merged into standalone checkpoint, CijovLang architecture)

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ model/tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2026 Cijov
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright [yyyy] [name of copyright owner]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ Sienna-v2.0
2
+ Copyright 2026 Cijov
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
5
+ You may not use this file except in compliance with the License.
6
+ You should have received a copy of the License in the LICENSE file.
7
+
8
+ Sienna-v2.0 is a LoRA fine-tune of cijov/cijov-lang-1B-1V
9
+ (https://huggingface.co/cijov/cijov-lang-1B-1V), merged into a standalone
10
+ checkpoint. See that repo's own NOTICE for the backbone's provenance.
README.md ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ - fr
6
+ - es
7
+ - ro
8
+ base_model: cijov/cijov-lang-1B-1V
9
+ pipeline_tag: text-generation
10
+ tags:
11
+ - children-stories
12
+ - multilingual
13
+ ---
14
+
15
+ # Sienna-v2.0
16
+
17
+ Sienna is a children's-story generator fine-tuned on top of
18
+ [cijov/cijov-lang-1B-1V](https://huggingface.co/cijov/cijov-lang-1B-1V), a
19
+ ~1.2B parameter model. This release is a LoRA fine-tune merged into a
20
+ standalone checkpoint — no `peft` dependency needed to use it.
21
+
22
+ Supports 4 languages (English, French, Spanish, Romanian) across 5 story
23
+ genres (bedtime, animals, friendship, fantasy, general), selected via the
24
+ system prompt.
25
+
26
+ ## Usage
27
+
28
+ ```python
29
+ import torch
30
+ from transformers import AutoModelForCausalLM, AutoTokenizer
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained("cijov/Sienna-v2.0", subfolder="model")
33
+ model = AutoModelForCausalLM.from_pretrained(
34
+ "cijov/Sienna-v2.0", subfolder="model", trust_remote_code=True, dtype=torch.bfloat16
35
+ ).to("cuda")
36
+
37
+ messages = [
38
+ {"role": "system", "content": (
39
+ "You are Sienna, a children's story writer. "
40
+ "Write a short magical fairy-tale for a young child. "
41
+ "Use simple words and a wondrous, friendly tone. "
42
+ "Respond only in Romanian."
43
+ )},
44
+ {"role": "user", "content": "Tell me a magical fairy tale."},
45
+ ]
46
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False) + "\n"
47
+ inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
48
+ out = model.generate(**inputs, max_new_tokens=300, do_sample=True, temperature=0.8, top_p=0.9, top_k=50, repetition_penalty=1.15)
49
+ print(tokenizer.decode(out[0][inputs.input_ids.shape[1]:], skip_special_tokens=True))
50
+ ```
51
+
52
+ Or use the included standalone script:
53
+
54
+ ```bash
55
+ python generate.py --genre fantasy --lang ro
56
+ ```
57
+
58
+ `trust_remote_code=True` is required — the backbone (`cijov/cijov-lang-1B-1V`)
59
+ is published as its own standalone architecture, not a stock `transformers`
60
+ class.
61
+
62
+ ## Genres and languages
63
+
64
+ | genre | system prompt intent |
65
+ |---|---|
66
+ | `bedtime` | calm, soothing, peaceful ending |
67
+ | `animals` | fun, simple, happy ending |
68
+ | `friendship` | warm, kindness/sharing, gentle lesson |
69
+ | `fantasy` | magical fairy-tale, wondrous tone |
70
+ | `general` | short, simple, age-appropriate |
71
+
72
+ Select a language by appending `Respond only in <Language>.` to the system
73
+ prompt (English / French / Spanish / Romanian) — see `generate.py`.
74
+
75
+ ## Known limitations
76
+
77
+ **Romanian quality lags the other three languages.** This is inherited from
78
+ the base backbone's own pretraining — Romanian started with substantially
79
+ higher perplexity and lower QA accuracy than English/French/Spanish before
80
+ Sienna's fine-tuning ever touched it, and additional fine-tuning does not
81
+ close that gap (confirmed via a dedicated experiment: extending training
82
+ specifically to test this left Romanian perplexity flat across 6,000+
83
+ further steps). Concretely, on held-out validation text: English ppl ≈ 11.8,
84
+ Spanish ≈ 17.2, French ≈ 26.3, Romanian ≈ 81.6. Closing this gap requires
85
+ additional Romanian-language pretraining in the backbone itself, not further
86
+ Sienna-side fine-tuning.
87
+
88
+ **Genre adherence is moderate, not high**, and varies by language/genre —
89
+ measured via keyword-based classification on generated samples (grand
90
+ average ~48% across languages/genres, "general" genre excluded from scoring
91
+ since it has no positive keyword signal of its own). Diversity and
92
+ repetition metrics are strong across the board (distinct-2 ≈ 0.96-0.98,
93
+ 4-gram repetition ≈ 0.00), and a small multilingual safety-keyword check
94
+ found near-zero hits — the model reliably avoids degenerate/repetitive
95
+ output and unsafe content, but doesn't always hit the requested genre on the
96
+ first try. Occasional short glued-fragment artifacts (a stray foreign-
97
+ language word fused into an otherwise-correct sentence) can appear rarely;
98
+ this is a known, low-frequency noise-floor characteristic rather than a
99
+ systematic language-mixing failure — the model's own generation stays
100
+ correctly in the requested language in the large majority of samples.
101
+
102
+ ## Training
103
+
104
+ - Base: `cijov/cijov-lang-1B-1V`, frozen, LoRA rank 64.
105
+ - Data: `roneneldan/TinyStories` (en), `ffuuugor/tinystories_spanish` +
106
+ fairy-tale sources (es), `iproskurina/TinyStories-French` + fairy-tale
107
+ sources (fr), `readerbench/ro-stories` + fairy-tale + synthetic sources
108
+ (ro). Under/over-represented languages and sources are oversampled to
109
+ roughly equal effective training volume.
110
+ - Genre labels are auto-assigned via multilingual keyword matching over the
111
+ story text at data-prep time, then encoded into the system prompt for
112
+ training and inference alike.
113
+ - SFT with chat-template label masking (loss only on assistant tokens).
114
+
115
+ ## License
116
+
117
+ Apache 2.0, matching the base backbone. See `LICENSE`/`NOTICE`.
configuration_cijov_lang.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Cijov
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Cijov-lang model configuration.
15
+
16
+ Cijov-lang is trained via Megatron-LM using a Qwen3-compatible architecture
17
+ for training-infrastructure compatibility, then exported/published as its
18
+ own standalone architecture -- this file has no dependency on transformers'
19
+ Qwen3 implementation.
20
+ """
21
+
22
+ from huggingface_hub.dataclasses import strict
23
+
24
+ from transformers.configuration_utils import PreTrainedConfig
25
+ from transformers.modeling_rope_utils import RopeParameters
26
+ from transformers.utils import auto_docstring
27
+
28
+
29
+ @auto_docstring(checkpoint="cijov/cijov-lang-1B-1V")
30
+ @strict
31
+ class CijovLangConfig(PreTrainedConfig):
32
+ r"""
33
+ ```python
34
+ >>> from modeling_cijov_lang import CijovLangModel
35
+ >>> from configuration_cijov_lang import CijovLangConfig
36
+
37
+ >>> # Initializing a Cijov-lang style configuration
38
+ >>> configuration = CijovLangConfig()
39
+
40
+ >>> # Initializing a model from the configuration
41
+ >>> model = CijovLangModel(configuration)
42
+
43
+ >>> # Accessing the model configuration
44
+ >>> configuration = model.config
45
+ ```
46
+ """
47
+
48
+ model_type = "cijov_lang"
49
+ keys_to_ignore_at_inference = ["past_key_values"]
50
+
51
+ base_model_tp_plan = {
52
+ "layers.*.attention.query_proj": "colwise",
53
+ "layers.*.attention.key_proj": "colwise",
54
+ "layers.*.attention.value_proj": "colwise",
55
+ "layers.*.attention.query_norm": "replicated_with_grad_allreduce",
56
+ "layers.*.attention.key_norm": "replicated_with_grad_allreduce",
57
+ "layers.*.attention.output_proj": "rowwise",
58
+ "layers.*.feed_forward.gate_proj": "colwise",
59
+ "layers.*.feed_forward.up_proj": "colwise",
60
+ "layers.*.feed_forward.down_proj": "rowwise",
61
+ }
62
+ base_model_pp_plan = {
63
+ "token_embeddings": (["input_ids"], ["inputs_embeds"]),
64
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
65
+ "final_norm": (["hidden_states"], ["hidden_states"]),
66
+ }
67
+
68
+ vocab_size: int = 151936
69
+ hidden_size: int = 1280
70
+ intermediate_size: int = 4608
71
+ num_hidden_layers: int = 36
72
+ num_attention_heads: int = 20
73
+ num_key_value_heads: int | None = 10
74
+ head_dim: int = 128
75
+ hidden_act: str = "silu"
76
+ max_position_embeddings: int = 32768
77
+ initializer_range: float = 0.02
78
+ rms_norm_eps: float = 1e-6
79
+ use_cache: bool = True
80
+ tie_word_embeddings: bool = True
81
+ rope_parameters: RopeParameters | dict | None = None
82
+ attention_bias: bool = True
83
+ use_sliding_window: bool = False
84
+ sliding_window: int | None = 4096
85
+ max_window_layers: int = 28
86
+ layer_types: list[str] | None = None
87
+ attention_dropout: float | int = 0.0
88
+ pad_token_id: int | None = None
89
+ bos_token_id: int | None = None
90
+ eos_token_id: int | list[int] | None = None
91
+
92
+ def __post_init__(self, **kwargs):
93
+ self.sliding_window = self.sliding_window if self.use_sliding_window else None
94
+ if self.num_key_value_heads is None:
95
+ self.num_key_value_heads = self.num_attention_heads
96
+
97
+ if self.layer_types is None:
98
+ self.layer_types = [
99
+ "sliding_attention"
100
+ if self.sliding_window is not None and i >= self.max_window_layers
101
+ else "full_attention"
102
+ for i in range(self.num_hidden_layers)
103
+ ]
104
+ super().__post_init__(**kwargs)
105
+
106
+
107
+ __all__ = ["CijovLangConfig"]
generate.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal standalone inference script for Sienna-v2.0.
2
+
3
+ python generate.py --genre fantasy --lang ro
4
+ python generate.py --genre bedtime --lang en --prompt "Tell me about a sleepy fox."
5
+ """
6
+ import argparse
7
+
8
+ import torch
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer
10
+
11
+ LANGUAGE_NAMES = {"en": "English", "fr": "French", "es": "Spanish", "ro": "Romanian"}
12
+
13
+ GENRES = {
14
+ "bedtime": {
15
+ "system": (
16
+ "You are Sienna, a gentle children's story writer. "
17
+ "Write a calm, soothing bedtime story for a young child. "
18
+ "Use simple words, slow rhythm, and a peaceful ending."
19
+ ),
20
+ "default_user": "Tell me a gentle bedtime story.",
21
+ },
22
+ "animals": {
23
+ "system": (
24
+ "You are Sienna, a children's story writer. "
25
+ "Write a fun, simple story about animals for a toddler. "
26
+ "Use short sentences and a happy ending."
27
+ ),
28
+ "default_user": "Tell me a fun story about animals.",
29
+ },
30
+ "friendship": {
31
+ "system": (
32
+ "You are Sienna, a children's story writer. "
33
+ "Write a warm story about friendship, sharing, or kindness "
34
+ "for a toddler. Keep it simple and end with a gentle lesson."
35
+ ),
36
+ "default_user": "Tell me a story about friends sharing.",
37
+ },
38
+ "fantasy": {
39
+ "system": (
40
+ "You are Sienna, a children's story writer. "
41
+ "Write a short magical fairy-tale for a young child. "
42
+ "Use simple words and a wondrous, friendly tone."
43
+ ),
44
+ "default_user": "Tell me a magical fairy tale.",
45
+ },
46
+ "general": {
47
+ "system": (
48
+ "You are Sienna, a children's story writer. "
49
+ "Write a short, simple, age-appropriate story for a young child."
50
+ ),
51
+ "default_user": "Tell me a short story for a young child.",
52
+ },
53
+ }
54
+
55
+
56
+ def build_messages(genre: str, prompt: str, lang: str):
57
+ cfg = GENRES[genre]
58
+ user = prompt.strip() if prompt else cfg["default_user"]
59
+ system = cfg["system"]
60
+ lang_name = LANGUAGE_NAMES.get(lang)
61
+ if lang_name:
62
+ system = f"{system} Respond only in {lang_name}."
63
+ return [{"role": "system", "content": system}, {"role": "user", "content": user}]
64
+
65
+
66
+ def main():
67
+ p = argparse.ArgumentParser()
68
+ p.add_argument("--model", default="cijov/Sienna-v2.0")
69
+ p.add_argument("--subfolder", default="model")
70
+ p.add_argument("--genre", default="bedtime", choices=list(GENRES))
71
+ p.add_argument("--lang", default="en", choices=list(LANGUAGE_NAMES))
72
+ p.add_argument("--prompt", default="")
73
+ p.add_argument("--max_new_tokens", type=int, default=300)
74
+ p.add_argument("--temperature", type=float, default=0.8)
75
+ p.add_argument("--top_p", type=float, default=0.9)
76
+ p.add_argument("--top_k", type=int, default=50)
77
+ p.add_argument("--repetition_penalty", type=float, default=1.15)
78
+ args = p.parse_args()
79
+
80
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
81
+ tokenizer = AutoTokenizer.from_pretrained(args.model, subfolder=args.subfolder)
82
+ model = AutoModelForCausalLM.from_pretrained(
83
+ args.model, subfolder=args.subfolder, trust_remote_code=True, dtype=torch.bfloat16
84
+ ).to(device).eval()
85
+
86
+ messages = build_messages(args.genre, args.prompt, args.lang)
87
+ prompt_text = tokenizer.apply_chat_template(
88
+ messages, tokenize=False, add_generation_prompt=True, enable_thinking=False
89
+ )
90
+ # A trailing newline avoids a leading-token generation glitch seen
91
+ # without it -- keep this even though it looks redundant.
92
+ prompt_text += "\n"
93
+ inputs = tokenizer(prompt_text, return_tensors="pt").to(device)
94
+
95
+ with torch.no_grad():
96
+ out = model.generate(
97
+ **inputs,
98
+ max_new_tokens=args.max_new_tokens,
99
+ do_sample=True,
100
+ temperature=args.temperature,
101
+ top_p=args.top_p,
102
+ top_k=args.top_k,
103
+ repetition_penalty=args.repetition_penalty,
104
+ pad_token_id=tokenizer.pad_token_id,
105
+ eos_token_id=tokenizer.eos_token_id,
106
+ )
107
+ text = tokenizer.decode(out[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
108
+ print(text)
109
+
110
+
111
+ if __name__ == "__main__":
112
+ main()
model/chat_template.jinja ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- for message in messages -%}
2
+ {%- if message['role'] == 'system' -%}
3
+ <|im_start|>system
4
+ {{ message['content'] }}<|im_end|>
5
+ {% elif message['role'] == 'user' -%}
6
+ <|im_start|>user
7
+ {{ message['content'] }}<|im_end|>
8
+ {% elif message['role'] == 'assistant' -%}
9
+ <|im_start|>assistant
10
+ {{ message['content'] }}<|im_end|>
11
+ {% endif -%}
12
+ {%- endfor -%}
13
+ {%- if add_generation_prompt -%}
14
+ <|im_start|>assistant
15
+ {%- endif -%}
model/config.json ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "CijovLangForCausalLM"
4
+ ],
5
+ "attention_bias": true,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_cijov_lang.CijovLangConfig",
9
+ "AutoModelForCausalLM": "modeling_cijov_lang.CijovLangForCausalLM"
10
+ },
11
+ "bos_token_id": null,
12
+ "dtype": "bfloat16",
13
+ "eos_token_id": null,
14
+ "head_dim": 128,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 1280,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 4608,
19
+ "layer_types": [
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention",
35
+ "full_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "full_attention",
39
+ "full_attention",
40
+ "full_attention",
41
+ "full_attention",
42
+ "full_attention",
43
+ "full_attention",
44
+ "full_attention",
45
+ "full_attention",
46
+ "full_attention",
47
+ "full_attention",
48
+ "full_attention",
49
+ "full_attention",
50
+ "full_attention",
51
+ "full_attention",
52
+ "full_attention",
53
+ "full_attention",
54
+ "full_attention",
55
+ "full_attention"
56
+ ],
57
+ "max_position_embeddings": 32768,
58
+ "max_window_layers": 28,
59
+ "model_type": "cijov_lang",
60
+ "num_attention_heads": 20,
61
+ "num_hidden_layers": 36,
62
+ "num_key_value_heads": 10,
63
+ "pad_token_id": null,
64
+ "rms_norm_eps": 1e-06,
65
+ "rope_parameters": {
66
+ "rope_theta": 1000000.0,
67
+ "rope_type": "default"
68
+ },
69
+ "sliding_window": null,
70
+ "tie_word_embeddings": true,
71
+ "transformers_version": "5.9.0",
72
+ "use_cache": true,
73
+ "use_sliding_window": false,
74
+ "vocab_size": 151936
75
+ }
model/configuration_cijov_lang.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Cijov
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Cijov-lang model configuration.
15
+
16
+ Cijov-lang is trained via Megatron-LM using a Qwen3-compatible architecture
17
+ for training-infrastructure compatibility, then exported/published as its
18
+ own standalone architecture -- this file has no dependency on transformers'
19
+ Qwen3 implementation.
20
+ """
21
+
22
+ from huggingface_hub.dataclasses import strict
23
+
24
+ from transformers.configuration_utils import PreTrainedConfig
25
+ from transformers.modeling_rope_utils import RopeParameters
26
+ from transformers.utils import auto_docstring
27
+
28
+
29
+ @auto_docstring(checkpoint="cijov/cijov-lang-1B-1V")
30
+ @strict
31
+ class CijovLangConfig(PreTrainedConfig):
32
+ r"""
33
+ ```python
34
+ >>> from modeling_cijov_lang import CijovLangModel
35
+ >>> from configuration_cijov_lang import CijovLangConfig
36
+
37
+ >>> # Initializing a Cijov-lang style configuration
38
+ >>> configuration = CijovLangConfig()
39
+
40
+ >>> # Initializing a model from the configuration
41
+ >>> model = CijovLangModel(configuration)
42
+
43
+ >>> # Accessing the model configuration
44
+ >>> configuration = model.config
45
+ ```
46
+ """
47
+
48
+ model_type = "cijov_lang"
49
+ keys_to_ignore_at_inference = ["past_key_values"]
50
+
51
+ base_model_tp_plan = {
52
+ "layers.*.attention.query_proj": "colwise",
53
+ "layers.*.attention.key_proj": "colwise",
54
+ "layers.*.attention.value_proj": "colwise",
55
+ "layers.*.attention.query_norm": "replicated_with_grad_allreduce",
56
+ "layers.*.attention.key_norm": "replicated_with_grad_allreduce",
57
+ "layers.*.attention.output_proj": "rowwise",
58
+ "layers.*.feed_forward.gate_proj": "colwise",
59
+ "layers.*.feed_forward.up_proj": "colwise",
60
+ "layers.*.feed_forward.down_proj": "rowwise",
61
+ }
62
+ base_model_pp_plan = {
63
+ "token_embeddings": (["input_ids"], ["inputs_embeds"]),
64
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
65
+ "final_norm": (["hidden_states"], ["hidden_states"]),
66
+ }
67
+
68
+ vocab_size: int = 151936
69
+ hidden_size: int = 1280
70
+ intermediate_size: int = 4608
71
+ num_hidden_layers: int = 36
72
+ num_attention_heads: int = 20
73
+ num_key_value_heads: int | None = 10
74
+ head_dim: int = 128
75
+ hidden_act: str = "silu"
76
+ max_position_embeddings: int = 32768
77
+ initializer_range: float = 0.02
78
+ rms_norm_eps: float = 1e-6
79
+ use_cache: bool = True
80
+ tie_word_embeddings: bool = True
81
+ rope_parameters: RopeParameters | dict | None = None
82
+ attention_bias: bool = True
83
+ use_sliding_window: bool = False
84
+ sliding_window: int | None = 4096
85
+ max_window_layers: int = 28
86
+ layer_types: list[str] | None = None
87
+ attention_dropout: float | int = 0.0
88
+ pad_token_id: int | None = None
89
+ bos_token_id: int | None = None
90
+ eos_token_id: int | list[int] | None = None
91
+
92
+ def __post_init__(self, **kwargs):
93
+ self.sliding_window = self.sliding_window if self.use_sliding_window else None
94
+ if self.num_key_value_heads is None:
95
+ self.num_key_value_heads = self.num_attention_heads
96
+
97
+ if self.layer_types is None:
98
+ self.layer_types = [
99
+ "sliding_attention"
100
+ if self.sliding_window is not None and i >= self.max_window_layers
101
+ else "full_attention"
102
+ for i in range(self.num_hidden_layers)
103
+ ]
104
+ super().__post_init__(**kwargs)
105
+
106
+
107
+ __all__ = ["CijovLangConfig"]
model/generation_config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "5.9.0",
4
+ "use_cache": true
5
+ }
model/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e914a49bf5b06bc6a48f903126de6c1e3b94afeb8d9023dff0dcf644fdc73200
3
+ size 2371494120
model/modeling_cijov_lang.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Cijov
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Cijov-lang model.
15
+
16
+ Same underlying transformer math as the architecture used to train this
17
+ model via Megatron-LM (Qwen3-compatible, for training-infrastructure
18
+ compatibility only), but published as its own standalone architecture: no
19
+ import from transformers' Qwen3 implementation, and module names below
20
+ (attention/feed_forward/query_proj/... instead of self_attn/mlp/q_proj/...)
21
+ are Cijov-lang's own, not inherited Qwen naming -- so the state dict keys of
22
+ a Cijov-lang checkpoint are genuinely distinct from a Qwen3 one, not just the
23
+ class names.
24
+ """
25
+
26
+ from collections.abc import Callable
27
+ from typing import Optional
28
+
29
+ import torch
30
+ from torch import nn
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.generation import GenerationMixin
35
+ from transformers.integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
36
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
37
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
38
+ from transformers.modeling_layers import GradientCheckpointingLayer
39
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
40
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
41
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from transformers.processing_utils import Unpack
43
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
44
+ from transformers.utils.generic import maybe_autocast, merge_with_config_defaults
45
+ from transformers.utils.output_capturing import capture_outputs
46
+
47
+ from .configuration_cijov_lang import CijovLangConfig
48
+
49
+
50
+ @use_kernel_forward_from_hub("RMSNorm")
51
+ class CijovLangRMSNorm(nn.Module):
52
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
53
+ super().__init__()
54
+ self.weight = nn.Parameter(torch.ones(hidden_size))
55
+ self.variance_epsilon = eps
56
+
57
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
58
+ input_dtype = hidden_states.dtype
59
+ hidden_states = hidden_states.to(torch.float32)
60
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
61
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
62
+ return self.weight * hidden_states.to(input_dtype)
63
+
64
+ def extra_repr(self):
65
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
66
+
67
+
68
+ class CijovLangFeedForward(nn.Module):
69
+ def __init__(self, config):
70
+ super().__init__()
71
+ self.config = config
72
+ self.hidden_size = config.hidden_size
73
+ self.intermediate_size = config.intermediate_size
74
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
75
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
76
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
77
+ self.act_fn = ACT2FN[config.hidden_act]
78
+
79
+ def forward(self, x):
80
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
81
+
82
+
83
+ class CijovLangRotaryEmbedding(nn.Module):
84
+ inv_freq: torch.Tensor
85
+
86
+ def __init__(self, config: CijovLangConfig, device=None):
87
+ super().__init__()
88
+ self.max_seq_len_cached = config.max_position_embeddings
89
+ self.original_max_seq_len = config.max_position_embeddings
90
+ self.config = config
91
+
92
+ self.rope_type = self.config.rope_parameters["rope_type"]
93
+ rope_init_fn: Callable = self.compute_default_rope_parameters
94
+ if self.rope_type != "default":
95
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
96
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
97
+
98
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
99
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
100
+
101
+ @staticmethod
102
+ def compute_default_rope_parameters(
103
+ config: "CijovLangConfig | None" = None,
104
+ device: Optional["torch.device"] = None,
105
+ seq_len: int | None = None,
106
+ ) -> tuple["torch.Tensor", float]:
107
+ base = config.rope_parameters["rope_theta"]
108
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
109
+ attention_factor = 1.0
110
+ inv_freq = 1.0 / (
111
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
112
+ )
113
+ return inv_freq, attention_factor
114
+
115
+ @torch.no_grad()
116
+ @dynamic_rope_update
117
+ def forward(self, x, position_ids):
118
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
119
+ position_ids_expanded = position_ids[:, None, :].float()
120
+
121
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
122
+ with maybe_autocast(device_type=device_type, enabled=False):
123
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
124
+ emb = torch.cat((freqs, freqs), dim=-1)
125
+ cos = emb.cos() * self.attention_scaling
126
+ sin = emb.sin() * self.attention_scaling
127
+
128
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
129
+
130
+
131
+ def rotate_half(x):
132
+ x1 = x[..., : x.shape[-1] // 2]
133
+ x2 = x[..., x.shape[-1] // 2 :]
134
+ return torch.cat((-x2, x1), dim=-1)
135
+
136
+
137
+ @use_kernel_func_from_hub("rotary_pos_emb")
138
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
139
+ cos = cos.unsqueeze(unsqueeze_dim)
140
+ sin = sin.unsqueeze(unsqueeze_dim)
141
+ q_embed = (q * cos) + (rotate_half(q) * sin)
142
+ k_embed = (k * cos) + (rotate_half(k) * sin)
143
+ return q_embed, k_embed
144
+
145
+
146
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
147
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
148
+ if n_rep == 1:
149
+ return hidden_states
150
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
151
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
152
+
153
+
154
+ def eager_attention_forward(
155
+ module: nn.Module,
156
+ query: torch.Tensor,
157
+ key: torch.Tensor,
158
+ value: torch.Tensor,
159
+ attention_mask: torch.Tensor | None,
160
+ scaling: float,
161
+ dropout: float = 0.0,
162
+ **kwargs: Unpack[TransformersKwargs],
163
+ ):
164
+ key_states = repeat_kv(key, module.num_key_value_groups)
165
+ value_states = repeat_kv(value, module.num_key_value_groups)
166
+
167
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
168
+ if attention_mask is not None:
169
+ attn_weights = attn_weights + attention_mask
170
+
171
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
172
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
173
+ attn_output = torch.matmul(attn_weights, value_states)
174
+ attn_output = attn_output.transpose(1, 2).contiguous()
175
+
176
+ return attn_output, attn_weights
177
+
178
+
179
+ @use_kernelized_func(apply_rotary_pos_emb)
180
+ class CijovLangAttention(nn.Module):
181
+ """Multi-headed attention, grouped-query with per-head query/key RMSNorm."""
182
+
183
+ def __init__(self, config: CijovLangConfig, layer_idx: int):
184
+ super().__init__()
185
+ self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
186
+ self.config = config
187
+ self.layer_idx = layer_idx
188
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
189
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
190
+ self.scaling = self.head_dim**-0.5
191
+ self.attention_dropout = config.attention_dropout
192
+ self.is_causal = True
193
+
194
+ self.query_proj = nn.Linear(
195
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
196
+ )
197
+ self.key_proj = nn.Linear(
198
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
199
+ )
200
+ self.value_proj = nn.Linear(
201
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
202
+ )
203
+ self.output_proj = nn.Linear(
204
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
205
+ )
206
+ self.query_norm = CijovLangRMSNorm(self.head_dim, eps=config.rms_norm_eps)
207
+ self.key_norm = CijovLangRMSNorm(self.head_dim, eps=config.rms_norm_eps)
208
+ self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
209
+
210
+ def forward(
211
+ self,
212
+ hidden_states: torch.Tensor,
213
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
214
+ attention_mask: torch.Tensor | None,
215
+ past_key_values: Cache | None = None,
216
+ **kwargs: Unpack[FlashAttentionKwargs],
217
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
218
+ input_shape = hidden_states.shape[:-1]
219
+ hidden_shape = (*input_shape, -1, self.head_dim)
220
+
221
+ query_states = self.query_norm(self.query_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
222
+ key_states = self.key_norm(self.key_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
223
+ value_states = self.value_proj(hidden_states).view(hidden_shape).transpose(1, 2)
224
+
225
+ cos, sin = position_embeddings
226
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
227
+
228
+ if past_key_values is not None:
229
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
230
+
231
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
232
+ self.config._attn_implementation, eager_attention_forward
233
+ )
234
+
235
+ attn_output, attn_weights = attention_interface(
236
+ self,
237
+ query_states,
238
+ key_states,
239
+ value_states,
240
+ attention_mask,
241
+ dropout=0.0 if not self.training else self.attention_dropout,
242
+ scaling=self.scaling,
243
+ sliding_window=self.sliding_window,
244
+ **kwargs,
245
+ )
246
+
247
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
248
+ attn_output = self.output_proj(attn_output)
249
+ return attn_output, attn_weights
250
+
251
+
252
+ class CijovLangDecoderLayer(GradientCheckpointingLayer):
253
+ def __init__(self, config: CijovLangConfig, layer_idx: int):
254
+ super().__init__()
255
+ self.hidden_size = config.hidden_size
256
+
257
+ self.attention = CijovLangAttention(config=config, layer_idx=layer_idx)
258
+ self.feed_forward = CijovLangFeedForward(config)
259
+ self.attention_norm = CijovLangRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
260
+ self.feed_forward_norm = CijovLangRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
261
+
262
+ def forward(
263
+ self,
264
+ hidden_states: torch.Tensor,
265
+ attention_mask: torch.Tensor | None = None,
266
+ position_ids: torch.LongTensor | None = None,
267
+ past_key_values: Cache | None = None,
268
+ use_cache: bool | None = False,
269
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
270
+ **kwargs: Unpack[TransformersKwargs],
271
+ ) -> torch.Tensor:
272
+ residual = hidden_states
273
+ hidden_states = self.attention_norm(hidden_states)
274
+ hidden_states, _ = self.attention(
275
+ hidden_states=hidden_states,
276
+ attention_mask=attention_mask,
277
+ position_ids=position_ids,
278
+ past_key_values=past_key_values,
279
+ use_cache=use_cache,
280
+ position_embeddings=position_embeddings,
281
+ **kwargs,
282
+ )
283
+ hidden_states = residual + hidden_states
284
+
285
+ residual = hidden_states
286
+ hidden_states = self.feed_forward_norm(hidden_states)
287
+ hidden_states = self.feed_forward(hidden_states)
288
+ hidden_states = residual + hidden_states
289
+ return hidden_states
290
+
291
+
292
+ @auto_docstring
293
+ class CijovLangPreTrainedModel(PreTrainedModel):
294
+ config: CijovLangConfig
295
+ base_model_prefix = "model"
296
+ # PreTrainedModel's get/set_input_embeddings default to looking for an
297
+ # attribute literally named "embed_tokens"; token_embeddings is Cijov-
298
+ # lang's own naming, so point the generic auto-handling at it instead of
299
+ # duplicating that logic with a manual override.
300
+ _input_embed_layer = "token_embeddings"
301
+ supports_gradient_checkpointing = True
302
+ _no_split_modules = ["CijovLangDecoderLayer"]
303
+ _skip_keys_device_placement = ["past_key_values"]
304
+ _supports_flash_attn = True
305
+ _supports_sdpa = True
306
+ _supports_flex_attn = True
307
+
308
+ _can_compile_fullgraph = True
309
+ _supports_attention_backend = True
310
+ _can_record_outputs = {
311
+ "hidden_states": CijovLangDecoderLayer,
312
+ "attentions": CijovLangAttention,
313
+ }
314
+
315
+
316
+ @auto_docstring
317
+ class CijovLangModel(CijovLangPreTrainedModel):
318
+ def __init__(self, config: CijovLangConfig):
319
+ super().__init__(config)
320
+ self.padding_idx = config.pad_token_id
321
+ self.vocab_size = config.vocab_size
322
+
323
+ self.token_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
324
+ self.layers = nn.ModuleList(
325
+ [CijovLangDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
326
+ )
327
+ self.final_norm = CijovLangRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
328
+ self.rotary_emb = CijovLangRotaryEmbedding(config=config)
329
+ self.gradient_checkpointing = False
330
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
331
+
332
+ self.post_init()
333
+
334
+ @merge_with_config_defaults
335
+ @capture_outputs
336
+ @auto_docstring
337
+ def forward(
338
+ self,
339
+ input_ids: torch.LongTensor | None = None,
340
+ attention_mask: torch.Tensor | None = None,
341
+ position_ids: torch.LongTensor | None = None,
342
+ past_key_values: Cache | None = None,
343
+ inputs_embeds: torch.FloatTensor | None = None,
344
+ use_cache: bool | None = None,
345
+ **kwargs: Unpack[TransformersKwargs],
346
+ ) -> BaseModelOutputWithPast:
347
+ if (input_ids is None) ^ (inputs_embeds is not None):
348
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
349
+
350
+ if inputs_embeds is None:
351
+ inputs_embeds = self.token_embeddings(input_ids)
352
+
353
+ if use_cache and past_key_values is None:
354
+ past_key_values = DynamicCache(config=self.config)
355
+
356
+ if position_ids is None:
357
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
358
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
359
+ position_ids = position_ids.unsqueeze(0)
360
+
361
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
362
+ mask_kwargs = {
363
+ "config": self.config,
364
+ "inputs_embeds": inputs_embeds,
365
+ "attention_mask": attention_mask,
366
+ "past_key_values": past_key_values,
367
+ "position_ids": position_ids,
368
+ }
369
+ causal_mask_mapping = {
370
+ "full_attention": create_causal_mask(**mask_kwargs),
371
+ }
372
+ if self.has_sliding_layers:
373
+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
374
+
375
+ hidden_states = inputs_embeds
376
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
377
+
378
+ for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
379
+ hidden_states = decoder_layer(
380
+ hidden_states,
381
+ attention_mask=causal_mask_mapping[self.config.layer_types[i]],
382
+ position_embeddings=position_embeddings,
383
+ position_ids=position_ids,
384
+ past_key_values=past_key_values,
385
+ use_cache=use_cache,
386
+ **kwargs,
387
+ )
388
+
389
+ hidden_states = self.final_norm(hidden_states)
390
+ return BaseModelOutputWithPast(
391
+ last_hidden_state=hidden_states,
392
+ past_key_values=past_key_values if use_cache else None,
393
+ )
394
+
395
+
396
+ @auto_docstring
397
+ class CijovLangForCausalLM(CijovLangPreTrainedModel, GenerationMixin):
398
+ _tied_weights_keys = {"lm_head.weight": "model.token_embeddings.weight"}
399
+ _tp_plan = {"lm_head": "colwise_gather_output"}
400
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
401
+
402
+ def __init__(self, config):
403
+ super().__init__(config)
404
+ self.model = CijovLangModel(config)
405
+ self.vocab_size = config.vocab_size
406
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
407
+
408
+ self.post_init()
409
+
410
+ @can_return_tuple
411
+ @auto_docstring
412
+ def forward(
413
+ self,
414
+ input_ids: torch.LongTensor | None = None,
415
+ attention_mask: torch.Tensor | None = None,
416
+ position_ids: torch.LongTensor | None = None,
417
+ past_key_values: Cache | None = None,
418
+ inputs_embeds: torch.FloatTensor | None = None,
419
+ labels: torch.LongTensor | None = None,
420
+ use_cache: bool | None = None,
421
+ logits_to_keep: int | torch.Tensor = 0,
422
+ **kwargs: Unpack[TransformersKwargs],
423
+ ) -> CausalLMOutputWithPast:
424
+ r"""
425
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
426
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
427
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
428
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
429
+
430
+ Example:
431
+
432
+ ```python
433
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
434
+
435
+ >>> model = AutoModelForCausalLM.from_pretrained("cijov/cijov-lang-1B-1V", subfolder="model", trust_remote_code=True)
436
+ >>> tokenizer = AutoTokenizer.from_pretrained("cijov/cijov-lang-1B-1V", subfolder="model")
437
+
438
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
439
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
440
+
441
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
442
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
443
+ ```"""
444
+ outputs: BaseModelOutputWithPast = self.model(
445
+ input_ids=input_ids,
446
+ attention_mask=attention_mask,
447
+ position_ids=position_ids,
448
+ past_key_values=past_key_values,
449
+ inputs_embeds=inputs_embeds,
450
+ use_cache=use_cache,
451
+ **kwargs,
452
+ )
453
+
454
+ hidden_states = outputs.last_hidden_state
455
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
456
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
457
+
458
+ loss = None
459
+ if labels is not None:
460
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
461
+
462
+ return CausalLMOutputWithPast(
463
+ loss=loss,
464
+ logits=logits,
465
+ past_key_values=outputs.past_key_values,
466
+ hidden_states=outputs.hidden_states,
467
+ attentions=outputs.attentions,
468
+ )
469
+
470
+
471
+ __all__ = ["CijovLangForCausalLM", "CijovLangModel", "CijovLangPreTrainedModel"]
model/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94e630a13bda6a31c71fd7227ece2e8f4ade40dda567b4127f9d2374e7f9864d
3
+ size 11285267
model/tokenizer_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": null,
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|im_end|>",
7
+ "is_local": true,
8
+ "local_files_only": false,
9
+ "model_max_length": 40960,
10
+ "pad_token": "<|endoftext|>",
11
+ "padding_side": "left",
12
+ "tokenizer_class": "TokenizersBackend",
13
+ "unk_token": null
14
+ }
modeling_cijov_lang.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Cijov
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Cijov-lang model.
15
+
16
+ Same underlying transformer math as the architecture used to train this
17
+ model via Megatron-LM (Qwen3-compatible, for training-infrastructure
18
+ compatibility only), but published as its own standalone architecture: no
19
+ import from transformers' Qwen3 implementation, and module names below
20
+ (attention/feed_forward/query_proj/... instead of self_attn/mlp/q_proj/...)
21
+ are Cijov-lang's own, not inherited Qwen naming -- so the state dict keys of
22
+ a Cijov-lang checkpoint are genuinely distinct from a Qwen3 one, not just the
23
+ class names.
24
+ """
25
+
26
+ from collections.abc import Callable
27
+ from typing import Optional
28
+
29
+ import torch
30
+ from torch import nn
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.generation import GenerationMixin
35
+ from transformers.integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
36
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
37
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
38
+ from transformers.modeling_layers import GradientCheckpointingLayer
39
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
40
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
41
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from transformers.processing_utils import Unpack
43
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
44
+ from transformers.utils.generic import maybe_autocast, merge_with_config_defaults
45
+ from transformers.utils.output_capturing import capture_outputs
46
+
47
+ from .configuration_cijov_lang import CijovLangConfig
48
+
49
+
50
+ @use_kernel_forward_from_hub("RMSNorm")
51
+ class CijovLangRMSNorm(nn.Module):
52
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
53
+ super().__init__()
54
+ self.weight = nn.Parameter(torch.ones(hidden_size))
55
+ self.variance_epsilon = eps
56
+
57
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
58
+ input_dtype = hidden_states.dtype
59
+ hidden_states = hidden_states.to(torch.float32)
60
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
61
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
62
+ return self.weight * hidden_states.to(input_dtype)
63
+
64
+ def extra_repr(self):
65
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
66
+
67
+
68
+ class CijovLangFeedForward(nn.Module):
69
+ def __init__(self, config):
70
+ super().__init__()
71
+ self.config = config
72
+ self.hidden_size = config.hidden_size
73
+ self.intermediate_size = config.intermediate_size
74
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
75
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
76
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
77
+ self.act_fn = ACT2FN[config.hidden_act]
78
+
79
+ def forward(self, x):
80
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
81
+
82
+
83
+ class CijovLangRotaryEmbedding(nn.Module):
84
+ inv_freq: torch.Tensor
85
+
86
+ def __init__(self, config: CijovLangConfig, device=None):
87
+ super().__init__()
88
+ self.max_seq_len_cached = config.max_position_embeddings
89
+ self.original_max_seq_len = config.max_position_embeddings
90
+ self.config = config
91
+
92
+ self.rope_type = self.config.rope_parameters["rope_type"]
93
+ rope_init_fn: Callable = self.compute_default_rope_parameters
94
+ if self.rope_type != "default":
95
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
96
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
97
+
98
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
99
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
100
+
101
+ @staticmethod
102
+ def compute_default_rope_parameters(
103
+ config: "CijovLangConfig | None" = None,
104
+ device: Optional["torch.device"] = None,
105
+ seq_len: int | None = None,
106
+ ) -> tuple["torch.Tensor", float]:
107
+ base = config.rope_parameters["rope_theta"]
108
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
109
+ attention_factor = 1.0
110
+ inv_freq = 1.0 / (
111
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
112
+ )
113
+ return inv_freq, attention_factor
114
+
115
+ @torch.no_grad()
116
+ @dynamic_rope_update
117
+ def forward(self, x, position_ids):
118
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
119
+ position_ids_expanded = position_ids[:, None, :].float()
120
+
121
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
122
+ with maybe_autocast(device_type=device_type, enabled=False):
123
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
124
+ emb = torch.cat((freqs, freqs), dim=-1)
125
+ cos = emb.cos() * self.attention_scaling
126
+ sin = emb.sin() * self.attention_scaling
127
+
128
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
129
+
130
+
131
+ def rotate_half(x):
132
+ x1 = x[..., : x.shape[-1] // 2]
133
+ x2 = x[..., x.shape[-1] // 2 :]
134
+ return torch.cat((-x2, x1), dim=-1)
135
+
136
+
137
+ @use_kernel_func_from_hub("rotary_pos_emb")
138
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
139
+ cos = cos.unsqueeze(unsqueeze_dim)
140
+ sin = sin.unsqueeze(unsqueeze_dim)
141
+ q_embed = (q * cos) + (rotate_half(q) * sin)
142
+ k_embed = (k * cos) + (rotate_half(k) * sin)
143
+ return q_embed, k_embed
144
+
145
+
146
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
147
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
148
+ if n_rep == 1:
149
+ return hidden_states
150
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
151
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
152
+
153
+
154
+ def eager_attention_forward(
155
+ module: nn.Module,
156
+ query: torch.Tensor,
157
+ key: torch.Tensor,
158
+ value: torch.Tensor,
159
+ attention_mask: torch.Tensor | None,
160
+ scaling: float,
161
+ dropout: float = 0.0,
162
+ **kwargs: Unpack[TransformersKwargs],
163
+ ):
164
+ key_states = repeat_kv(key, module.num_key_value_groups)
165
+ value_states = repeat_kv(value, module.num_key_value_groups)
166
+
167
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
168
+ if attention_mask is not None:
169
+ attn_weights = attn_weights + attention_mask
170
+
171
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
172
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
173
+ attn_output = torch.matmul(attn_weights, value_states)
174
+ attn_output = attn_output.transpose(1, 2).contiguous()
175
+
176
+ return attn_output, attn_weights
177
+
178
+
179
+ @use_kernelized_func(apply_rotary_pos_emb)
180
+ class CijovLangAttention(nn.Module):
181
+ """Multi-headed attention, grouped-query with per-head query/key RMSNorm."""
182
+
183
+ def __init__(self, config: CijovLangConfig, layer_idx: int):
184
+ super().__init__()
185
+ self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
186
+ self.config = config
187
+ self.layer_idx = layer_idx
188
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
189
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
190
+ self.scaling = self.head_dim**-0.5
191
+ self.attention_dropout = config.attention_dropout
192
+ self.is_causal = True
193
+
194
+ self.query_proj = nn.Linear(
195
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
196
+ )
197
+ self.key_proj = nn.Linear(
198
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
199
+ )
200
+ self.value_proj = nn.Linear(
201
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
202
+ )
203
+ self.output_proj = nn.Linear(
204
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
205
+ )
206
+ self.query_norm = CijovLangRMSNorm(self.head_dim, eps=config.rms_norm_eps)
207
+ self.key_norm = CijovLangRMSNorm(self.head_dim, eps=config.rms_norm_eps)
208
+ self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
209
+
210
+ def forward(
211
+ self,
212
+ hidden_states: torch.Tensor,
213
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
214
+ attention_mask: torch.Tensor | None,
215
+ past_key_values: Cache | None = None,
216
+ **kwargs: Unpack[FlashAttentionKwargs],
217
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
218
+ input_shape = hidden_states.shape[:-1]
219
+ hidden_shape = (*input_shape, -1, self.head_dim)
220
+
221
+ query_states = self.query_norm(self.query_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
222
+ key_states = self.key_norm(self.key_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
223
+ value_states = self.value_proj(hidden_states).view(hidden_shape).transpose(1, 2)
224
+
225
+ cos, sin = position_embeddings
226
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
227
+
228
+ if past_key_values is not None:
229
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
230
+
231
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
232
+ self.config._attn_implementation, eager_attention_forward
233
+ )
234
+
235
+ attn_output, attn_weights = attention_interface(
236
+ self,
237
+ query_states,
238
+ key_states,
239
+ value_states,
240
+ attention_mask,
241
+ dropout=0.0 if not self.training else self.attention_dropout,
242
+ scaling=self.scaling,
243
+ sliding_window=self.sliding_window,
244
+ **kwargs,
245
+ )
246
+
247
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
248
+ attn_output = self.output_proj(attn_output)
249
+ return attn_output, attn_weights
250
+
251
+
252
+ class CijovLangDecoderLayer(GradientCheckpointingLayer):
253
+ def __init__(self, config: CijovLangConfig, layer_idx: int):
254
+ super().__init__()
255
+ self.hidden_size = config.hidden_size
256
+
257
+ self.attention = CijovLangAttention(config=config, layer_idx=layer_idx)
258
+ self.feed_forward = CijovLangFeedForward(config)
259
+ self.attention_norm = CijovLangRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
260
+ self.feed_forward_norm = CijovLangRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
261
+
262
+ def forward(
263
+ self,
264
+ hidden_states: torch.Tensor,
265
+ attention_mask: torch.Tensor | None = None,
266
+ position_ids: torch.LongTensor | None = None,
267
+ past_key_values: Cache | None = None,
268
+ use_cache: bool | None = False,
269
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
270
+ **kwargs: Unpack[TransformersKwargs],
271
+ ) -> torch.Tensor:
272
+ residual = hidden_states
273
+ hidden_states = self.attention_norm(hidden_states)
274
+ hidden_states, _ = self.attention(
275
+ hidden_states=hidden_states,
276
+ attention_mask=attention_mask,
277
+ position_ids=position_ids,
278
+ past_key_values=past_key_values,
279
+ use_cache=use_cache,
280
+ position_embeddings=position_embeddings,
281
+ **kwargs,
282
+ )
283
+ hidden_states = residual + hidden_states
284
+
285
+ residual = hidden_states
286
+ hidden_states = self.feed_forward_norm(hidden_states)
287
+ hidden_states = self.feed_forward(hidden_states)
288
+ hidden_states = residual + hidden_states
289
+ return hidden_states
290
+
291
+
292
+ @auto_docstring
293
+ class CijovLangPreTrainedModel(PreTrainedModel):
294
+ config: CijovLangConfig
295
+ base_model_prefix = "model"
296
+ # PreTrainedModel's get/set_input_embeddings default to looking for an
297
+ # attribute literally named "embed_tokens"; token_embeddings is Cijov-
298
+ # lang's own naming, so point the generic auto-handling at it instead of
299
+ # duplicating that logic with a manual override.
300
+ _input_embed_layer = "token_embeddings"
301
+ supports_gradient_checkpointing = True
302
+ _no_split_modules = ["CijovLangDecoderLayer"]
303
+ _skip_keys_device_placement = ["past_key_values"]
304
+ _supports_flash_attn = True
305
+ _supports_sdpa = True
306
+ _supports_flex_attn = True
307
+
308
+ _can_compile_fullgraph = True
309
+ _supports_attention_backend = True
310
+ _can_record_outputs = {
311
+ "hidden_states": CijovLangDecoderLayer,
312
+ "attentions": CijovLangAttention,
313
+ }
314
+
315
+
316
+ @auto_docstring
317
+ class CijovLangModel(CijovLangPreTrainedModel):
318
+ def __init__(self, config: CijovLangConfig):
319
+ super().__init__(config)
320
+ self.padding_idx = config.pad_token_id
321
+ self.vocab_size = config.vocab_size
322
+
323
+ self.token_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
324
+ self.layers = nn.ModuleList(
325
+ [CijovLangDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
326
+ )
327
+ self.final_norm = CijovLangRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
328
+ self.rotary_emb = CijovLangRotaryEmbedding(config=config)
329
+ self.gradient_checkpointing = False
330
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
331
+
332
+ self.post_init()
333
+
334
+ @merge_with_config_defaults
335
+ @capture_outputs
336
+ @auto_docstring
337
+ def forward(
338
+ self,
339
+ input_ids: torch.LongTensor | None = None,
340
+ attention_mask: torch.Tensor | None = None,
341
+ position_ids: torch.LongTensor | None = None,
342
+ past_key_values: Cache | None = None,
343
+ inputs_embeds: torch.FloatTensor | None = None,
344
+ use_cache: bool | None = None,
345
+ **kwargs: Unpack[TransformersKwargs],
346
+ ) -> BaseModelOutputWithPast:
347
+ if (input_ids is None) ^ (inputs_embeds is not None):
348
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
349
+
350
+ if inputs_embeds is None:
351
+ inputs_embeds = self.token_embeddings(input_ids)
352
+
353
+ if use_cache and past_key_values is None:
354
+ past_key_values = DynamicCache(config=self.config)
355
+
356
+ if position_ids is None:
357
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
358
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
359
+ position_ids = position_ids.unsqueeze(0)
360
+
361
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
362
+ mask_kwargs = {
363
+ "config": self.config,
364
+ "inputs_embeds": inputs_embeds,
365
+ "attention_mask": attention_mask,
366
+ "past_key_values": past_key_values,
367
+ "position_ids": position_ids,
368
+ }
369
+ causal_mask_mapping = {
370
+ "full_attention": create_causal_mask(**mask_kwargs),
371
+ }
372
+ if self.has_sliding_layers:
373
+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
374
+
375
+ hidden_states = inputs_embeds
376
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
377
+
378
+ for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
379
+ hidden_states = decoder_layer(
380
+ hidden_states,
381
+ attention_mask=causal_mask_mapping[self.config.layer_types[i]],
382
+ position_embeddings=position_embeddings,
383
+ position_ids=position_ids,
384
+ past_key_values=past_key_values,
385
+ use_cache=use_cache,
386
+ **kwargs,
387
+ )
388
+
389
+ hidden_states = self.final_norm(hidden_states)
390
+ return BaseModelOutputWithPast(
391
+ last_hidden_state=hidden_states,
392
+ past_key_values=past_key_values if use_cache else None,
393
+ )
394
+
395
+
396
+ @auto_docstring
397
+ class CijovLangForCausalLM(CijovLangPreTrainedModel, GenerationMixin):
398
+ _tied_weights_keys = {"lm_head.weight": "model.token_embeddings.weight"}
399
+ _tp_plan = {"lm_head": "colwise_gather_output"}
400
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
401
+
402
+ def __init__(self, config):
403
+ super().__init__(config)
404
+ self.model = CijovLangModel(config)
405
+ self.vocab_size = config.vocab_size
406
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
407
+
408
+ self.post_init()
409
+
410
+ @can_return_tuple
411
+ @auto_docstring
412
+ def forward(
413
+ self,
414
+ input_ids: torch.LongTensor | None = None,
415
+ attention_mask: torch.Tensor | None = None,
416
+ position_ids: torch.LongTensor | None = None,
417
+ past_key_values: Cache | None = None,
418
+ inputs_embeds: torch.FloatTensor | None = None,
419
+ labels: torch.LongTensor | None = None,
420
+ use_cache: bool | None = None,
421
+ logits_to_keep: int | torch.Tensor = 0,
422
+ **kwargs: Unpack[TransformersKwargs],
423
+ ) -> CausalLMOutputWithPast:
424
+ r"""
425
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
426
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
427
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
428
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
429
+
430
+ Example:
431
+
432
+ ```python
433
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
434
+
435
+ >>> model = AutoModelForCausalLM.from_pretrained("cijov/cijov-lang-1B-1V", subfolder="model", trust_remote_code=True)
436
+ >>> tokenizer = AutoTokenizer.from_pretrained("cijov/cijov-lang-1B-1V", subfolder="model")
437
+
438
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
439
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
440
+
441
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
442
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
443
+ ```"""
444
+ outputs: BaseModelOutputWithPast = self.model(
445
+ input_ids=input_ids,
446
+ attention_mask=attention_mask,
447
+ position_ids=position_ids,
448
+ past_key_values=past_key_values,
449
+ inputs_embeds=inputs_embeds,
450
+ use_cache=use_cache,
451
+ **kwargs,
452
+ )
453
+
454
+ hidden_states = outputs.last_hidden_state
455
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
456
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
457
+
458
+ loss = None
459
+ if labels is not None:
460
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
461
+
462
+ return CausalLMOutputWithPast(
463
+ loss=loss,
464
+ logits=logits,
465
+ past_key_values=outputs.past_key_values,
466
+ hidden_states=outputs.hidden_states,
467
+ attentions=outputs.attentions,
468
+ )
469
+
470
+
471
+ __all__ = ["CijovLangForCausalLM", "CijovLangModel", "CijovLangPreTrainedModel"]