transformers
670 строк · 28.2 Кб
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"""
17Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dataset.
18
19Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
20https://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
24import logging
25import math
26import os
27import sys
28import warnings
29from dataclasses import dataclass, field
30from itertools import chain
31from typing import Optional
32
33import datasets
34import evaluate
35import torch
36from datasets import load_dataset
37
38import transformers
39from transformers import (
40CONFIG_MAPPING,
41MODEL_FOR_CAUSAL_LM_MAPPING,
42AutoConfig,
43AutoModelForCausalLM,
44AutoTokenizer,
45HfArgumentParser,
46Trainer,
47TrainingArguments,
48default_data_collator,
49is_torch_tpu_available,
50set_seed,
51)
52from transformers.testing_utils import CaptureLogger
53from transformers.trainer_utils import get_last_checkpoint
54from transformers.utils import check_min_version, send_example_telemetry
55from 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.
59check_min_version("4.39.0.dev0")
60
61require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
62
63logger = logging.getLogger(__name__)
64
65
66MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys())
67MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
68
69
70@dataclass
71class ModelArguments:
72"""
73Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
74"""
75
76model_name_or_path: Optional[str] = field(
77default=None,
78metadata={
79"help": (
80"The model checkpoint for weights initialization. Don't set if you want to train a model from scratch."
81)
82},
83)
84model_type: Optional[str] = field(
85default=None,
86metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
87)
88config_overrides: Optional[str] = field(
89default=None,
90metadata={
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)
97config_name: Optional[str] = field(
98default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
99)
100tokenizer_name: Optional[str] = field(
101default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
102)
103cache_dir: Optional[str] = field(
104default=None,
105metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
106)
107use_fast_tokenizer: bool = field(
108default=True,
109metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
110)
111model_revision: str = field(
112default="main",
113metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
114)
115token: str = field(
116default=None,
117metadata={
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)
124use_auth_token: bool = field(
125default=None,
126metadata={
127"help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead."
128},
129)
130trust_remote_code: bool = field(
131default=False,
132metadata={
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)
140torch_dtype: Optional[str] = field(
141default=None,
142metadata={
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)
150low_cpu_mem_usage: bool = field(
151default=False,
152metadata={
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
160def __post_init__(self):
161if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):
162raise ValueError(
163"--config_overrides can't be used in combination with --config_name or --model_name_or_path"
164)
165
166
167@dataclass
168class DataTrainingArguments:
169"""
170Arguments pertaining to what data we are going to input our model for training and eval.
171"""
172
173dataset_name: Optional[str] = field(
174default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
175)
176dataset_config_name: Optional[str] = field(
177default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
178)
179train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
180validation_file: Optional[str] = field(
181default=None,
182metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
183)
184max_train_samples: Optional[int] = field(
185default=None,
186metadata={
187"help": (
188"For debugging purposes or quicker training, truncate the number of training examples to this "
189"value if set."
190)
191},
192)
193max_eval_samples: Optional[int] = field(
194default=None,
195metadata={
196"help": (
197"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
198"value if set."
199)
200},
201)
202streaming: bool = field(default=False, metadata={"help": "Enable streaming mode"})
203block_size: Optional[int] = field(
204default=None,
205metadata={
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)
213overwrite_cache: bool = field(
214default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
215)
216validation_split_percentage: Optional[int] = field(
217default=5,
218metadata={
219"help": "The percentage of the train set used as validation set in case there's no validation split"
220},
221)
222preprocessing_num_workers: Optional[int] = field(
223default=None,
224metadata={"help": "The number of processes to use for the preprocessing."},
225)
226keep_linebreaks: bool = field(
227default=True, metadata={"help": "Whether to keep line breaks when using TXT files or not."}
228)
229
230def __post_init__(self):
231if self.streaming:
232require_version("datasets>=2.0.0", "The streaming feature requires `datasets>=2.0.0`")
233
234if self.dataset_name is None and self.train_file is None and self.validation_file is None:
235raise ValueError("Need either a dataset name or a training/validation file.")
236else:
237if self.train_file is not None:
238extension = self.train_file.split(".")[-1]
239assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
240if self.validation_file is not None:
241extension = self.validation_file.split(".")[-1]
242assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
243
244
245def 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
250parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
251if 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.
254model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
255else:
256model_args, data_args, training_args = parser.parse_args_into_dataclasses()
257
258if model_args.use_auth_token is not None:
259warnings.warn(
260"The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead.",
261FutureWarning,
262)
263if model_args.token is not None:
264raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
265model_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.
269send_example_telemetry("run_clm", model_args, data_args)
270
271# Setup logging
272logging.basicConfig(
273format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
274datefmt="%m/%d/%Y %H:%M:%S",
275handlers=[logging.StreamHandler(sys.stdout)],
276)
277
278if 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.
280transformers.utils.logging.set_verbosity_info()
281
282log_level = training_args.get_process_log_level()
283logger.setLevel(log_level)
284datasets.utils.logging.set_verbosity(log_level)
285transformers.utils.logging.set_verbosity(log_level)
286transformers.utils.logging.enable_default_handler()
287transformers.utils.logging.enable_explicit_format()
288
289# Log on each process the small summary:
290logger.warning(
291f"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)
294logger.info(f"Training/evaluation parameters {training_args}")
295
296# Detecting last checkpoint.
297last_checkpoint = None
298if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
299last_checkpoint = get_last_checkpoint(training_args.output_dir)
300if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
301raise ValueError(
302f"Output directory ({training_args.output_dir}) already exists and is not empty. "
303"Use --overwrite_output_dir to overcome."
304)
305elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
306logger.info(
307f"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.
312set_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.
323if data_args.dataset_name is not None:
324# Downloading and loading a dataset from the hub.
325raw_datasets = load_dataset(
326data_args.dataset_name,
327data_args.dataset_config_name,
328cache_dir=model_args.cache_dir,
329token=model_args.token,
330streaming=data_args.streaming,
331)
332if "validation" not in raw_datasets.keys():
333raw_datasets["validation"] = load_dataset(
334data_args.dataset_name,
335data_args.dataset_config_name,
336split=f"train[:{data_args.validation_split_percentage}%]",
337cache_dir=model_args.cache_dir,
338token=model_args.token,
339streaming=data_args.streaming,
340)
341raw_datasets["train"] = load_dataset(
342data_args.dataset_name,
343data_args.dataset_config_name,
344split=f"train[{data_args.validation_split_percentage}%:]",
345cache_dir=model_args.cache_dir,
346token=model_args.token,
347streaming=data_args.streaming,
348)
349else:
350data_files = {}
351dataset_args = {}
352if data_args.train_file is not None:
353data_files["train"] = data_args.train_file
354if data_args.validation_file is not None:
355data_files["validation"] = data_args.validation_file
356extension = (
357data_args.train_file.split(".")[-1]
358if data_args.train_file is not None
359else data_args.validation_file.split(".")[-1]
360)
361if extension == "txt":
362extension = "text"
363dataset_args["keep_linebreaks"] = data_args.keep_linebreaks
364raw_datasets = load_dataset(
365extension,
366data_files=data_files,
367cache_dir=model_args.cache_dir,
368token=model_args.token,
369**dataset_args,
370)
371# If no validation data is there, validation_split_percentage will be used to divide the dataset.
372if "validation" not in raw_datasets.keys():
373raw_datasets["validation"] = load_dataset(
374extension,
375data_files=data_files,
376split=f"train[:{data_args.validation_split_percentage}%]",
377cache_dir=model_args.cache_dir,
378token=model_args.token,
379**dataset_args,
380)
381raw_datasets["train"] = load_dataset(
382extension,
383data_files=data_files,
384split=f"train[{data_args.validation_split_percentage}%:]",
385cache_dir=model_args.cache_dir,
386token=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
399config_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}
405if model_args.config_name:
406config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs)
407elif model_args.model_name_or_path:
408config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs)
409else:
410config = CONFIG_MAPPING[model_args.model_type]()
411logger.warning("You are instantiating a new config instance from scratch.")
412if model_args.config_overrides is not None:
413logger.info(f"Overriding config: {model_args.config_overrides}")
414config.update_from_string(model_args.config_overrides)
415logger.info(f"New config: {config}")
416
417tokenizer_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}
424if model_args.tokenizer_name:
425tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs)
426elif model_args.model_name_or_path:
427tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs)
428else:
429raise 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
434if model_args.model_name_or_path:
435torch_dtype = (
436model_args.torch_dtype
437if model_args.torch_dtype in ["auto", None]
438else getattr(torch, model_args.torch_dtype)
439)
440model = AutoModelForCausalLM.from_pretrained(
441model_args.model_name_or_path,
442from_tf=bool(".ckpt" in model_args.model_name_or_path),
443config=config,
444cache_dir=model_args.cache_dir,
445revision=model_args.model_revision,
446token=model_args.token,
447trust_remote_code=model_args.trust_remote_code,
448torch_dtype=torch_dtype,
449low_cpu_mem_usage=model_args.low_cpu_mem_usage,
450)
451else:
452model = AutoModelForCausalLM.from_config(config, trust_remote_code=model_args.trust_remote_code)
453n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values())
454logger.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.
458embedding_size = model.get_input_embeddings().weight.shape[0]
459if len(tokenizer) > embedding_size:
460model.resize_token_embeddings(len(tokenizer))
461
462# Preprocessing the datasets.
463# First we tokenize all the texts.
464if training_args.do_train:
465column_names = list(raw_datasets["train"].features)
466else:
467column_names = list(raw_datasets["validation"].features)
468text_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
471tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base")
472
473def tokenize_function(examples):
474with CaptureLogger(tok_logger) as cl:
475output = tokenizer(examples[text_column_name])
476# clm input could be much much longer than block_size
477if "Token indices sequence length is longer than the" in cl.out:
478tok_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)
482return output
483
484with training_args.main_process_first(desc="dataset map tokenization"):
485if not data_args.streaming:
486tokenized_datasets = raw_datasets.map(
487tokenize_function,
488batched=True,
489num_proc=data_args.preprocessing_num_workers,
490remove_columns=column_names,
491load_from_cache_file=not data_args.overwrite_cache,
492desc="Running tokenizer on dataset",
493)
494else:
495tokenized_datasets = raw_datasets.map(
496tokenize_function,
497batched=True,
498remove_columns=column_names,
499)
500if hasattr(config, "max_position_embeddings"):
501max_pos_embeddings = config.max_position_embeddings
502else:
503# Define a default value if the attribute is missing in the config.
504max_pos_embeddings = 1024
505
506if data_args.block_size is None:
507block_size = tokenizer.model_max_length
508if block_size > max_pos_embeddings:
509logger.warning(
510f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
511f"Using block_size={min(1024, max_pos_embeddings)} instead. You can change that default value by passing --block_size xxx."
512)
513if max_pos_embeddings > 0:
514block_size = min(1024, max_pos_embeddings)
515else:
516block_size = 1024
517else:
518if data_args.block_size > tokenizer.model_max_length:
519logger.warning(
520f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model "
521f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
522)
523block_size = min(data_args.block_size, tokenizer.model_max_length)
524
525# Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
526def group_texts(examples):
527# Concatenate all texts.
528concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
529total_length = len(concatenated_examples[list(examples.keys())[0]])
530# We drop the small remainder, and if the total_length < block_size we exclude this batch and return an empty dict.
531# We could add padding if the model supported it instead of this drop, you can customize this part to your needs.
532total_length = (total_length // block_size) * block_size
533# Split by chunks of max_len.
534result = {
535k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
536for k, t in concatenated_examples.items()
537}
538result["labels"] = result["input_ids"].copy()
539return result
540
541# Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
542# for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
543# to preprocess.
544#
545# To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
546# https://huggingface.co/docs/datasets/process#map
547
548with training_args.main_process_first(desc="grouping texts together"):
549if not data_args.streaming:
550lm_datasets = tokenized_datasets.map(
551group_texts,
552batched=True,
553num_proc=data_args.preprocessing_num_workers,
554load_from_cache_file=not data_args.overwrite_cache,
555desc=f"Grouping texts in chunks of {block_size}",
556)
557else:
558lm_datasets = tokenized_datasets.map(
559group_texts,
560batched=True,
561)
562
563if training_args.do_train:
564if "train" not in tokenized_datasets:
565raise ValueError("--do_train requires a train dataset")
566train_dataset = lm_datasets["train"]
567if data_args.max_train_samples is not None:
568max_train_samples = min(len(train_dataset), data_args.max_train_samples)
569train_dataset = train_dataset.select(range(max_train_samples))
570
571if training_args.do_eval:
572if "validation" not in tokenized_datasets:
573raise ValueError("--do_eval requires a validation dataset")
574eval_dataset = lm_datasets["validation"]
575if data_args.max_eval_samples is not None:
576max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
577eval_dataset = eval_dataset.select(range(max_eval_samples))
578
579def preprocess_logits_for_metrics(logits, labels):
580if isinstance(logits, tuple):
581# Depending on the model and config, logits may contain extra tensors,
582# like past_key_values, but logits always come first
583logits = logits[0]
584return logits.argmax(dim=-1)
585
586metric = evaluate.load("accuracy", cache_dir=model_args.cache_dir)
587
588def compute_metrics(eval_preds):
589preds, labels = eval_preds
590# preds have the same shape as the labels, after the argmax(-1) has been calculated
591# by preprocess_logits_for_metrics but we need to shift the labels
592labels = labels[:, 1:].reshape(-1)
593preds = preds[:, :-1].reshape(-1)
594return metric.compute(predictions=preds, references=labels)
595
596# Initialize our Trainer
597trainer = Trainer(
598model=model,
599args=training_args,
600train_dataset=train_dataset if training_args.do_train else None,
601eval_dataset=eval_dataset if training_args.do_eval else None,
602tokenizer=tokenizer,
603# Data collator will default to DataCollatorWithPadding, so we change it.
604data_collator=default_data_collator,
605compute_metrics=compute_metrics if training_args.do_eval and not is_torch_tpu_available() else None,
606preprocess_logits_for_metrics=preprocess_logits_for_metrics
607if training_args.do_eval and not is_torch_tpu_available()
608else None,
609)
610
611# Training
612if training_args.do_train:
613checkpoint = None
614if training_args.resume_from_checkpoint is not None:
615checkpoint = training_args.resume_from_checkpoint
616elif last_checkpoint is not None:
617checkpoint = last_checkpoint
618train_result = trainer.train(resume_from_checkpoint=checkpoint)
619trainer.save_model() # Saves the tokenizer too for easy upload
620
621metrics = train_result.metrics
622
623max_train_samples = (
624data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
625)
626metrics["train_samples"] = min(max_train_samples, len(train_dataset))
627
628trainer.log_metrics("train", metrics)
629trainer.save_metrics("train", metrics)
630trainer.save_state()
631
632# Evaluation
633if training_args.do_eval:
634logger.info("*** Evaluate ***")
635
636metrics = trainer.evaluate()
637
638max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
639metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
640try:
641perplexity = math.exp(metrics["eval_loss"])
642except OverflowError:
643perplexity = float("inf")
644metrics["perplexity"] = perplexity
645
646trainer.log_metrics("eval", metrics)
647trainer.save_metrics("eval", metrics)
648
649kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"}
650if data_args.dataset_name is not None:
651kwargs["dataset_tags"] = data_args.dataset_name
652if data_args.dataset_config_name is not None:
653kwargs["dataset_args"] = data_args.dataset_config_name
654kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
655else:
656kwargs["dataset"] = data_args.dataset_name
657
658if training_args.push_to_hub:
659trainer.push_to_hub(**kwargs)
660else:
661trainer.create_model_card(**kwargs)
662
663
664def _mp_fn(index):
665# For xla_spawn (TPUs)
666main()
667
668
669if __name__ == "__main__":
670main()
671