CosmicFish Initial commit
Browse files- LICENSE +201 -0
- config.json +25 -0
- example_usage.py +50 -0
- modeling_cosmicfish.py +296 -0
- pytorch_model.bin +3 -0
- tokenizer_config.json +11 -0
- vocab_info.json +5 -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 2025 Mistyoz AI Private Limited
|
| 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.
|
config.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "cosmicfish",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"CosmicFishForCausalLM"
|
| 5 |
+
],
|
| 6 |
+
"vocab_size": 50257,
|
| 7 |
+
"n_embd": 704,
|
| 8 |
+
"n_layer": 12,
|
| 9 |
+
"n_head": 16,
|
| 10 |
+
"block_size": 512,
|
| 11 |
+
"bias": true,
|
| 12 |
+
"dropout": 0.1,
|
| 13 |
+
"eps": 1e-06,
|
| 14 |
+
"use_rotary": true,
|
| 15 |
+
"use_swiglu": true,
|
| 16 |
+
"use_gqa": true,
|
| 17 |
+
"use_qk_norm": false,
|
| 18 |
+
"n_query_groups": 4,
|
| 19 |
+
"torch_dtype": "float32",
|
| 20 |
+
"transformers_version": "4.36.0",
|
| 21 |
+
"use_cache": true,
|
| 22 |
+
"pad_token_id": 50256,
|
| 23 |
+
"bos_token_id": 50256,
|
| 24 |
+
"eos_token_id": 50256
|
| 25 |
+
}
|
example_usage.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Example usage of CosmicFish model
|
| 3 |
+
"""
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import GPT2Tokenizer
|
| 6 |
+
from modeling_cosmicfish import CosmicFish, CosmicConfig
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
def load_cosmicfish(model_dir):
|
| 10 |
+
"""Load CosmicFish model and tokenizer"""
|
| 11 |
+
# Load config
|
| 12 |
+
with open(f"{model_dir}/config.json", "r") as f:
|
| 13 |
+
config_dict = json.load(f)
|
| 14 |
+
|
| 15 |
+
# Create CosmicConfig
|
| 16 |
+
config = CosmicConfig(
|
| 17 |
+
vocab_size=config_dict["vocab_size"],
|
| 18 |
+
block_size=config_dict["block_size"],
|
| 19 |
+
n_layer=config_dict["n_layer"],
|
| 20 |
+
n_head=config_dict["n_head"],
|
| 21 |
+
n_embd=config_dict["n_embd"],
|
| 22 |
+
bias=config_dict["bias"],
|
| 23 |
+
dropout=0.0, # Set to 0 for inference
|
| 24 |
+
use_rotary=config_dict["use_rotary"],
|
| 25 |
+
use_swiglu=config_dict["use_swiglu"],
|
| 26 |
+
use_gqa=config_dict["use_gqa"],
|
| 27 |
+
n_query_groups=config_dict["n_query_groups"],
|
| 28 |
+
use_qk_norm=config_dict["use_qk_norm"]
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
# Create model
|
| 32 |
+
model = CosmicFish(config)
|
| 33 |
+
|
| 34 |
+
# Load weights
|
| 35 |
+
state_dict = torch.load(f"{model_dir}/pytorch_model.bin", map_location="cpu")
|
| 36 |
+
model.load_state_dict(state_dict)
|
| 37 |
+
model.eval()
|
| 38 |
+
|
| 39 |
+
# Load tokenizer
|
| 40 |
+
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
|
| 41 |
+
|
| 42 |
+
return model, tokenizer
|
| 43 |
+
|
| 44 |
+
# Example usage:
|
| 45 |
+
# model, tokenizer = load_cosmicfish("./")
|
| 46 |
+
# input_text = "The future of AI is"
|
| 47 |
+
# inputs = tokenizer.encode(input_text, return_tensors="pt")
|
| 48 |
+
# outputs = model.generate(inputs, max_length=50, temperature=0.7, do_sample=True)
|
| 49 |
+
# response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 50 |
+
# print(response)
|
modeling_cosmicfish.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CosmicFish Model - Inference Only Version
|
| 3 |
+
Minimal implementation for loading and running inference with CosmicFish.
|
| 4 |
+
Removes all training-specific code and optimizations.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import math
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from torch.nn import functional as F
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class CosmicConfig:
|
| 14 |
+
"""Configuration class for CosmicFish."""
|
| 15 |
+
|
| 16 |
+
def __init__(self,
|
| 17 |
+
vocab_size=50257,
|
| 18 |
+
block_size=512,
|
| 19 |
+
n_layer=12,
|
| 20 |
+
n_head=16,
|
| 21 |
+
n_embd=704,
|
| 22 |
+
bias=True,
|
| 23 |
+
dropout=0.0, # Always 0 for inference
|
| 24 |
+
n_query_groups=4,
|
| 25 |
+
eps=1e-6,
|
| 26 |
+
use_rotary=True,
|
| 27 |
+
use_swiglu=True,
|
| 28 |
+
use_qk_norm=False,
|
| 29 |
+
use_gqa=True):
|
| 30 |
+
self.vocab_size = vocab_size
|
| 31 |
+
self.block_size = block_size
|
| 32 |
+
self.n_layer = n_layer
|
| 33 |
+
self.n_head = n_head
|
| 34 |
+
self.n_embd = n_embd
|
| 35 |
+
self.bias = bias
|
| 36 |
+
self.dropout = dropout
|
| 37 |
+
self.eps = eps
|
| 38 |
+
self.use_rotary = use_rotary
|
| 39 |
+
self.use_swiglu = use_swiglu
|
| 40 |
+
self.use_qk_norm = use_qk_norm
|
| 41 |
+
self.use_gqa = use_gqa
|
| 42 |
+
self.n_query_groups = n_query_groups if use_gqa else n_head
|
| 43 |
+
# Ensure n_head is divisible by n_query_groups
|
| 44 |
+
assert n_head % self.n_query_groups == 0, "n_head must be divisible by n_query_groups"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class RMSNorm(nn.Module):
|
| 48 |
+
"""Root Mean Square Normalization"""
|
| 49 |
+
|
| 50 |
+
def __init__(self, dim, eps=1e-6):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.eps = eps
|
| 53 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 54 |
+
|
| 55 |
+
def forward(self, x):
|
| 56 |
+
rms = torch.sqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
|
| 57 |
+
return self.weight * (x / rms)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def precompute_freqs_cis(dim, end, theta=10000.0):
|
| 61 |
+
"""Precompute the frequency tensor for complex exponentials (cis)"""
|
| 62 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
| 63 |
+
t = torch.arange(end, device=freqs.device)
|
| 64 |
+
freqs = torch.outer(t, freqs)
|
| 65 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
|
| 66 |
+
return freqs_cis
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def apply_rotary_emb(xq, xk, freqs_cis):
|
| 70 |
+
"""Apply rotary embeddings to input tensors"""
|
| 71 |
+
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
|
| 72 |
+
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
|
| 73 |
+
|
| 74 |
+
seq_len = xq_.size(2)
|
| 75 |
+
if freqs_cis.size(0) < seq_len:
|
| 76 |
+
raise ValueError(f"freqs_cis has only {freqs_cis.size(0)} values but sequence length is {seq_len}")
|
| 77 |
+
|
| 78 |
+
freqs_cis_seq = freqs_cis[:seq_len]
|
| 79 |
+
xq_out = torch.view_as_real(xq_ * freqs_cis_seq.unsqueeze(0)).flatten(3)
|
| 80 |
+
xk_out = torch.view_as_real(xk_ * freqs_cis_seq.unsqueeze(0)).flatten(3)
|
| 81 |
+
|
| 82 |
+
return xq_out.type_as(xq), xk_out.type_as(xk)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class GroupedQueryAttention(nn.Module):
|
| 86 |
+
"""Grouped Query Attention (GQA) implementation"""
|
| 87 |
+
|
| 88 |
+
def __init__(self, config):
|
| 89 |
+
super().__init__()
|
| 90 |
+
assert config.n_embd % config.n_head == 0
|
| 91 |
+
|
| 92 |
+
head_dim = config.n_embd // config.n_head
|
| 93 |
+
self.head_dim = head_dim
|
| 94 |
+
self.n_head = config.n_head
|
| 95 |
+
self.n_embd = config.n_embd
|
| 96 |
+
self.n_query_groups = config.n_query_groups
|
| 97 |
+
|
| 98 |
+
self.kv_heads = config.n_head // config.n_query_groups if config.use_gqa else config.n_head
|
| 99 |
+
qkv_proj_size = (config.n_head + 2 * self.kv_heads) * head_dim
|
| 100 |
+
|
| 101 |
+
self.c_attn = nn.Linear(config.n_embd, qkv_proj_size, bias=config.bias)
|
| 102 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
|
| 103 |
+
|
| 104 |
+
# Flash attention support
|
| 105 |
+
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
|
| 106 |
+
if not self.flash:
|
| 107 |
+
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
|
| 108 |
+
.view(1, 1, config.block_size, config.block_size))
|
| 109 |
+
|
| 110 |
+
# Query-key normalization
|
| 111 |
+
self.qk_norm = getattr(config, 'use_qk_norm', False)
|
| 112 |
+
if self.qk_norm:
|
| 113 |
+
self.q_norm = RMSNorm(head_dim, eps=getattr(config, 'eps', 1e-6))
|
| 114 |
+
self.k_norm = RMSNorm(head_dim, eps=getattr(config, 'eps', 1e-6))
|
| 115 |
+
|
| 116 |
+
def forward(self, x, freqs_cis=None):
|
| 117 |
+
B, T, C = x.size()
|
| 118 |
+
qkv = self.c_attn(x)
|
| 119 |
+
head_dim = C // self.n_head
|
| 120 |
+
|
| 121 |
+
q_size = self.n_head * head_dim
|
| 122 |
+
k_size = self.kv_heads * head_dim
|
| 123 |
+
v_size = self.kv_heads * head_dim
|
| 124 |
+
|
| 125 |
+
q, k, v = qkv.split([q_size, k_size, v_size], dim=2)
|
| 126 |
+
|
| 127 |
+
q = q.view(B, T, self.n_head, head_dim).transpose(1, 2)
|
| 128 |
+
k = k.view(B, T, self.kv_heads, head_dim).transpose(1, 2)
|
| 129 |
+
v = v.view(B, T, self.kv_heads, head_dim).transpose(1, 2)
|
| 130 |
+
|
| 131 |
+
# Repeat k and v if needed for GQA
|
| 132 |
+
if self.kv_heads < self.n_head:
|
| 133 |
+
repeats = self.n_head // self.kv_heads
|
| 134 |
+
k = k.repeat_interleave(repeats, dim=1)
|
| 135 |
+
v = v.repeat_interleave(repeats, dim=1)
|
| 136 |
+
|
| 137 |
+
# Apply rotary embeddings
|
| 138 |
+
if freqs_cis is not None:
|
| 139 |
+
q, k = apply_rotary_emb(q, k, freqs_cis)
|
| 140 |
+
|
| 141 |
+
# Apply query-key normalization
|
| 142 |
+
if self.qk_norm:
|
| 143 |
+
q = self.q_norm(q)
|
| 144 |
+
k = self.k_norm(k)
|
| 145 |
+
|
| 146 |
+
# Compute attention
|
| 147 |
+
if self.flash:
|
| 148 |
+
y = torch.nn.functional.scaled_dot_product_attention(
|
| 149 |
+
q, k, v, attn_mask=None, dropout_p=0.0, is_causal=True
|
| 150 |
+
)
|
| 151 |
+
else:
|
| 152 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
| 153 |
+
att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
|
| 154 |
+
att = F.softmax(att, dim=-1)
|
| 155 |
+
y = att @ v
|
| 156 |
+
|
| 157 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C)
|
| 158 |
+
y = self.c_proj(y)
|
| 159 |
+
return y
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class Block(nn.Module):
|
| 163 |
+
"""Transformer block"""
|
| 164 |
+
|
| 165 |
+
def __init__(self, config):
|
| 166 |
+
super().__init__()
|
| 167 |
+
self.ln_1 = RMSNorm(config.n_embd, eps=config.eps)
|
| 168 |
+
self.ln_2 = RMSNorm(config.n_embd, eps=config.eps)
|
| 169 |
+
self.attn = GroupedQueryAttention(config)
|
| 170 |
+
|
| 171 |
+
# MLP implementation based on configuration
|
| 172 |
+
if config.use_swiglu:
|
| 173 |
+
# SwiGLU MLP
|
| 174 |
+
self.mlp = nn.ModuleDict(dict(
|
| 175 |
+
gate=nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias),
|
| 176 |
+
up=nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias),
|
| 177 |
+
down=nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias),
|
| 178 |
+
act=nn.SiLU(),
|
| 179 |
+
))
|
| 180 |
+
m = self.mlp
|
| 181 |
+
self.mlpf = lambda x: m.down(m.act(m.up(x)) * m.gate(x))
|
| 182 |
+
else:
|
| 183 |
+
# Traditional MLP
|
| 184 |
+
self.mlp = nn.ModuleDict(dict(
|
| 185 |
+
c_fc=nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias),
|
| 186 |
+
c_proj=nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias),
|
| 187 |
+
act=nn.GELU(),
|
| 188 |
+
))
|
| 189 |
+
m = self.mlp
|
| 190 |
+
self.mlpf = lambda x: m.c_proj(m.act(m.c_fc(x)))
|
| 191 |
+
|
| 192 |
+
def forward(self, x, freqs_cis=None):
|
| 193 |
+
x = x + self.attn(self.ln_1(x), freqs_cis)
|
| 194 |
+
x = x + self.mlpf(self.ln_2(x))
|
| 195 |
+
return x
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class CosmicFish(nn.Module):
|
| 199 |
+
"""
|
| 200 |
+
CosmicFish model for inference only.
|
| 201 |
+
Features: Rotary Positional Embeddings, Grouped-Query Attention, SwiGLU, RMSNorm
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
+
def __init__(self, config):
|
| 205 |
+
super().__init__()
|
| 206 |
+
self.config = config
|
| 207 |
+
|
| 208 |
+
self.transformer = nn.ModuleDict(dict(
|
| 209 |
+
wte=nn.Embedding(config.vocab_size, config.n_embd),
|
| 210 |
+
h=nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
| 211 |
+
ln_f=RMSNorm(config.n_embd, eps=config.eps),
|
| 212 |
+
))
|
| 213 |
+
|
| 214 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 215 |
+
|
| 216 |
+
# Share weights between embedding and output
|
| 217 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 218 |
+
|
| 219 |
+
# Precompute rotary embedding frequencies
|
| 220 |
+
if config.use_rotary:
|
| 221 |
+
head_dim = config.n_embd // config.n_head
|
| 222 |
+
self.freqs_cis = precompute_freqs_cis(head_dim, config.block_size)
|
| 223 |
+
else:
|
| 224 |
+
self.freqs_cis = None
|
| 225 |
+
self.transformer.wpe = nn.Embedding(config.block_size, config.n_embd)
|
| 226 |
+
|
| 227 |
+
def get_num_params(self, non_embedding=True):
|
| 228 |
+
"""Return the number of parameters in the model."""
|
| 229 |
+
n_params = sum(p.numel() for p in self.parameters())
|
| 230 |
+
if non_embedding and hasattr(self.transformer, 'wpe'):
|
| 231 |
+
n_params -= self.transformer.wpe.weight.numel()
|
| 232 |
+
return n_params
|
| 233 |
+
|
| 234 |
+
def forward(self, idx, targets=None):
|
| 235 |
+
"""Forward pass through the model."""
|
| 236 |
+
device = idx.device
|
| 237 |
+
b, t = idx.size()
|
| 238 |
+
assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
|
| 239 |
+
|
| 240 |
+
# Get token embeddings
|
| 241 |
+
tok_emb = self.transformer.wte(idx)
|
| 242 |
+
|
| 243 |
+
# Handle positional embeddings
|
| 244 |
+
if self.config.use_rotary:
|
| 245 |
+
x = tok_emb
|
| 246 |
+
freqs_cis = self.freqs_cis.to(device) if self.freqs_cis is not None else None
|
| 247 |
+
else:
|
| 248 |
+
pos = torch.arange(0, t, dtype=torch.long, device=device).unsqueeze(0)
|
| 249 |
+
pos_emb = self.transformer.wpe(pos)
|
| 250 |
+
x = tok_emb + pos_emb
|
| 251 |
+
freqs_cis = None
|
| 252 |
+
|
| 253 |
+
# Apply transformer blocks
|
| 254 |
+
for block in self.transformer.h:
|
| 255 |
+
x = block(x, freqs_cis)
|
| 256 |
+
|
| 257 |
+
# Apply final normalization
|
| 258 |
+
x = self.transformer.ln_f(x)
|
| 259 |
+
|
| 260 |
+
# Calculate outputs
|
| 261 |
+
if targets is not None:
|
| 262 |
+
logits = self.lm_head(x)
|
| 263 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
|
| 264 |
+
else:
|
| 265 |
+
# For inference, only compute logits for the last token
|
| 266 |
+
logits = self.lm_head(x[:, [-1], :])
|
| 267 |
+
loss = None
|
| 268 |
+
|
| 269 |
+
return logits, loss
|
| 270 |
+
|
| 271 |
+
@torch.no_grad()
|
| 272 |
+
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
|
| 273 |
+
"""
|
| 274 |
+
Generate text by sampling from the model, token by token.
|
| 275 |
+
"""
|
| 276 |
+
for _ in range(max_new_tokens):
|
| 277 |
+
# Crop sequence to block size if needed
|
| 278 |
+
idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
|
| 279 |
+
|
| 280 |
+
# Forward pass
|
| 281 |
+
logits, _ = self(idx_cond)
|
| 282 |
+
logits = logits[:, -1, :] / temperature
|
| 283 |
+
|
| 284 |
+
# Apply top-k sampling
|
| 285 |
+
if top_k is not None:
|
| 286 |
+
v, _ = torch.topk(logits, top_k)
|
| 287 |
+
logits[logits < v[:, [-1]]] = -float('Inf')
|
| 288 |
+
|
| 289 |
+
# Sample next token
|
| 290 |
+
probs = F.softmax(logits, dim=-1)
|
| 291 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
| 292 |
+
|
| 293 |
+
# Append to sequence
|
| 294 |
+
idx = torch.cat((idx, idx_next), dim=1)
|
| 295 |
+
|
| 296 |
+
return idx
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f8fdc674e0b6392940633e05bb6dbf6cab45da20ae94af719de462ca50cbbf7d
|
| 3 |
+
size 243512043
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "GPT2Tokenizer",
|
| 3 |
+
"vocab_size": 50257,
|
| 4 |
+
"model_max_length": 512,
|
| 5 |
+
"bos_token": "<|endoftext|>",
|
| 6 |
+
"eos_token": "<|endoftext|>",
|
| 7 |
+
"unk_token": "<|endoftext|>",
|
| 8 |
+
"pad_token": "<|endoftext|>",
|
| 9 |
+
"add_prefix_space": false,
|
| 10 |
+
"do_lower_case": false
|
| 11 |
+
}
|
vocab_info.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"note": "This model uses GPT-2 tokenizer. Please use: tokenizer = GPT2Tokenizer.from_pretrained('gpt2')",
|
| 3 |
+
"vocab_size": 50257,
|
| 4 |
+
"encoding": "gpt2"
|
| 5 |
+
}
|