Added input and notebook and output folders with files
Browse files- .gitattributes +1 -0
- input/run_clm.py +667 -0
- notebook/GPT2_DrugsCom_DepressionReviews_FineTuning.ipynb +0 -0
- output/train_dataset.txt +3 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
output/train_dataset.txt filter=lfs diff=lfs merge=lfs -text
|
input/run_clm.py
ADDED
@@ -0,0 +1,667 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding=utf-8
|
3 |
+
# Copyright 2020 The HuggingFace Inc. team. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
"""
|
17 |
+
Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dataset.
|
18 |
+
|
19 |
+
Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
|
20 |
+
https://huggingface.co/models?filter=text-generation
|
21 |
+
"""
|
22 |
+
# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments.
|
23 |
+
|
24 |
+
import logging
|
25 |
+
import math
|
26 |
+
import os
|
27 |
+
import sys
|
28 |
+
import warnings
|
29 |
+
from dataclasses import dataclass, field
|
30 |
+
from itertools import chain
|
31 |
+
from typing import Optional
|
32 |
+
|
33 |
+
import datasets
|
34 |
+
import evaluate
|
35 |
+
import torch
|
36 |
+
from datasets import load_dataset
|
37 |
+
|
38 |
+
import transformers
|
39 |
+
from transformers import (
|
40 |
+
CONFIG_MAPPING,
|
41 |
+
MODEL_FOR_CAUSAL_LM_MAPPING,
|
42 |
+
AutoConfig,
|
43 |
+
AutoModelForCausalLM,
|
44 |
+
AutoTokenizer,
|
45 |
+
HfArgumentParser,
|
46 |
+
Trainer,
|
47 |
+
TrainingArguments,
|
48 |
+
default_data_collator,
|
49 |
+
is_torch_tpu_available,
|
50 |
+
set_seed,
|
51 |
+
)
|
52 |
+
from transformers.testing_utils import CaptureLogger
|
53 |
+
from transformers.trainer_utils import get_last_checkpoint
|
54 |
+
from transformers.utils import check_min_version, send_example_telemetry
|
55 |
+
from transformers.utils.versions import require_version
|
56 |
+
|
57 |
+
|
58 |
+
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
59 |
+
check_min_version("4.36.0.dev0")
|
60 |
+
|
61 |
+
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
|
62 |
+
|
63 |
+
logger = logging.getLogger(__name__)
|
64 |
+
|
65 |
+
|
66 |
+
MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys())
|
67 |
+
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
|
68 |
+
|
69 |
+
|
70 |
+
@dataclass
|
71 |
+
class ModelArguments:
|
72 |
+
"""
|
73 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
|
74 |
+
"""
|
75 |
+
|
76 |
+
model_name_or_path: Optional[str] = field(
|
77 |
+
default=None,
|
78 |
+
metadata={
|
79 |
+
"help": (
|
80 |
+
"The model checkpoint for weights initialization. Don't set if you want to train a model from scratch."
|
81 |
+
)
|
82 |
+
},
|
83 |
+
)
|
84 |
+
model_type: Optional[str] = field(
|
85 |
+
default=None,
|
86 |
+
metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
|
87 |
+
)
|
88 |
+
config_overrides: Optional[str] = field(
|
89 |
+
default=None,
|
90 |
+
metadata={
|
91 |
+
"help": (
|
92 |
+
"Override some existing default config settings when a model is trained from scratch. Example: "
|
93 |
+
"n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
|
94 |
+
)
|
95 |
+
},
|
96 |
+
)
|
97 |
+
config_name: Optional[str] = field(
|
98 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
99 |
+
)
|
100 |
+
tokenizer_name: Optional[str] = field(
|
101 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
102 |
+
)
|
103 |
+
cache_dir: Optional[str] = field(
|
104 |
+
default=None,
|
105 |
+
metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
|
106 |
+
)
|
107 |
+
use_fast_tokenizer: bool = field(
|
108 |
+
default=True,
|
109 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
110 |
+
)
|
111 |
+
model_revision: str = field(
|
112 |
+
default="main",
|
113 |
+
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
|
114 |
+
)
|
115 |
+
token: str = field(
|
116 |
+
default=None,
|
117 |
+
metadata={
|
118 |
+
"help": (
|
119 |
+
"The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
|
120 |
+
"generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
|
121 |
+
)
|
122 |
+
},
|
123 |
+
)
|
124 |
+
use_auth_token: bool = field(
|
125 |
+
default=None,
|
126 |
+
metadata={
|
127 |
+
"help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead."
|
128 |
+
},
|
129 |
+
)
|
130 |
+
trust_remote_code: bool = field(
|
131 |
+
default=False,
|
132 |
+
metadata={
|
133 |
+
"help": (
|
134 |
+
"Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
|
135 |
+
"should only be set to `True` for repositories you trust and in which you have read the code, as it will "
|
136 |
+
"execute code present on the Hub on your local machine."
|
137 |
+
)
|
138 |
+
},
|
139 |
+
)
|
140 |
+
torch_dtype: Optional[str] = field(
|
141 |
+
default=None,
|
142 |
+
metadata={
|
143 |
+
"help": (
|
144 |
+
"Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the "
|
145 |
+
"dtype will be automatically derived from the model's weights."
|
146 |
+
),
|
147 |
+
"choices": ["auto", "bfloat16", "float16", "float32"],
|
148 |
+
},
|
149 |
+
)
|
150 |
+
low_cpu_mem_usage: bool = field(
|
151 |
+
default=False,
|
152 |
+
metadata={
|
153 |
+
"help": (
|
154 |
+
"It is an option to create the model as an empty shell, then only materialize its parameters when the pretrained weights are loaded. "
|
155 |
+
"set True will benefit LLM loading time and RAM consumption."
|
156 |
+
)
|
157 |
+
},
|
158 |
+
)
|
159 |
+
|
160 |
+
def __post_init__(self):
|
161 |
+
if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):
|
162 |
+
raise ValueError(
|
163 |
+
"--config_overrides can't be used in combination with --config_name or --model_name_or_path"
|
164 |
+
)
|
165 |
+
|
166 |
+
|
167 |
+
@dataclass
|
168 |
+
class DataTrainingArguments:
|
169 |
+
"""
|
170 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
171 |
+
"""
|
172 |
+
|
173 |
+
dataset_name: Optional[str] = field(
|
174 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
175 |
+
)
|
176 |
+
dataset_config_name: Optional[str] = field(
|
177 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
178 |
+
)
|
179 |
+
train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
|
180 |
+
validation_file: Optional[str] = field(
|
181 |
+
default=None,
|
182 |
+
metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
|
183 |
+
)
|
184 |
+
max_train_samples: Optional[int] = field(
|
185 |
+
default=None,
|
186 |
+
metadata={
|
187 |
+
"help": (
|
188 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
189 |
+
"value if set."
|
190 |
+
)
|
191 |
+
},
|
192 |
+
)
|
193 |
+
max_eval_samples: Optional[int] = field(
|
194 |
+
default=None,
|
195 |
+
metadata={
|
196 |
+
"help": (
|
197 |
+
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
|
198 |
+
"value if set."
|
199 |
+
)
|
200 |
+
},
|
201 |
+
)
|
202 |
+
streaming: bool = field(default=False, metadata={"help": "Enable streaming mode"})
|
203 |
+
block_size: Optional[int] = field(
|
204 |
+
default=None,
|
205 |
+
metadata={
|
206 |
+
"help": (
|
207 |
+
"Optional input sequence length after tokenization. "
|
208 |
+
"The training dataset will be truncated in block of this size for training. "
|
209 |
+
"Default to the model max input length for single sentence inputs (take into account special tokens)."
|
210 |
+
)
|
211 |
+
},
|
212 |
+
)
|
213 |
+
overwrite_cache: bool = field(
|
214 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
215 |
+
)
|
216 |
+
validation_split_percentage: Optional[int] = field(
|
217 |
+
default=5,
|
218 |
+
metadata={
|
219 |
+
"help": "The percentage of the train set used as validation set in case there's no validation split"
|
220 |
+
},
|
221 |
+
)
|
222 |
+
preprocessing_num_workers: Optional[int] = field(
|
223 |
+
default=None,
|
224 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
225 |
+
)
|
226 |
+
keep_linebreaks: bool = field(
|
227 |
+
default=True, metadata={"help": "Whether to keep line breaks when using TXT files or not."}
|
228 |
+
)
|
229 |
+
|
230 |
+
def __post_init__(self):
|
231 |
+
if self.streaming:
|
232 |
+
require_version("datasets>=2.0.0", "The streaming feature requires `datasets>=2.0.0`")
|
233 |
+
|
234 |
+
if self.dataset_name is None and self.train_file is None and self.validation_file is None:
|
235 |
+
raise ValueError("Need either a dataset name or a training/validation file.")
|
236 |
+
else:
|
237 |
+
if self.train_file is not None:
|
238 |
+
extension = self.train_file.split(".")[-1]
|
239 |
+
assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
|
240 |
+
if self.validation_file is not None:
|
241 |
+
extension = self.validation_file.split(".")[-1]
|
242 |
+
assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
|
243 |
+
|
244 |
+
|
245 |
+
def main():
|
246 |
+
# See all possible arguments in src/transformers/training_args.py
|
247 |
+
# or by passing the --help flag to this script.
|
248 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
249 |
+
|
250 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
251 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
252 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
253 |
+
# let's parse it to get our arguments.
|
254 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
255 |
+
else:
|
256 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
257 |
+
|
258 |
+
if model_args.use_auth_token is not None:
|
259 |
+
warnings.warn(
|
260 |
+
"The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead.",
|
261 |
+
FutureWarning,
|
262 |
+
)
|
263 |
+
if model_args.token is not None:
|
264 |
+
raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
|
265 |
+
model_args.token = model_args.use_auth_token
|
266 |
+
|
267 |
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
|
268 |
+
# information sent is the one passed as arguments along with your Python/PyTorch versions.
|
269 |
+
send_example_telemetry("run_clm", model_args, data_args)
|
270 |
+
|
271 |
+
# Setup logging
|
272 |
+
logging.basicConfig(
|
273 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
274 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
275 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
276 |
+
)
|
277 |
+
|
278 |
+
if training_args.should_log:
|
279 |
+
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
|
280 |
+
transformers.utils.logging.set_verbosity_info()
|
281 |
+
|
282 |
+
log_level = training_args.get_process_log_level()
|
283 |
+
logger.setLevel(log_level)
|
284 |
+
datasets.utils.logging.set_verbosity(log_level)
|
285 |
+
transformers.utils.logging.set_verbosity(log_level)
|
286 |
+
transformers.utils.logging.enable_default_handler()
|
287 |
+
transformers.utils.logging.enable_explicit_format()
|
288 |
+
|
289 |
+
# Log on each process the small summary:
|
290 |
+
logger.warning(
|
291 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, "
|
292 |
+
+ f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
|
293 |
+
)
|
294 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
295 |
+
|
296 |
+
# Detecting last checkpoint.
|
297 |
+
last_checkpoint = None
|
298 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
299 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
300 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
301 |
+
raise ValueError(
|
302 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
303 |
+
"Use --overwrite_output_dir to overcome."
|
304 |
+
)
|
305 |
+
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
|
306 |
+
logger.info(
|
307 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
308 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
309 |
+
)
|
310 |
+
|
311 |
+
# Set seed before initializing model.
|
312 |
+
set_seed(training_args.seed)
|
313 |
+
|
314 |
+
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
|
315 |
+
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
|
316 |
+
# (the dataset will be downloaded automatically from the datasets Hub).
|
317 |
+
#
|
318 |
+
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
|
319 |
+
# 'text' is found. You can easily tweak this behavior (see below).
|
320 |
+
#
|
321 |
+
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
|
322 |
+
# download the dataset.
|
323 |
+
if data_args.dataset_name is not None:
|
324 |
+
# Downloading and loading a dataset from the hub.
|
325 |
+
raw_datasets = load_dataset(
|
326 |
+
data_args.dataset_name,
|
327 |
+
data_args.dataset_config_name,
|
328 |
+
cache_dir=model_args.cache_dir,
|
329 |
+
token=model_args.token,
|
330 |
+
streaming=data_args.streaming,
|
331 |
+
)
|
332 |
+
if "validation" not in raw_datasets.keys():
|
333 |
+
raw_datasets["validation"] = load_dataset(
|
334 |
+
data_args.dataset_name,
|
335 |
+
data_args.dataset_config_name,
|
336 |
+
split=f"train[:{data_args.validation_split_percentage}%]",
|
337 |
+
cache_dir=model_args.cache_dir,
|
338 |
+
token=model_args.token,
|
339 |
+
streaming=data_args.streaming,
|
340 |
+
)
|
341 |
+
raw_datasets["train"] = load_dataset(
|
342 |
+
data_args.dataset_name,
|
343 |
+
data_args.dataset_config_name,
|
344 |
+
split=f"train[{data_args.validation_split_percentage}%:]",
|
345 |
+
cache_dir=model_args.cache_dir,
|
346 |
+
token=model_args.token,
|
347 |
+
streaming=data_args.streaming,
|
348 |
+
)
|
349 |
+
else:
|
350 |
+
data_files = {}
|
351 |
+
dataset_args = {}
|
352 |
+
if data_args.train_file is not None:
|
353 |
+
data_files["train"] = data_args.train_file
|
354 |
+
if data_args.validation_file is not None:
|
355 |
+
data_files["validation"] = data_args.validation_file
|
356 |
+
extension = (
|
357 |
+
data_args.train_file.split(".")[-1]
|
358 |
+
if data_args.train_file is not None
|
359 |
+
else data_args.validation_file.split(".")[-1]
|
360 |
+
)
|
361 |
+
if extension == "txt":
|
362 |
+
extension = "text"
|
363 |
+
dataset_args["keep_linebreaks"] = data_args.keep_linebreaks
|
364 |
+
raw_datasets = load_dataset(
|
365 |
+
extension,
|
366 |
+
data_files=data_files,
|
367 |
+
cache_dir=model_args.cache_dir,
|
368 |
+
token=model_args.token,
|
369 |
+
**dataset_args,
|
370 |
+
)
|
371 |
+
# If no validation data is there, validation_split_percentage will be used to divide the dataset.
|
372 |
+
if "validation" not in raw_datasets.keys():
|
373 |
+
raw_datasets["validation"] = load_dataset(
|
374 |
+
extension,
|
375 |
+
data_files=data_files,
|
376 |
+
split=f"train[:{data_args.validation_split_percentage}%]",
|
377 |
+
cache_dir=model_args.cache_dir,
|
378 |
+
token=model_args.token,
|
379 |
+
**dataset_args,
|
380 |
+
)
|
381 |
+
raw_datasets["train"] = load_dataset(
|
382 |
+
extension,
|
383 |
+
data_files=data_files,
|
384 |
+
split=f"train[{data_args.validation_split_percentage}%:]",
|
385 |
+
cache_dir=model_args.cache_dir,
|
386 |
+
token=model_args.token,
|
387 |
+
**dataset_args,
|
388 |
+
)
|
389 |
+
|
390 |
+
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
|
391 |
+
# https://huggingface.co/docs/datasets/loading_datasets.
|
392 |
+
|
393 |
+
# Load pretrained model and tokenizer
|
394 |
+
#
|
395 |
+
# Distributed training:
|
396 |
+
# The .from_pretrained methods guarantee that only one local process can concurrently
|
397 |
+
# download model & vocab.
|
398 |
+
|
399 |
+
config_kwargs = {
|
400 |
+
"cache_dir": model_args.cache_dir,
|
401 |
+
"revision": model_args.model_revision,
|
402 |
+
"token": model_args.token,
|
403 |
+
"trust_remote_code": model_args.trust_remote_code,
|
404 |
+
}
|
405 |
+
if model_args.config_name:
|
406 |
+
config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs)
|
407 |
+
elif model_args.model_name_or_path:
|
408 |
+
config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs)
|
409 |
+
else:
|
410 |
+
config = CONFIG_MAPPING[model_args.model_type]()
|
411 |
+
logger.warning("You are instantiating a new config instance from scratch.")
|
412 |
+
if model_args.config_overrides is not None:
|
413 |
+
logger.info(f"Overriding config: {model_args.config_overrides}")
|
414 |
+
config.update_from_string(model_args.config_overrides)
|
415 |
+
logger.info(f"New config: {config}")
|
416 |
+
|
417 |
+
tokenizer_kwargs = {
|
418 |
+
"cache_dir": model_args.cache_dir,
|
419 |
+
"use_fast": model_args.use_fast_tokenizer,
|
420 |
+
"revision": model_args.model_revision,
|
421 |
+
"token": model_args.token,
|
422 |
+
"trust_remote_code": model_args.trust_remote_code,
|
423 |
+
}
|
424 |
+
if model_args.tokenizer_name:
|
425 |
+
tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs)
|
426 |
+
elif model_args.model_name_or_path:
|
427 |
+
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs)
|
428 |
+
else:
|
429 |
+
raise ValueError(
|
430 |
+
"You are instantiating a new tokenizer from scratch. This is not supported by this script. "
|
431 |
+
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
|
432 |
+
)
|
433 |
+
|
434 |
+
if model_args.model_name_or_path:
|
435 |
+
torch_dtype = (
|
436 |
+
model_args.torch_dtype
|
437 |
+
if model_args.torch_dtype in ["auto", None]
|
438 |
+
else getattr(torch, model_args.torch_dtype)
|
439 |
+
)
|
440 |
+
model = AutoModelForCausalLM.from_pretrained(
|
441 |
+
model_args.model_name_or_path,
|
442 |
+
from_tf=bool(".ckpt" in model_args.model_name_or_path),
|
443 |
+
config=config,
|
444 |
+
cache_dir=model_args.cache_dir,
|
445 |
+
revision=model_args.model_revision,
|
446 |
+
token=model_args.token,
|
447 |
+
trust_remote_code=model_args.trust_remote_code,
|
448 |
+
torch_dtype=torch_dtype,
|
449 |
+
low_cpu_mem_usage=model_args.low_cpu_mem_usage,
|
450 |
+
)
|
451 |
+
else:
|
452 |
+
model = AutoModelForCausalLM.from_config(config, trust_remote_code=model_args.trust_remote_code)
|
453 |
+
n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values())
|
454 |
+
logger.info(f"Training new model from scratch - Total size={n_params/2**20:.2f}M params")
|
455 |
+
|
456 |
+
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
|
457 |
+
# on a small vocab and want a smaller embedding size, remove this test.
|
458 |
+
embedding_size = model.get_input_embeddings().weight.shape[0]
|
459 |
+
if len(tokenizer) > embedding_size:
|
460 |
+
model.resize_token_embeddings(len(tokenizer))
|
461 |
+
|
462 |
+
# Preprocessing the datasets.
|
463 |
+
# First we tokenize all the texts.
|
464 |
+
if training_args.do_train:
|
465 |
+
column_names = list(raw_datasets["train"].features)
|
466 |
+
else:
|
467 |
+
column_names = list(raw_datasets["validation"].features)
|
468 |
+
text_column_name = "text" if "text" in column_names else column_names[0]
|
469 |
+
|
470 |
+
# since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function
|
471 |
+
tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base")
|
472 |
+
|
473 |
+
def tokenize_function(examples):
|
474 |
+
with CaptureLogger(tok_logger) as cl:
|
475 |
+
output = tokenizer(examples[text_column_name])
|
476 |
+
# clm input could be much much longer than block_size
|
477 |
+
if "Token indices sequence length is longer than the" in cl.out:
|
478 |
+
tok_logger.warning(
|
479 |
+
"^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits"
|
480 |
+
" before being passed to the model."
|
481 |
+
)
|
482 |
+
return output
|
483 |
+
|
484 |
+
with training_args.main_process_first(desc="dataset map tokenization"):
|
485 |
+
if not data_args.streaming:
|
486 |
+
tokenized_datasets = raw_datasets.map(
|
487 |
+
tokenize_function,
|
488 |
+
batched=True,
|
489 |
+
num_proc=data_args.preprocessing_num_workers,
|
490 |
+
remove_columns=column_names,
|
491 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
492 |
+
desc="Running tokenizer on dataset",
|
493 |
+
)
|
494 |
+
else:
|
495 |
+
tokenized_datasets = raw_datasets.map(
|
496 |
+
tokenize_function,
|
497 |
+
batched=True,
|
498 |
+
remove_columns=column_names,
|
499 |
+
)
|
500 |
+
if hasattr(config, "max_position_embeddings"):
|
501 |
+
max_pos_embeddings = config.max_position_embeddings
|
502 |
+
else:
|
503 |
+
# Define a default value if the attribute is missing in the config.
|
504 |
+
max_pos_embeddings = 1024
|
505 |
+
|
506 |
+
if data_args.block_size is None:
|
507 |
+
block_size = tokenizer.model_max_length
|
508 |
+
if block_size > max_pos_embeddings:
|
509 |
+
logger.warning(
|
510 |
+
f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
|
511 |
+
f"Using block_size={min(1024, max_pos_embeddings)} instead. You can change that default value by passing --block_size xxx."
|
512 |
+
)
|
513 |
+
block_size = min(1024, max_pos_embeddings)
|
514 |
+
else:
|
515 |
+
if data_args.block_size > tokenizer.model_max_length:
|
516 |
+
logger.warning(
|
517 |
+
f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model "
|
518 |
+
f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
|
519 |
+
)
|
520 |
+
block_size = min(data_args.block_size, tokenizer.model_max_length)
|
521 |
+
|
522 |
+
# Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
|
523 |
+
def group_texts(examples):
|
524 |
+
# Concatenate all texts.
|
525 |
+
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
|
526 |
+
total_length = len(concatenated_examples[list(examples.keys())[0]])
|
527 |
+
# We drop the small remainder, and if the total_length < block_size we exclude this batch and return an empty dict.
|
528 |
+
# We could add padding if the model supported it instead of this drop, you can customize this part to your needs.
|
529 |
+
total_length = (total_length // block_size) * block_size
|
530 |
+
# Split by chunks of max_len.
|
531 |
+
result = {
|
532 |
+
k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
|
533 |
+
for k, t in concatenated_examples.items()
|
534 |
+
}
|
535 |
+
result["labels"] = result["input_ids"].copy()
|
536 |
+
return result
|
537 |
+
|
538 |
+
# Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
|
539 |
+
# for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
|
540 |
+
# to preprocess.
|
541 |
+
#
|
542 |
+
# To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
|
543 |
+
# https://huggingface.co/docs/datasets/process#map
|
544 |
+
|
545 |
+
with training_args.main_process_first(desc="grouping texts together"):
|
546 |
+
if not data_args.streaming:
|
547 |
+
lm_datasets = tokenized_datasets.map(
|
548 |
+
group_texts,
|
549 |
+
batched=True,
|
550 |
+
num_proc=data_args.preprocessing_num_workers,
|
551 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
552 |
+
desc=f"Grouping texts in chunks of {block_size}",
|
553 |
+
)
|
554 |
+
else:
|
555 |
+
lm_datasets = tokenized_datasets.map(
|
556 |
+
group_texts,
|
557 |
+
batched=True,
|
558 |
+
)
|
559 |
+
|
560 |
+
if training_args.do_train:
|
561 |
+
if "train" not in tokenized_datasets:
|
562 |
+
raise ValueError("--do_train requires a train dataset")
|
563 |
+
train_dataset = lm_datasets["train"]
|
564 |
+
if data_args.max_train_samples is not None:
|
565 |
+
max_train_samples = min(len(train_dataset), data_args.max_train_samples)
|
566 |
+
train_dataset = train_dataset.select(range(max_train_samples))
|
567 |
+
|
568 |
+
if training_args.do_eval:
|
569 |
+
if "validation" not in tokenized_datasets:
|
570 |
+
raise ValueError("--do_eval requires a validation dataset")
|
571 |
+
eval_dataset = lm_datasets["validation"]
|
572 |
+
if data_args.max_eval_samples is not None:
|
573 |
+
max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
|
574 |
+
eval_dataset = eval_dataset.select(range(max_eval_samples))
|
575 |
+
|
576 |
+
def preprocess_logits_for_metrics(logits, labels):
|
577 |
+
if isinstance(logits, tuple):
|
578 |
+
# Depending on the model and config, logits may contain extra tensors,
|
579 |
+
# like past_key_values, but logits always come first
|
580 |
+
logits = logits[0]
|
581 |
+
return logits.argmax(dim=-1)
|
582 |
+
|
583 |
+
metric = evaluate.load("accuracy")
|
584 |
+
|
585 |
+
def compute_metrics(eval_preds):
|
586 |
+
preds, labels = eval_preds
|
587 |
+
# preds have the same shape as the labels, after the argmax(-1) has been calculated
|
588 |
+
# by preprocess_logits_for_metrics but we need to shift the labels
|
589 |
+
labels = labels[:, 1:].reshape(-1)
|
590 |
+
preds = preds[:, :-1].reshape(-1)
|
591 |
+
return metric.compute(predictions=preds, references=labels)
|
592 |
+
|
593 |
+
# Initialize our Trainer
|
594 |
+
trainer = Trainer(
|
595 |
+
model=model,
|
596 |
+
args=training_args,
|
597 |
+
train_dataset=train_dataset if training_args.do_train else None,
|
598 |
+
eval_dataset=eval_dataset if training_args.do_eval else None,
|
599 |
+
tokenizer=tokenizer,
|
600 |
+
# Data collator will default to DataCollatorWithPadding, so we change it.
|
601 |
+
data_collator=default_data_collator,
|
602 |
+
compute_metrics=compute_metrics if training_args.do_eval and not is_torch_tpu_available() else None,
|
603 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics
|
604 |
+
if training_args.do_eval and not is_torch_tpu_available()
|
605 |
+
else None,
|
606 |
+
)
|
607 |
+
|
608 |
+
# Training
|
609 |
+
if training_args.do_train:
|
610 |
+
checkpoint = None
|
611 |
+
if training_args.resume_from_checkpoint is not None:
|
612 |
+
checkpoint = training_args.resume_from_checkpoint
|
613 |
+
elif last_checkpoint is not None:
|
614 |
+
checkpoint = last_checkpoint
|
615 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
616 |
+
trainer.save_model() # Saves the tokenizer too for easy upload
|
617 |
+
|
618 |
+
metrics = train_result.metrics
|
619 |
+
|
620 |
+
max_train_samples = (
|
621 |
+
data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
|
622 |
+
)
|
623 |
+
metrics["train_samples"] = min(max_train_samples, len(train_dataset))
|
624 |
+
|
625 |
+
trainer.log_metrics("train", metrics)
|
626 |
+
trainer.save_metrics("train", metrics)
|
627 |
+
trainer.save_state()
|
628 |
+
|
629 |
+
# Evaluation
|
630 |
+
if training_args.do_eval:
|
631 |
+
logger.info("*** Evaluate ***")
|
632 |
+
|
633 |
+
metrics = trainer.evaluate()
|
634 |
+
|
635 |
+
max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
|
636 |
+
metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
|
637 |
+
try:
|
638 |
+
perplexity = math.exp(metrics["eval_loss"])
|
639 |
+
except OverflowError:
|
640 |
+
perplexity = float("inf")
|
641 |
+
metrics["perplexity"] = perplexity
|
642 |
+
|
643 |
+
trainer.log_metrics("eval", metrics)
|
644 |
+
trainer.save_metrics("eval", metrics)
|
645 |
+
|
646 |
+
kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"}
|
647 |
+
if data_args.dataset_name is not None:
|
648 |
+
kwargs["dataset_tags"] = data_args.dataset_name
|
649 |
+
if data_args.dataset_config_name is not None:
|
650 |
+
kwargs["dataset_args"] = data_args.dataset_config_name
|
651 |
+
kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
|
652 |
+
else:
|
653 |
+
kwargs["dataset"] = data_args.dataset_name
|
654 |
+
|
655 |
+
if training_args.push_to_hub:
|
656 |
+
trainer.push_to_hub(**kwargs)
|
657 |
+
else:
|
658 |
+
trainer.create_model_card(**kwargs)
|
659 |
+
|
660 |
+
|
661 |
+
def _mp_fn(index):
|
662 |
+
# For xla_spawn (TPUs)
|
663 |
+
main()
|
664 |
+
|
665 |
+
|
666 |
+
if __name__ == "__main__":
|
667 |
+
main()
|
notebook/GPT2_DrugsCom_DepressionReviews_FineTuning.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
output/train_dataset.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bb3aeef76ca1ca9e4ef227e5b78a6b9605242638451f5e3eea7e33f5864b2dd4
|
3 |
+
size 51728323
|