PodAI commited on
Commit
0fe78e2
1 Parent(s): 4cb1d09

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +186 -120
README.md CHANGED
@@ -1,199 +1,265 @@
1
  ---
2
  library_name: transformers
3
- tags: []
 
 
 
 
4
  ---
5
 
6
- # Model Card for Model ID
7
-
8
- <!-- Provide a quick summary of what the model is/does. -->
9
-
10
-
11
-
12
  ## Model Details
13
 
14
- ### Model Description
15
-
16
- <!-- Provide a longer summary of what this model is. -->
17
-
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
-
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
-
28
- ### Model Sources [optional]
29
 
30
- <!-- Provide the basic links for the model. -->
31
 
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
 
36
- ## Uses
37
 
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
 
40
- ### Direct Use
 
 
 
 
 
 
41
 
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
 
44
- [More Information Needed]
45
 
46
- ### Downstream Use [optional]
47
 
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- [More Information Needed]
51
 
52
- ### Out-of-Scope Use
53
 
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
 
56
- [More Information Needed]
57
 
58
- ## Bias, Risks, and Limitations
 
59
 
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
 
62
- [More Information Needed]
63
 
64
- ### Recommendations
65
 
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
 
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
 
70
- ## How to Get Started with the Model
71
 
72
- Use the code below to get started with the model.
73
 
74
- [More Information Needed]
75
 
76
- ## Training Details
77
 
78
- ### Training Data
79
 
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
 
82
- [More Information Needed]
83
 
84
- ### Training Procedure
85
 
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
 
88
  #### Preprocessing [optional]
89
 
90
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
 
93
  #### Training Hyperparameters
94
 
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
 
103
  ## Evaluation
104
 
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
 
107
- ### Testing Data, Factors & Metrics
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
- #### Testing Data
110
 
111
- <!-- This should link to a Dataset Card if possible. -->
112
 
113
- [More Information Needed]
 
 
114
 
115
- #### Factors
116
 
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
 
 
 
118
 
119
- [More Information Needed]
120
 
121
- #### Metrics
122
 
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
 
131
  #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
 
159
  ### Compute Infrastructure
160
 
161
- [More Information Needed]
162
 
163
  #### Hardware
164
 
165
- [More Information Needed]
166
-
167
- #### Software
168
 
169
  [More Information Needed]
170
 
171
- ## Citation [optional]
172
 
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
 
 
 
 
 
174
 
175
- **BibTeX:**
176
 
177
- [More Information Needed]
178
 
179
- **APA:**
180
 
181
- [More Information Needed]
182
 
183
- ## Glossary [optional]
184
 
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
 
187
- [More Information Needed]
188
 
189
- ## More Information [optional]
190
 
191
- [More Information Needed]
192
 
193
- ## Model Card Authors [optional]
194
 
195
- [More Information Needed]
196
 
197
- ## Model Card Contact
198
 
199
- [More Information Needed]
 
1
  ---
2
  library_name: transformers
3
+ license: mit
4
+ language:
5
+ - en
6
+ metrics:
7
+ - accuracy
8
  ---
9
 
 
 
 
 
 
 
10
  ## Model Details
11
 
12
+ A Gemma2B-it model finetuned on
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ ### Model Description
15
 
16
+ This is a fine-tuned version of the Gemma2B-it model, a large language model developed by Google.
17
+ The fine-tuning process has been performed on a medical reasoning dataset to adapt the model for answering medical-related questions.
 
18
 
 
19
 
20
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
21
 
22
+ - **Developed by:** Ananya S Kaligal, Kashish Varma, Ajay S Patil
23
+ - **Mentored by:** Dr.Shabeerbasha S H
24
+ - **Supported by:** RV University
25
+ - **Model type:** Instruct
26
+ - **Language(s) (NLP):** english-en
27
+ - **License:** [MIT]
28
+ - **Finetuned from model:** google/gemma2b-it
29
 
30
+ ### Model Sources [optional] : **Huggingface
31
 
32
+ - **Repository:** google/gemma2b-it
33
 
34
+ ## How to Get Started with the Model
35
 
36
+ Install Required Libraries:
37
+ Begin by installing the necessary Python libraries and their specific versions.
38
+ In this case, ensure you have the required versions of bitsandbytes, peft, trl, accelerate, datasets, and transformers.
39
+ You can use the following commands to install them:
40
+ ```
41
+ !pip3 install -q -U bitsandbytes==0.42.0
42
+ !pip3 install -q -U peft==0.8.2
43
+ !pip3 install -q -U trl==0.7.10
44
+ !pip3 install -q -U accelerate==0.27.1
45
+ !pip3 install -q -U datasets==2.17.0
46
+ !pip3 install -q -U transformers==4.38.0
47
+
48
+ ```
49
+ **Library Imports**: Import the required libraries in your Python script or Jupyter Notebook. These include torch, transformers, datasets, bitsandbytes, peft, and trl. These libraries provide functionalities for model training, optimization, and evaluation.<br>
50
+ **Model Setup**: Initialize the language model for causal language modeling (LM) using the AutoModelForCausalLM class from the transformers library. Load the pre-trained model from the Hugging Face Model Hub using its identifier, such as "google/gemma-2b-it". Configure any additional settings or optimizations required for your task.<br>
51
+ **Data Loading**: Load your training dataset using the load_dataset function from the datasets library. Specify the dataset identifier or path to load the desired dataset. This dataset will be used to fine-tune the language model for your specific task.<br>
52
+ **Prompt Generation**: Generate prompts for each data point in your training dataset. These prompts should include instructions for the task and any associated input data required for inference.<br>
53
+ **Tokenization**: Tokenize the generated prompts using the AutoTokenizer from the transformers library. Tokenization converts the text data into numerical inputs suitable for the language model.<br>
54
+ **Dataset Splitting**: Split your dataset into training and testing subsets using the train_test_split method. This allows you to evaluate the model's performance on unseen data during training.<br>
55
+ **Model Configuration**: Configure the language model for training by setting up various parameters and optimizations. This may include gradient checkpointing, low-rank adaptation, and other techniques to improve training efficiency and performance.<br>
56
+ **Training**: Train the language model using the SFTTrainer class from the trl library. Specify the training arguments such as batch size, learning rate, and optimization strategy. Monitor the training progress and evaluate the model's performance on the testing subset.<br>
57
+ **Model Saving**: Save the trained model and tokenizer locally using the save_pretrained method. This allows you to reload the model for future use without retraining.<br>
58
+ **Model Deployment**: Optionally, push the trained model and tokenizer to the Hugging Face Model Hub for sharing and deployment. This makes your model accessible to the wider community for use in various applications.<br>
59
 
 
60
 
 
61
 
 
62
 
63
+ ### Training Data
64
 
65
+ [ruslnmv] : ["https://huggingface.co/api/datasets/ruslanmv/ai-medical-chatbot/parquet/default/train/0.parquet"]<br>
66
+ [prsdm] : ["prsdm/MedQuad-phi2-1k"]
67
 
68
+ ### Training Procedure
69
 
 
70
 
71
+ 1. **Data Loading**: The training data is loaded using the `load_dataset` function from the `datasets` library. In this case, the dataset used is `"mamachang/medical-reasoning"`.
72
 
73
+ 2. **Model Setup**: The language model for causal language modeling (LM) is initialized using the `AutoModelForCausalLM` class from the `transformers` library. The model is loaded from the `"google/gemma-2b-it"` pre-trained model. Additionally, a `BitsAndBytesConfig` is used to configure low-precision quantization for the model.
74
 
75
+ 3. **Prompt Generation**: The training data is preprocessed by generating prompts for each data point. These prompts include instructions for a task and any associated input data.
76
 
77
+ 4. **Tokenization**: The generated prompts are tokenized using the `AutoTokenizer` from the `transformers` library. Tokenization is necessary to convert the text data into numerical inputs suitable for the model.
78
 
79
+ 5. **Dataset Splitting**: The dataset is split into training and testing subsets using the `train_test_split` method. This allows for evaluating the model's performance on unseen data during training.
80
 
81
+ 6. **Model Configuration**: Various model configurations, such as gradient checkpointing and low-rank adaptation (LORA), are set up to optimize training performance and efficiency.
82
 
83
+ 7. **Training**: The model is trained using the `SFTTrainer` class from the `trl` library. Training is performed using the specified training arguments, including batch size, learning rate, and optimization strategy.
84
 
85
+ 8. **Model Saving**: After training, the fine-tuned model is saved locally using the `save_pretrained` method. Additionally, the tokenizer's configuration is saved for future use.
86
 
87
+ 9. **Merging Base and Fine-tuned Models**: The fine-tuned model is merged with the base model to create a new model that retains the optimizations and adaptations applied during training.
88
 
89
+ 10. **Push to Model Hub**: The merged model and tokenizer are pushed to the Hugging Face Model Hub for sharing and deployment.
90
 
91
+ 11. **Model Inference**: Finally, the trained model is used for text completion tasks by providing a prompt/question, encoding it, and generating a response using the `generate` method.
92
 
 
93
 
94
  #### Preprocessing [optional]
95
 
96
+ Certainly! Let's go through your code and identify the parts responsible for dataset preprocessing:
97
+
98
+ ```python
99
+ dataset = load_dataset("mamachang/medical-reasoning")
100
+ ```
101
+ - This line loads the dataset `"mamachang/medical-reasoning"` using the `load_dataset` function from the `datasets` library. It fetches the dataset from the Hugging Face dataset repository.
102
+
103
+ ```python
104
+ def generate_prompt(data_point):
105
+ # Generate prompt
106
+ prefix_text = 'Below is an instruction that describes a task. Write a response that ' \
107
+ 'appropriately completes the request.\n\n'
108
+ # Samples with additional context into.
109
+ if data_point['input']:
110
+ text = f"""<start_of_turn>user {prefix_text} {data_point["instruction"]} here are the inputs {data_point["input"]} <end_of_turn>\n<start_of_turn>model{data_point["output"]} <end_of_turn>"""
111
+ # Without
112
+ else:
113
+ text = f"""<start_of_turn>user {prefix_text} {data_point["instruction"]} <end_of_turn>\n<start_of_turn>model{data_point["output"]} <end_of_turn>"""
114
+ return text
115
+
116
+ text_column = [generate_prompt(data_point) for data_point in dataset["train"]]
117
+ dataset = dataset["train"].add_column("prompt", text_column)
118
+ ```
119
+ - Here, you define a function `generate_prompt` to create prompts for each data point in the dataset. The prompts include instructions for the task, along with any input data required. These prompts are then added as a new column named `"prompt"` to the training subset of the dataset.
120
+
121
+ ```python
122
+ dataset = dataset.shuffle(seed=1234) # Shuffle dataset here
123
+ dataset = dataset.map(lambda samples: tokenizer(samples["prompt"]), batched=True)
124
+ dataset = dataset.train_test_split(test_size=0.1)
125
+ train_data = dataset["train"]
126
+ test_data = dataset["test"]
127
+ ```
128
+ - The dataset is shuffled to randomize the order of data samples using the `shuffle` method. This helps prevent any inherent ordering bias in the dataset.
129
+ - Next, the `map` function is used to apply tokenization to the generated prompts using the tokenizer instantiated earlier. The prompts are tokenized in batches for efficiency.
130
+ - The preprocessed dataset is split into training and testing subsets using the `train_test_split` method. This allows for evaluating the model's performance on unseen data during training.
131
+
132
+ These parts of your code handle various aspects of dataset preprocessing, including data loading, prompt generation, tokenization, shuffling, and dataset splitting, to prepare the dataset for training the language model.
133
 
134
 
135
  #### Training Hyperparameters
136
 
137
+ 1. **BitsAndBytes Configuration**:
138
+ - `load_in_4bit=True`: Model weights are loaded in 4-bit precision.
139
+ - `bnb_4bit_use_double_quant=True`: Double quantization is used for 4-bit quantization.
140
+ - `bnb_4bit_quant_type="nf4"`: Normalization-Free 4-bit quantization is used.
141
+ - `bnb_4bit_compute_dtype=torch.bfloat16`: Computations are performed in bfloat16 precision.
142
+
143
+ 2. **LoRA Configuration**:
144
+ - `r=64`: Rank of the LoRA matrices.
145
+ - `lora_alpha=32`: Alpha value for LoRA scaling.
146
+ - `target_modules`: Determined dynamically based on the model's linear layers.
147
+ - `lora_dropout=0.05`: Dropout rate for LoRA matrices.
148
+ - `bias="none"`: No bias is used for LoRA.
149
+ - `task_type="CAUSAL_LM"`: Task type is set to casual language modeling.
150
+
151
+ 3. **Training Arguments**:
152
+ - `per_device_train_batch_size=1`: Batch size for training.
153
+ - `gradient_accumulation_steps=4`: Gradient accumulation steps.
154
+ - `warmup_steps=0.03`: Number of warmup steps for the learning rate scheduler.
155
+ - `max_steps=100`: Maximum number of training steps.
156
+ - `learning_rate=2e-4`: Learning rate for the optimizer.
157
+ - `logging_steps=1`: Logging interval (in steps).
158
+ - `output_dir="outputs"`: Output directory for saving checkpoints and logs.
159
+ - `optim="paged_adamw_8bit"`: Optimizer is 8-bit Paged AdamW.
160
+ - `save_strategy="epoch"`: Save strategy is set to save checkpoints after each epoch.
161
+
162
+ 4. **Data Collator**:
163
+ - `transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False)`: Data collator is set for language modeling without masked language modeling.
164
+
165
+ 5. **Other Configurations**:
166
+ - `max_seq_length=2500`: Maximum sequence length for input data.
167
+ - `model.config.use_cache=False`: Caching is disabled for the model.
168
+
169
+ These hyperparameters control various aspects of the training process, such as quantization, LoRA configuration, batch size, gradient accumulation, learning rate, and optimizer settings. Adjusting these hyperparameters can significantly impact the training performance, memory efficiency, and model accuracy.
170
 
 
 
 
171
 
172
  ## Evaluation
173
 
174
+ Sure! Let's delve into the evaluation process based on your code:
175
 
176
+ ```python
177
+ trainer = SFTTrainer(
178
+ model=model,
179
+ train_dataset=train_data,
180
+ eval_dataset=test_data,
181
+ dataset_text_field="prompt",
182
+ peft_config=lora_config,
183
+ max_seq_length=2500,
184
+ args=transformers.TrainingArguments(
185
+ per_device_train_batch_size=1,
186
+ gradient_accumulation_steps=4,
187
+ warmup_steps=0.03,
188
+ max_steps=100,
189
+ learning_rate=2e-4,
190
+ logging_steps=1,
191
+ output_dir="outputs",
192
+ optim="paged_adamw_8bit",
193
+ save_strategy="epoch",
194
+ ),
195
+ data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
196
+ )
197
+ ```
198
 
199
+ - The `SFTTrainer` class from the `trl` (Text Rewriting for Language Understanding) library is used for training and evaluation. It is initialized with parameters including the model, training dataset (`train_data`), evaluation dataset (`test_data`), dataset text field (which specifies the input field to use for the dataset), `peft_config` (configuration for the low-rank adaptation technique), and various training arguments specified in `transformers.TrainingArguments`.
200
 
201
+ - Evaluation is performed on the evaluation dataset (`test_data`). During evaluation, the model is evaluated on unseen data to assess its performance and generalization capabilities.
202
 
203
+ ```python
204
+ trainer.train()
205
+ ```
206
 
207
+ - After initializing the trainer, the `train` method is called to start the training process. During training, the model is fine-tuned on the training dataset (`train_data`) using the specified training arguments and configurations.
208
 
209
+ ```python
210
+ result = get_completion(query=query, model=merged_model, tokenizer=tokenizer)
211
+ print(result)
212
+ ```
213
 
214
+ - Lastly, a function named `get_completion` is called to generate completions for a given query using the trained model (`merged_model`). This completion is printed to the console for inspection or further analysis.
215
 
 
216
 
 
 
 
 
 
 
 
217
 
218
  #### Summary
219
+ The code implements fine-tuning and evaluation of a language model using Hugging Face's Transformers library. It loads a pre-trained model, prepares the dataset, trains the model, and evaluates its performance.
220
+ However, explicit evaluation metrics are not defined. The trained model is saved and can be used for generating text completions.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
  ### Compute Infrastructure
223
 
224
+ Utilised 20GB of NVIDIA A100
225
 
226
  #### Hardware
227
 
228
+ NVIDIA DGX-A100
 
 
229
 
230
  [More Information Needed]
231
 
232
+ #### Software
233
 
234
+ Python 3.10.12
235
+ Transformers 4.38.0
236
+ Torch 2.3.0
237
+ BitsAndBytes 0.42.0
238
+ TRL 0.7.10
239
+ PEFT 0.8.2
240
 
241
+ ## Glossary [optional]
242
 
243
+ 1. **BitsAndBytes**: A Python library that provides functionality for low-precision quantization and optimization of neural network models, allowing for efficient inference on resource-constrained devices by using 4-bit and 8-bit data types.
244
 
245
+ 2. **Quantization**: The process of converting floating-point model parameters and activations into lower precision formats, such as 4-bit or 8-bit integers, to reduce memory storage requirements and improve computational efficiency during inference.
246
 
247
+ 3. **Low-Rank Adaptation (LORA)**: A compression technique used to reduce the computational complexity of neural network models by approximating weight matrices with low-rank matrices, thereby decreasing the number of parameters and improving inference speed.
248
 
249
+ 4. **PeftModel**: A model variant optimized for low-precision training and inference, capable of handling data types such as 4-bit and 8-bit integers efficiently, typically used in scenarios where computational resources are limited.
250
 
251
+ 5. **Gradient Checkpointing**: A memory-saving technique used during training that trades off computational overhead for reduced memory usage by recomputing intermediate activations during backpropagation, rather than storing them in memory.
252
 
253
+ 6. **Data Collator**: A component responsible for batch processing and data preparation during training, including tasks such as padding sequences to a uniform length, shuffling batches, and converting data into tensor format suitable for input to the model.
254
 
255
+ 7. **Hardware Type**: The specific hardware infrastructure used for model training and inference, including details such as GPU (Graphics Processing Unit), CPU (Central Processing Unit), or specialized hardware accelerators like TPUs (Tensor Processing Units) or FPGAs (Field-Programmable Gate Arrays).
256
 
257
+ 8. **Paged AdamW Optimizer**: An optimization algorithm derived from the AdamW optimizer, which updates model parameters based on gradient descent principles while incorporating weight decay regularization to prevent overfitting.
258
 
259
+ 9. **Sequence Length**: The maximum number of tokens or words allowed in input sequences processed by the model, which impacts memory consumption and computation time during training and inference.
260
 
261
+ 10. **Cloud Provider**: The service provider responsible for hosting the computational resources used for training and deploying the model, including cloud computing platforms such as Amazon Web Services (AWS), Google Cloud Platform (GCP), or Microsoft Azure.
262
 
263
+ 11. **Carbon Emissions**: The total amount of greenhouse gas emissions, typically measured in grams of CO2 equivalents, generated as a result of running the model on computational hardware, taking into account factors such as energy consumption and infrastructure efficiency.
264
 
265
+ 12. **Throughput**: The rate at which the model processes input data or performs inference, typically measured in examples or tokens per second, and influenced by factors such as batch size, model complexity, and hardware specifications.