Elijah commited on
Commit
8410be3
·
verified ·
1 Parent(s): 728c3c9

Upload 12 files

Browse files
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.
README.md CHANGED
@@ -1,3 +1,175 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ annotations_creators:
3
+ - machine-generated
4
+ language:
5
+ - en
6
+ language_creators:
7
+ - machine-generated
8
+ license:
9
+ - mit
10
+ multilinguality:
11
+ - monolingual
12
+ pretty_name: Dakitari-Instruct
13
+ size_categories:
14
+ - 10M<n<100M
15
+ source_datasets:
16
+ - hwang2006/PUBMED_title_abstracts_2020_baseline
17
+ - vaishnavm/medquad
18
+ - pubmed_qa
19
+ task_categories:
20
+ - text-generation
21
+ - question-answering
22
+ task_ids:
23
+ - language-modeling
24
+ - medical-qa
25
+ ---
26
+
27
+ # Dakitari-Instruct Medical Language Model
28
+
29
+ A specialized language model for medical text generation and question answering, trained on PubMed abstracts and medical QA datasets.
30
+
31
+ ## Model Description
32
+
33
+ - **Model Type:** Transformer-based Language Model
34
+ - **Language:** English
35
+ - **License:** MIT
36
+ - **Training Data:** PubMed abstracts + Medical QA pairs
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ from transformers import AutoTokenizer, AutoModelForCausalLM
42
+
43
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext")
44
+ model = AutoModelForCausalLM.from_pretrained("path/to/dakitari-instruct")
45
+ ```
46
+
47
+ ## Training Data
48
+
49
+ This model is trained on:
50
+ 1. PubMed abstracts (biomedical literature)
51
+ 2. Medical question-answer pairs
52
+
53
+ For detailed dataset information, see [dataset_card.md](dataset_card.md).
54
+
55
+ ## Features
56
+
57
+ - Medical text generation
58
+ - Medical question answering
59
+ - Research assistance
60
+ - Built on transformer architecture
61
+ - Trained on PubMed abstracts and medical Q&A datasets
62
+
63
+ ## Requirements
64
+
65
+ - Python 3.8+
66
+ - TensorFlow 2.13+
67
+ - Transformers library
68
+ - Other dependencies listed in `requirements.txt`
69
+
70
+ ## Installation
71
+
72
+ 1. Clone the repository:
73
+ ```bash
74
+ git clone https://github.com/elijahnzeli1/dakitari-instruct.git
75
+ cd dakitari-instruct
76
+ ```
77
+
78
+ 2. Create a virtual environment (recommended):
79
+ ```bash
80
+ python -m venv venv
81
+ #for windows
82
+ .\venv\Scripts\Activate
83
+ #for mac/linux
84
+ source venv/bin/activate
85
+ ```
86
+
87
+ 3. Install dependencies:
88
+ ```bash
89
+ pip install -r requirements.txt
90
+ ```
91
+
92
+ ## Training the Model
93
+
94
+ 1. Start training:
95
+ ```bash
96
+ python train.py --batch_size 32 --epochs 10
97
+ ```
98
+
99
+ 2. Monitor training progress with TensorBoard:
100
+ ```bash
101
+ tensorboard --logdir logs
102
+ ```
103
+ Then open your browser and navigate to `http://localhost:6006` to view training metrics.
104
+
105
+ Training logs are also saved in CSV format in the `logs` directory for backup.
106
+
107
+ ### Training Parameters
108
+
109
+ You can customize the training by adjusting these parameters:
110
+
111
+ - `--batch_size`: Batch size for training (default: 32)
112
+ - `--epochs`: Number of training epochs (default: 10)
113
+ - `--max_length`: Maximum sequence length (default: 512)
114
+ - `--embed_dim`: Embedding dimension (default: 256)
115
+ - `--num_heads`: Number of attention heads (default: 8)
116
+ - `--ff_dim`: Feed-forward dimension (default: 512)
117
+ - `--num_transformer_blocks`: Number of transformer blocks (default: 6)
118
+ - `--dropout_rate`: Dropout rate (default: 0.1)
119
+ - `--learning_rate`: Learning rate (default: 1e-4)
120
+ - `--checkpoint_dir`: Directory to save model checkpoints (default: "checkpoints")
121
+ - `--log_dir`: Directory to save training logs (default: "logs")
122
+
123
+ ## Project Structure
124
+
125
+ ```
126
+ dakitari-instruct/
127
+ ├── data/
128
+ │ └── preprocess.py # Data preprocessing utilities
129
+ ├── model/
130
+ │ └── transformer_model.py # Model architecture
131
+ ├── train.py # Training script
132
+ ├── requirements.txt # Project dependencies
133
+ └── README.md # This file
134
+ ```
135
+
136
+ ## Hardware Requirements
137
+
138
+ - Minimum: 16GB RAM, NVIDIA GPU with 8GB VRAM
139
+ - Recommended: 32GB RAM, NVIDIA GPU with 16GB+ VRAM
140
+
141
+ ## Dataset Sources
142
+
143
+ The model is trained on:
144
+ 1. PubMed abstracts
145
+ 2. Medical questions and answers pairs
146
+
147
+ ## Contributing
148
+
149
+ 1. Fork the repository
150
+ 2. Create your feature branch
151
+ 3. Commit your changes
152
+ 4. Push to the branch
153
+ 5. Create a new Pull Request
154
+
155
+ ## License
156
+
157
+ This project is licensed under the MIT License - see the LICENSE file for details.
158
+
159
+ ## Acknowledgments
160
+
161
+ - Thanks to the HuggingFace team for the transformers library
162
+ - Thanks to the TensorFlow team for the excellent framework
163
+ - Thanks to the medical community for the valuable datasets
164
+
165
+ Now you can track your training progress locally using TensorBoard, which provides:
166
+ - Real-time metrics visualization
167
+ - Learning rate tracking
168
+ - Model graph visualization
169
+ - Histogram of weights and biases
170
+
171
+ The training metrics are also saved in CSV format as a backup, which you can analyze using any spreadsheet software or data analysis tools.
172
+ To view the training progress:
173
+ - Start training your model
174
+ - In a separate terminal, run [tensorboard --logdir logs]()
175
+ - Open <http://localhost:6006> in your browser
config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "dakitari_instruct",
3
+ "architectures": [
4
+ "DakitariInstructModel"
5
+ ],
6
+ "vocab_size": 30522,
7
+ "hidden_size": 256,
8
+ "num_attention_heads": 8,
9
+ "num_hidden_layers": 6,
10
+ "epoch": 2,
11
+ "global_step": 34191
12
+ }
configuration_dakitari_instruct.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+
3
+ class DakitariInstructConfig(PretrainedConfig):
4
+ model_type = "dakitari_instruct"
5
+
6
+ def __init__(
7
+ self,
8
+ vocab_size=30522,
9
+ n_positions=512,
10
+ n_embd=768, # increased embedding dimension
11
+ n_layer=24, # increased number of layers
12
+ n_head=8, # increased attention heads if desired
13
+ n_inner=3072, # increased feed-forward dimension
14
+ pad_token_id=0,
15
+ bos_token_id=1,
16
+ eos_token_id=2,
17
+ activation_function="gelu",
18
+ resid_pdrop=0.1,
19
+ embd_pdrop=0.1,
20
+ attn_pdrop=0.1,
21
+ layer_norm_epsilon=1e-5,
22
+ initializer_range=0.02,
23
+ adapter_bottleneck=128, # optionally increase adapter capacity
24
+ model_name="DakitariInstruct-v1.1",
25
+ creator="Quantum Leap AI company",
26
+ country="Kenya, Africa",
27
+ healthcare_purpose="Assist healthcare professionals and patients with accurate medical information",
28
+ **kwargs
29
+ ):
30
+ self.vocab_size = vocab_size
31
+ self.n_positions = n_positions
32
+ self.n_embd = n_embd
33
+ self.n_layer = n_layer
34
+ self.n_head = n_head
35
+ self.n_inner = n_inner
36
+ self.pad_token_id = pad_token_id
37
+ self.bos_token_id = bos_token_id
38
+ self.eos_token_id = eos_token_id
39
+ self.activation_function = activation_function
40
+ self.resid_pdrop = resid_pdrop
41
+ self.embd_pdrop = embd_pdrop
42
+ self.attn_pdrop = attn_pdrop
43
+ self.layer_norm_epsilon = layer_norm_epsilon
44
+ self.initializer_range = initializer_range
45
+ self.adapter_bottleneck = adapter_bottleneck
46
+ self.model_name = model_name
47
+ self.creator = creator
48
+ self.country = country
49
+ self.healthcare_purpose = healthcare_purpose
50
+ super().__init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "max_length": 512,
3
+ "num_beams": 4,
4
+ "do_sample": true,
5
+ "temperature": 0.7,
6
+ "top_k": 50,
7
+ "top_p": 0.9,
8
+ "repetition_penalty": 1.2,
9
+ "no_repeat_ngram_size": 3
10
+ }
model.safetensors.index.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "format": "tf"
4
+ },
5
+ "weight_map": {
6
+ "embeddings": "model.safetensors",
7
+ "kernel": "model.safetensors",
8
+ "bias": "model.safetensors",
9
+ "gamma": "model.safetensors",
10
+ "beta": "model.safetensors"
11
+ }
12
+ }
modeling_dakitari_instruct.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ from transformers.modeling_utils import PreTrainedModel
5
+ from transformers.modeling_outputs import CausalLMOutput
6
+ from transformers.generation import GenerationMixin # NEW: Import GenerationMixin
7
+ from .configuration_dakitari_instruct import DakitariInstructConfig
8
+
9
+ class SimpleAttention(nn.Module):
10
+ def __init__(self, config):
11
+ super().__init__()
12
+ self.n_embd = config.n_embd
13
+ self.in_proj = nn.Linear(config.n_embd, config.n_embd)
14
+ self.out_proj = nn.Linear(config.n_embd, config.n_embd)
15
+
16
+ def forward(self, x, attention_mask=None):
17
+ B, L, D = x.size() # batch, length, dimension
18
+ q = k = v = self.in_proj(x)
19
+
20
+ # Compute attention scores
21
+ scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(D)
22
+
23
+ if attention_mask is not None:
24
+ # Expand mask to correct shape
25
+ attention_mask = attention_mask.view(B, 1, L)
26
+ scores = scores.masked_fill(~attention_mask, float('-inf'))
27
+
28
+ attn = torch.softmax(scores, dim=-1)
29
+ context = torch.matmul(attn, v)
30
+ return self.out_proj(context)
31
+
32
+ class CustomTransformerLayer(nn.Module):
33
+ def __init__(self, config):
34
+ super().__init__()
35
+ self.attention = SimpleAttention(config)
36
+ self.linear1 = nn.Linear(config.n_embd, config.n_embd) # Keep dimensions consistent
37
+ self.linear2 = nn.Linear(config.n_embd, config.n_embd) # Keep dimensions consistent
38
+ self.norm1 = nn.LayerNorm(config.n_embd)
39
+ self.norm2 = nn.LayerNorm(config.n_embd)
40
+ self.dropout = nn.Dropout(config.resid_pdrop)
41
+ self.activation = nn.GELU()
42
+ # New: Adapter layers for domain-specific finetuning
43
+ self.adapter_down = nn.Linear(config.n_embd, config.adapter_bottleneck)
44
+ self.adapter_up = nn.Linear(config.adapter_bottleneck, config.n_embd)
45
+ self.norm_adapter = nn.LayerNorm(config.n_embd)
46
+
47
+ def forward(self, x, attention_mask=None):
48
+ residual = x
49
+ x_norm = self.norm1(x)
50
+ x_attn = self.attention(x_norm, attention_mask)
51
+ x = residual + self.dropout(x_attn)
52
+
53
+ residual = x
54
+ x_norm = self.norm2(x)
55
+ x_ff = self.linear2(self.dropout(self.activation(self.linear1(x_norm))))
56
+ x = residual + self.dropout(x_ff)
57
+
58
+ # New: Adapter branch (only train adapter layers)
59
+ adapter_input = self.norm_adapter(x)
60
+ adapter_out = self.adapter_up(self.adapter_down(adapter_input))
61
+ x = x + adapter_out
62
+
63
+ return x
64
+
65
+ class DakitariInstructModel(PreTrainedModel, GenerationMixin): # Updated: Inherit from GenerationMixin
66
+ config_class = DakitariInstructConfig
67
+
68
+ def __init__(self, config):
69
+ super().__init__(config)
70
+ self.config = config
71
+
72
+ # Update embeddings with new dimensions
73
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
74
+ self.wpe = nn.Embedding(config.n_positions, config.n_embd)
75
+ self.drop = nn.Dropout(config.embd_pdrop)
76
+
77
+ # Build transformer layers based on new n_layer value and dimensions
78
+ self.layers = nn.ModuleList([
79
+ CustomTransformerLayer(config)
80
+ for _ in range(config.n_layer)
81
+ ])
82
+
83
+ self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
84
+ # New: LM head for generation
85
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
86
+
87
+ self.apply(self._init_weights)
88
+ # Ensure adapter layers are not frozen (already commented out freezing)
89
+ for name, param in self.named_parameters():
90
+ if "adapter" in name:
91
+ param.requires_grad = True # Explicit: make sure adapters train
92
+
93
+ def _init_weights(self, module):
94
+ if isinstance(module, (nn.Linear, nn.Embedding)):
95
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
96
+ if isinstance(module, nn.Linear) and module.bias is not None:
97
+ module.bias.data.zero_()
98
+ elif isinstance(module, nn.LayerNorm):
99
+ module.bias.data.zero_()
100
+ module.weight.data.fill_(1.0)
101
+
102
+ def forward(self, input_ids=None, attention_mask=None, position_ids=None, **kwargs):
103
+ if input_ids is None:
104
+ raise ValueError("input_ids must be provided")
105
+
106
+ # Ensure input_ids are within bounds
107
+ input_ids = torch.clamp(input_ids, 0, self.config.vocab_size - 1)
108
+
109
+ input_shape = input_ids.shape
110
+ batch_size, seq_length = input_shape
111
+
112
+ # Handle position IDs correctly
113
+ if position_ids is None:
114
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)
115
+ position_ids = position_ids.unsqueeze(0).expand(batch_size, seq_length)
116
+
117
+ # Embeddings
118
+ inputs_embeds = self.wte(input_ids)
119
+ position_embeds = self.wpe(position_ids)
120
+ hidden_states = self.drop(inputs_embeds + position_embeds)
121
+
122
+ # Ensure attention mask is bool tensor
123
+ if attention_mask is not None:
124
+ attention_mask = attention_mask.bool()
125
+
126
+ # Process through transformer layers
127
+ for layer in self.layers:
128
+ hidden_states = layer(hidden_states, attention_mask)
129
+
130
+ hidden_states = self.ln_f(hidden_states)
131
+ logits = self.lm_head(hidden_states)
132
+ # NEW: Return a CausalLMOutput with logits attribute so generate() works correctly
133
+ return CausalLMOutput(logits=logits, loss=logits.mean())
134
+
135
+ # NEW: Override generation input preparation
136
+ def prepare_inputs_for_generation(self, input_ids, **kwargs):
137
+ return {"input_ids": input_ids}
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_basic_tokenize": true,
47
+ "do_lower_case": true,
48
+ "extra_special_tokens": {},
49
+ "mask_token": "[MASK]",
50
+ "model_max_length": 1000000000000000019884624838656,
51
+ "never_split": null,
52
+ "pad_token": "[PAD]",
53
+ "sep_token": "[SEP]",
54
+ "strip_accents": null,
55
+ "tokenize_chinese_chars": true,
56
+ "tokenizer_class": "BertTokenizer",
57
+ "unk_token": "[UNK]"
58
+ }
training_state.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4713bd7eff0a031558e8182c82c6b15104babb58b950f200ec4c0dfe701ca7cb
3
+ size 1641950
vocab.txt ADDED
The diff for this file is too large to render. See raw diff