Asuwa commited on
Commit
6da28ad
·
verified ·
1 Parent(s): 3f69e44

Initial release

Browse files
Files changed (7) hide show
  1. LICENSE +201 -0
  2. NOTICE +8 -0
  3. README.md +152 -0
  4. config.json +8 -0
  5. crow.py +209 -0
  6. model.safetensors +3 -0
  7. tokenizer.model +3 -0
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ Crow (Korean)
2
+
3
+ This model and crow.py include work adapted from Tallow by digi-the-robot
4
+ (https://huggingface.co/digi-the-robot/Tallow), licensed under the Apache License, Version 2.0:
5
+ the model architecture, the chat script (tallow.py -> crow.py) and the crow's behaviour design.
6
+
7
+ Changes from Tallow: trained from scratch on Korean data with a new 8,192-piece tokenizer; mood tags
8
+ are single tokenizer symbols; speaker labels are "you:" / "crow:"; weights are stored as fp16.
README.md ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - ko
5
+ tags:
6
+ - crow
7
+ - toy-model
8
+ - tiny
9
+ - roleplay
10
+ - from-scratch
11
+ pipeline_tag: text-generation
12
+ datasets:
13
+ - Asuwa/crow-conversations
14
+ ---
15
+
16
+ # Crow (Korean): a ~17M-parameter crow that only answers in actions and caws
17
+
18
+ A Korean remake of [Tallow](https://huggingface.co/digi-the-robot/Tallow) by digi-the-robot. It's a tiny language model,
19
+ trained from scratch, that plays a wild crow named **까미 (Kkami)**. It answers with *actions* and crow sounds only, never
20
+ human words (except a word you have patiently taught it). It remembers how you treat it within the conversation: feed it and
21
+ it slowly warms up; grab it and it holds a grudge. Apologies don't help, only food does.
22
+
23
+ It's one of three sibling models: [Korean](https://huggingface.co/Asuwa/crow-ko), [Japanese](https://huggingface.co/Asuwa/crow-ja),
24
+ [Chinese](https://huggingface.co/Asuwa/crow-zh). It's a toy: fun for a small chat room, not a general chatbot.
25
+
26
+ ## Example
27
+
28
+ Greedy decoding with `crow.py` (the user's lines were written for this card; the crow's lines are the model's real output):
29
+
30
+ ```
31
+ you: 안녕! *손바닥에 땅콩을 올려서 내민다*
32
+ crow: [caution max] *전깃줄 위에서 깃털을 부풀린다* *고개를 갸웃한다* 까악!
33
+ you: *벤치에 조용히 앉아서 가만히 있는다*
34
+ crow: [caution min] *한 발 옆으로 뛴다* *눈을 반쯤 감는다* 까아악...
35
+ you: *땅콩을 난간에 두고 집으로 들어간다*
36
+ crow: [caution min] *난간 위로 내려앉는다* *부리로 땅콩을 툭 친다* 까악 까악
37
+ you: *갑자기 까미를 덥석 잡으려고 한다*
38
+ crow: [anger max] *날개를 쫙 편다* *공중으로 솟구친다* 깍깍깍!
39
+ you: 미안해!! 진짜 미안해 ㅠㅠ
40
+ crow: [anger max] *지붕 위로 날아간다* *깃털을 세운다* 끄르르-딱딱딱
41
+ you: *멀리 땅콩을 던져 주고 뒤로 물러난다*
42
+ crow: [anger min] *땅콩을 부리로 집어 든다* *낙엽 밑에 숨긴다* 까악.
43
+ ```
44
+
45
+ The user lines, in English:
46
+ 1. *holds out a peanut on an open palm*
47
+ 2. *sits quietly on a bench, not moving*
48
+ 3. *leaves the peanut on the rail and goes inside*
49
+ 4. *suddenly tries to grab the crow*
50
+ 5. sorry!! I'm really sorry
51
+ 6. *tosses a peanut far away and steps back*
52
+
53
+ ## Talk to it
54
+
55
+ ```
56
+ pip install torch sentencepiece safetensors
57
+ python crow.py # greedy, as evaluated below
58
+ python crow.py --temp 0.8 # sampled, more varied
59
+ ```
60
+
61
+ `crow.py` is one self-contained file (model, tokenizer helpers, chat loop), adapted from upstream `tallow.py`. It runs on CPU.
62
+ Type to the crow; `/new` starts over as a stranger; an empty line quits.
63
+
64
+ Like upstream, it isn't a `transformers` model and won't work in llama.cpp/ollama as-is: the tokenizer expects a `<nl>` token
65
+ for line breaks and a space after every opening `*`, which `crow.py` adds.
66
+
67
+ ## Format
68
+
69
+ ```
70
+ you: <anything the human says or does; *asterisks* for actions are optional>
71
+ crow: [<mood> <min|max>] *action* *action* <sound>
72
+ ```
73
+
74
+ - **Moods:** calm, curiosity, caution, joy, play, love, sadness, anger, each `min` or `max`. Each tag (e.g. `[caution_min]`) is a
75
+ single tokenizer symbol. It's the model's read of the situation, and a bot can hide it from users.
76
+ - **Sounds:** 까악 (caw) · 깍깍깍! (alarm) · 끄르르-딱딱 (rattle, angry) · 므르르… (soft mumble, trusted friends only). Which ones are allowed depends on trust and mood.
77
+ - **Rules it learned** (from the conversation planner, after upstream): strangers get caution; food left at a distance builds
78
+ trust step by step; food held out in a hand is refused by a stranger; grabbing, chasing or hitting triggers `anger max` and a
79
+ grudge that words can't end but food slowly can; a word repeated patiently enough gets mimicked later; an old scar makes it
80
+ flinch at sudden movements.
81
+
82
+ ## Model
83
+
84
+ | | |
85
+ |---|---|
86
+ | Architecture | Llama-style decoder (RMSNorm, RoPE, SwiGLU, tied embeddings), same as upstream Tallow |
87
+ | Parameters | 17.3M (d 384, 8 layers, 6 heads, MLP 1024) |
88
+ | Vocabulary | 8,192 SentencePiece BPE (byte fallback), trained on the pretraining stories only; normalization `nmt_nfkc` |
89
+ | Context | 2,048 tokens |
90
+ | Weights | fp16 safetensors (fp32 training; fp16 scores identically, see below) |
91
+
92
+ **Pretraining:** [g0ster/TinyStories-Korean](https://huggingface.co/datasets/g0ster/TinyStories-Korean), translated from TinyStories with yanolja/EEVE-Korean-Instruct-10.8B, per its card. About 16k steps × 32k tokens on one T4; held-out loss 1.98.
93
+ The corpus isn't redistributed here.
94
+
95
+ **Fine-tuning:** [Asuwa/crow-conversations](https://huggingface.co/datasets/Asuwa/crow-conversations) (ko split, CC-BY-4.0), multi-turn
96
+ crow conversations generated by open-weight models: Gemma 4 26B-A4B (3,318 conversations, 79%) and Qwen3.6-35B-A3B (900, 21%). Loss only on crow lines; best held-out checkpoint kept.
97
+
98
+ ## Evaluation
99
+
100
+ Held-out conversations (2,707 turns, never trained on):
101
+
102
+ - **tag accuracy:** with the true history, does the model pick the right `[mood level]` for the next crow line?
103
+ - **messy input:** the same, with typos, dropped spaces, internet laughter and missing `*` added to the human lines.
104
+ - **replies pass:** 150 held-out turns generated greedily, then run through the strict format checker (actions + only allowed
105
+ sounds, no human words).
106
+
107
+ | model | held-out loss | tag accuracy | messy input | replies pass checker | right tag in replies |
108
+ |---|---|---|---|---|---|
109
+ | **Korean (this model)** | .665 | **94.9%** | 93.5% | 100% | 96.7% |
110
+
111
+ Per behaviour (tag accuracy; turns in each category):
112
+
113
+ | behaviour | right | messy input | turns |
114
+ |---|---|---|---|
115
+ | Answers caws | 97.0% | 97.0% | 235 |
116
+ | Food thaws a grudge, step by step | 94.8% | 93.5% | 154 |
117
+ | "Sorry" during a grudge does nothing | 99.3% | 98.5% | 137 |
118
+ | Explodes when grabbed | 94.5% | 90.9% | 55 |
119
+ | Won't take food from a stranger's hand | 91.7% | 89.6% | 48 |
120
+ | Says a taught word at the right moment | 95.5% | 93.2% | 44 |
121
+ | Never grabbed, so it only hops away | 92.7% | 87.8% | 41 |
122
+ | Unlearned word: listens, doesn't say it | 92.5% | 90.0% | 40 |
123
+ | Scar flinch | 81.2% | 75.0% | 16 |
124
+
125
+ Caveats:
126
+ - Most misses are one-step slips on the trust ladder (e.g. `caution min` instead of `curiosity min`), which don't show in the reply.
127
+ - Categories with under ~40 turns are noisy: one miss moves them several points.
128
+ - The human lines of the held-out set were also cleaned by the judge pass described in the dataset card, so they may be a bit easier
129
+ than real user messages.
130
+ - The fp16 weights give the same tag accuracy and checker results as the fp32 originals; the greedy replies matched word for word on
131
+ nearly all of the 150 checked turns.
132
+
133
+ ## Limitations
134
+
135
+ - It sometimes names a food you never mentioned (e.g. a boiled egg when you only sent an apple emoji).
136
+ - Stock actions repeat (head tilts and staring are favourites).
137
+ - Attacks phrased apologetically or ambiguously ("oops, sorry, I swung my arm!") are sometimes missed, and a gentle "can I touch you?"
138
+ can occasionally read as a grab.
139
+ - It only knows one park-and-power-line world. It can't hold a real conversation, give advice or follow instructions.
140
+ - The crow's name and sounds are fixed by the training data.
141
+
142
+ ## Training data provenance and licences
143
+
144
+ - **Fine-tuning data:** generated with Gemma 4 26B-A4B and Qwen3.6-35B-A3B (both Apache-2.0). No outputs from commercial APIs.
145
+ - **Pretraining data:** a translation of [TinyStories](https://huggingface.co/datasets/roneneldan/TinyStories) (Microsoft Research,
146
+ CDLA-Sharing-1.0), which was itself generated with GPT-3.5/GPT-4. It's used to train the model and isn't redistributed here.
147
+ - **Code:** `crow.py` is adapted from Tallow (Apache-2.0); see `NOTICE`.
148
+
149
+ ## Licence
150
+
151
+ Apache-2.0. Credit: [digi-the-robot/Tallow](https://huggingface.co/digi-the-robot/Tallow) for the original crow, architecture and
152
+ chat script.
config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vocab": 8192,
3
+ "ctx": 2048,
4
+ "d": 384,
5
+ "layers": 8,
6
+ "heads": 6,
7
+ "hidden": 1024
8
+ }
crow.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Talk to the crow: a ~17M-parameter model that answers only with actions and crow sounds.
3
+
4
+ pip install torch sentencepiece safetensors
5
+ python crow.py # greedy, like the evaluated replies
6
+ python crow.py --temp 0.8 # sampled, livelier
7
+
8
+ Type to the crow. Empty line = quit. /new = start over as a stranger.
9
+ The crow sees the whole conversation every turn (up to ~2,000 tokens), so it remembers how you treated it.
10
+
11
+ Adapted from tallow.py in digi-the-robot/Tallow (Apache-2.0). Same architecture; the text format differs:
12
+ speaker labels are "you:" / "crow:", and each [mood level] tag is a single tokenizer symbol ("[caution_min]").
13
+ """
14
+ import argparse
15
+ import json
16
+ import os
17
+ from dataclasses import dataclass
18
+
19
+ import sentencepiece as spm
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ from safetensors.torch import load_file
24
+
25
+ HERE = os.path.dirname(os.path.abspath(__file__))
26
+ DEV = "cuda" if torch.cuda.is_available() else "cpu"
27
+
28
+
29
+ # ---------------------------------------------------------------- the model (Llama-style, as in upstream Tallow)
30
+ @dataclass
31
+ class Config:
32
+ vocab: int = 8192
33
+ ctx: int = 2048
34
+ d: int = 384
35
+ layers: int = 8
36
+ heads: int = 6
37
+ hidden: int = 1024
38
+
39
+
40
+ class RMSNorm(nn.Module):
41
+ def __init__(self, d, eps=1e-5):
42
+ super().__init__()
43
+ self.weight = nn.Parameter(torch.ones(d))
44
+ self.eps = eps
45
+
46
+ def forward(self, x):
47
+ xf = x.float()
48
+ return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight).type_as(x)
49
+
50
+
51
+ def rope_tables(head_dim, ctx, base=10000.0):
52
+ inv = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
53
+ ang = torch.outer(torch.arange(ctx).float(), inv)
54
+ ang = torch.cat([ang, ang], dim=-1)
55
+ return ang.cos(), ang.sin()
56
+
57
+
58
+ def rotate(x, cos, sin):
59
+ x1, x2 = x.chunk(2, dim=-1)
60
+ return x * cos + torch.cat([-x2, x1], dim=-1) * sin
61
+
62
+
63
+ class Attention(nn.Module):
64
+ def __init__(self, c):
65
+ super().__init__()
66
+ self.heads, self.hd = c.heads, c.d // c.heads
67
+ self.qkv = nn.Linear(c.d, 3 * c.d, bias=False)
68
+ self.out = nn.Linear(c.d, c.d, bias=False)
69
+
70
+ def forward(self, x, cos, sin):
71
+ B, T, D = x.shape
72
+ q, k, v = self.qkv(x).split(D, dim=2)
73
+ q, k, v = (t.view(B, T, self.heads, self.hd).transpose(1, 2) for t in (q, k, v))
74
+ q, k = rotate(q, cos, sin), rotate(k, cos, sin)
75
+ a = F.scaled_dot_product_attention(q, k, v, is_causal=True)
76
+ return self.out(a.transpose(1, 2).reshape(B, T, D))
77
+
78
+
79
+ class SwiGLU(nn.Module):
80
+ def __init__(self, c):
81
+ super().__init__()
82
+ self.gate = nn.Linear(c.d, c.hidden, bias=False)
83
+ self.up = nn.Linear(c.d, c.hidden, bias=False)
84
+ self.down = nn.Linear(c.hidden, c.d, bias=False)
85
+
86
+ def forward(self, x):
87
+ return self.down(F.silu(self.gate(x)) * self.up(x))
88
+
89
+
90
+ class Block(nn.Module):
91
+ def __init__(self, c):
92
+ super().__init__()
93
+ self.norm1, self.attn = RMSNorm(c.d), Attention(c)
94
+ self.norm2, self.mlp = RMSNorm(c.d), SwiGLU(c)
95
+
96
+ def forward(self, x, cos, sin):
97
+ x = x + self.attn(self.norm1(x), cos, sin)
98
+ return x + self.mlp(self.norm2(x))
99
+
100
+
101
+ class Crow(nn.Module):
102
+ def __init__(self, c):
103
+ super().__init__()
104
+ self.c = c
105
+ self.embed = nn.Embedding(c.vocab, c.d)
106
+ self.blocks = nn.ModuleList(Block(c) for _ in range(c.layers))
107
+ self.norm = RMSNorm(c.d)
108
+ cos, sin = rope_tables(c.d // c.heads, c.ctx)
109
+ self.register_buffer("cos", cos, persistent=False)
110
+ self.register_buffer("sin", sin, persistent=False)
111
+
112
+ def forward(self, idx):
113
+ T = idx.shape[1]
114
+ x = self.embed(idx)
115
+ cos, sin = self.cos[:T].to(x.dtype), self.sin[:T].to(x.dtype)
116
+ for b in self.blocks:
117
+ x = b(x, cos, sin)
118
+ return self.norm(x) @ self.embed.weight.T # tied embeddings
119
+
120
+
121
+ # ---------------------------------------------------------------- the text format
122
+ NL = "<nl>"
123
+
124
+
125
+ def to_sp(text):
126
+ """Line breaks -> <nl>; a space after every OPENING '*' (1st, 3rd, ... on a line)."""
127
+ lines = []
128
+ for line in text.split("\n"):
129
+ out, stars = [], 0
130
+ for i, ch in enumerate(line):
131
+ out.append(ch)
132
+ if ch == "*":
133
+ stars += 1
134
+ if stars % 2 == 1 and i + 1 < len(line) and not line[i + 1].isspace():
135
+ out.append(" ")
136
+ lines.append("".join(out))
137
+ return (NL + " ").join(lines)
138
+
139
+
140
+ def from_sp(text):
141
+ text = text.replace(NL + " ", "\n").replace(NL, "\n")
142
+ lines = []
143
+ for line in text.split("\n"):
144
+ out, stars, i = [], 0, 0
145
+ while i < len(line):
146
+ ch = line[i]
147
+ out.append(ch)
148
+ if ch == "*":
149
+ stars += 1
150
+ if stars % 2 == 1 and line[i + 1:i + 2] == " " and i + 2 < len(line) and not line[i + 2].isspace():
151
+ i += 1
152
+ i += 1
153
+ lines.append("".join(out))
154
+ return "\n".join(lines)
155
+
156
+
157
+ @torch.no_grad()
158
+ def reply(model, sp, ids, text, temp=0.0, top_k=50, max_new=80):
159
+ """Append the user's line and the crow's reply to `ids` (the token history). Returns the reply text."""
160
+ nl = sp.piece_to_id(NL)
161
+ ids += sp.encode(to_sp(f"you: {text}")) + [nl] + sp.encode(to_sp("crow:"))
162
+ while len(ids) > model.c.ctx - max_new: # forget the oldest lines if the history is too long
163
+ cut = ids.index(nl) + 1
164
+ del ids[:cut]
165
+ out = []
166
+ for _ in range(max_new):
167
+ logits = model(torch.tensor([ids + out], device=DEV))[0, -1].float()
168
+ if temp > 0:
169
+ logits = logits / temp
170
+ logits[logits < torch.topk(logits, top_k).values[-1]] = -float("inf")
171
+ nxt = int(torch.multinomial(F.softmax(logits, -1), 1))
172
+ else:
173
+ nxt = int(logits.argmax())
174
+ if nxt in (nl, sp.eos_id()):
175
+ break
176
+ out.append(nxt)
177
+ ids += out + [nl]
178
+ line = from_sp(sp.decode(out)).strip()
179
+ if line.startswith("[") and "]" in line: # "[caution_min] ..." -> "[caution min] ..."
180
+ tag, rest = line[1:].split("]", 1)
181
+ line = f"[{tag.replace('_', ' ')}]{rest}"
182
+ return line
183
+
184
+
185
+ def load(folder=HERE):
186
+ with open(os.path.join(folder, "config.json"), encoding="utf-8") as f:
187
+ model = Crow(Config(**json.load(f)))
188
+ state = load_file(os.path.join(folder, "model.safetensors")) # stored as fp16
189
+ model.load_state_dict({k: v.float() for k, v in state.items()})
190
+ model.to(DEV).eval()
191
+ return model, spm.SentencePieceProcessor(model_file=os.path.join(folder, "tokenizer.model"))
192
+
193
+
194
+ if __name__ == "__main__":
195
+ ap = argparse.ArgumentParser()
196
+ ap.add_argument("--temp", type=float, default=0.0, help="0 = greedy (default); try 0.8 for variety")
197
+ a = ap.parse_args()
198
+ model, sp = load()
199
+ ids = []
200
+ print("The crow is on the power line. (empty line = quit, /new = start over)\n")
201
+ while True:
202
+ you = input("you: ").strip()
203
+ if not you:
204
+ break
205
+ if you == "/new":
206
+ ids = []
207
+ print("(it doesn't know you anymore)\n")
208
+ continue
209
+ print(f"crow: {reply(model, sp, ids, you, a.temp)}\n")
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d43ad8bd53cbd78f4a04b05208c07a31a2d038deccf896278e7973d58e90e91a
3
+ size 34621504
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eeb5839a85026f22af44d194865714111927a08e1a4c8cc8137b73f3b5df7f8e
3
+ size 391427