code: def main():
      # See all possible arguments in src/transformers/training_args.py
      # or by passing the --help flag to this script.
      # We now keep distinct sets of args, for a cleaner separation of concerns.
  
      parser = HfArgumentParser(
          (ModelArguments, DataTrainingArguments, TrainingArguments)
      )
      (
          model_args,
          data_args,
          training_args,
      ) = parser.parse_args_into_dataclasses()
  
      # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
      # information sent is the one passed as arguments along with your Python/PyTorch versions.
      send_example_telemetry("run_xnli", model_args)
  
      # Setup logging
      logging.basicConfig(
          format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
          datefmt="%m/%d/%Y %H:%M:%S",
          handlers=[logging.StreamHandler(sys.stdout)],
      )
  
      log_level = training_args.get_process_log_level()
      logger.setLevel(log_level)
      datasets.utils.logging.set_verbosity(log_level)
      transformers.utils.logging.set_verbosity(log_level)
      transformers.utils.logging.enable_default_handler()
      transformers.utils.logging.enable_explicit_format()
  
      # Log on each process the small summary:
      logger.warning(
          f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
          + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
      )
      logger.info(f"Training/evaluation parameters {training_args}")
  
      # Detecting last checkpoint.
      last_checkpoint = None
      if (
          os.path.isdir(training_args.output_dir)
          and training_args.do_train
          and not training_args.overwrite_output_dir
      ):
          last_checkpoint = get_last_checkpoint(
              training_args.output_dir
          )
          if (
              last_checkpoint is None
              and len(os.listdir(training_args.output_dir)) > 0
          ):
              raise ValueError(
                  f"Output directory ({training_args.output_dir}) already exists and is not empty. "
                  "Use --overwrite_output_dir to overcome."
              )
          elif last_checkpoint is not None:
              logger.info(
                  f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
                  "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
              )
  
      # Set seed before initializing model.
      set_seed(training_args.seed)
  
      # In distributed training, the load_dataset function guarantees that only one local process can concurrently
      # download the dataset.
      # Downloading and loading xnli dataset from the hub.
      if training_args.do_train:
          if model_args.train_language is None:
              train_dataset = load_dataset(
                  "xnli",
                  model_args.language,
                  split="train",
                  cache_dir=model_args.cache_dir,
                  use_auth_token=True
                  if model_args.use_auth_token
                  else None,
              )
          else:
              train_dataset = load_dataset(
                  "xnli",
                  model_args.train_language,
                  split="train",
                  cache_dir=model_args.cache_dir,
                  use_auth_token=True
                  if model_args.use_auth_token
                  else None,
              )
          label_list = train_dataset.features["label"].names
  
      if training_args.do_eval:
          eval_dataset = load_dataset(
              "xnli",
              model_args.language,
              split="validation",
              cache_dir=model_args.cache_dir,
              use_auth_token=True
              if model_args.use_auth_token
              else None,
          )
          label_list = eval_dataset.features["label"].names
  
      if training_args.do_predict:
          predict_dataset = load_dataset(
              "xnli",
              model_args.language,
              split="test",
              cache_dir=model_args.cache_dir,
              use_auth_token=True
              if model_args.use_auth_token
              else None,
          )
          label_list = predict_dataset.features["label"].names
  
      # Labels
      num_labels = len(label_list)
  
      # Load pretrained model and tokenizer
      # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
      # download model & vocab.
      config = AutoConfig.from_pretrained(
          model_args.config_name
          if model_args.config_name
          else model_args.model_name_or_path,
          num_labels=num_labels,
          finetuning_task="xnli",
          cache_dir=model_args.cache_dir,
          revision=model_args.model_revision,
          use_auth_token=True if model_args.use_auth_token else None,
      )
      tokenizer = AutoTokenizer.from_pretrained(
          model_args.tokenizer_name
          if model_args.tokenizer_name
          else model_args.model_name_or_path,
          do_lower_case=model_args.do_lower_case,
          cache_dir=model_args.cache_dir,
          use_fast=model_args.use_fast_tokenizer,
          revision=model_args.model_revision,
          use_auth_token=True if model_args.use_auth_token else None,
      )
      model = AutoModelForSequenceClassification.from_pretrained(
          model_args.model_name_or_path,
          from_tf=bool(".ckpt" in model_args.model_name_or_path),
          config=config,
          cache_dir=model_args.cache_dir,
          revision=model_args.model_revision,
          use_auth_token=True if model_args.use_auth_token else None,
          ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
      )
  
      # Preprocessing the datasets
      # Padding strategy
      if data_args.pad_to_max_length:
          padding = "max_length"
      else:
          # We will pad later, dynamically at batch creation, to the max sequence length in each batch
          padding = False
  
      def preprocess_function(examples):
          # Tokenize the texts
          return tokenizer(
              examples["premise"],
              examples["hypothesis"],
              padding=padding,
              max_length=data_args.max_seq_length,
              truncation=True,
          )
  
      if training_args.do_train:
          if data_args.max_train_samples is not None:
              max_train_samples = min(
                  len(train_dataset), data_args.max_train_samples
              )
              train_dataset = train_dataset.select(
                  range(max_train_samples)
              )
          with training_args.main_process_first(
              desc="train dataset map pre-processing"
          ):
              train_dataset = train_dataset.map(
                  preprocess_function,
                  batched=True,
                  load_from_cache_file=not data_args.overwrite_cache,
                  desc="Running tokenizer on train dataset",
              )
          # Log a few random samples from the training set:
          for index in random.sample(range(len(train_dataset)), 3):
              logger.info(
                  f"Sample {index} of the training set: {train_dataset[index]}."
              )
  
      if training_args.do_eval:
          if data_args.max_eval_samples is not None:
              max_eval_samples = min(
                  len(eval_dataset), data_args.max_eval_samples
              )
              eval_dataset = eval_dataset.select(
                  range(max_eval_samples)
              )
          with training_args.main_process_first(
              desc="validation dataset map pre-processing"
          ):
              eval_dataset = eval_dataset.map(
                  preprocess_function,
                  batched=True,
                  load_from_cache_file=not data_args.overwrite_cache,
                  desc="Running tokenizer on validation dataset",
              )
  
      if training_args.do_predict:
          if data_args.max_predict_samples is not None:
              max_predict_samples = min(
                  len(predict_dataset), data_args.max_predict_samples
              )
              predict_dataset = predict_dataset.select(
                  range(max_predict_samples)
              )
          with training_args.main_process_first(
              desc="prediction dataset map pre-processing"
          ):
              predict_dataset = predict_dataset.map(
                  preprocess_function,
                  batched=True,
                  load_from_cache_file=not data_args.overwrite_cache,
                  desc="Running tokenizer on prediction dataset",
              )
  
      # Get the metric function
      metric = evaluate.load("xnli")
  
      # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
      # predictions and label_ids field) and has to return a dictionary string to float.
      def compute_metrics(p: EvalPrediction):
          preds = (
              p.predictions[0]
              if isinstance(p.predictions, tuple)
              else p.predictions
          )
          preds = np.argmax(preds, axis=1)
          return metric.compute(
              predictions=preds, references=p.label_ids
          )
  
      # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
      if data_args.pad_to_max_length:
          data_collator = default_data_collator
      elif training_args.fp16:
          data_collator = DataCollatorWithPadding(
              tokenizer, pad_to_multiple_of=8
          )
      else:
          data_collator = None
  
      # Initialize our Trainer
      trainer = Trainer(
          model=model,
          args=training_args,
          train_dataset=train_dataset
          if training_args.do_train
          else None,
          eval_dataset=eval_dataset if training_args.do_eval else None,
          compute_metrics=compute_metrics,
          tokenizer=tokenizer,
          data_collator=data_collator,
      )
  
      # Training
      if training_args.do_train:
          checkpoint = None
          if training_args.resume_from_checkpoint is not None:
              checkpoint = training_args.resume_from_checkpoint
          elif last_checkpoint is not None:
              checkpoint = last_checkpoint
          train_result = trainer.train(
              resume_from_checkpoint=checkpoint
          )
          metrics = train_result.metrics
          max_train_samples = (
              data_args.max_train_samples
              if data_args.max_train_samples is not None
              else len(train_dataset)
          )
          metrics["train_samples"] = min(
              max_train_samples, len(train_dataset)
          )
  
          trainer.save_model()  # Saves the tokenizer too for easy upload
  
          trainer.log_metrics("train", metrics)
          trainer.save_metrics("train", metrics)
          trainer.save_state()
  
      # Evaluation
      if training_args.do_eval:
          logger.info("*** Evaluate ***")
          metrics = trainer.evaluate(eval_dataset=eval_dataset)
  
          max_eval_samples = (
              data_args.max_eval_samples
              if data_args.max_eval_samples is not None
              else len(eval_dataset)
          )
          metrics["eval_samples"] = min(
              max_eval_samples, len(eval_dataset)
          )
  
          trainer.log_metrics("eval", metrics)
          trainer.save_metrics("eval", metrics)
  
      # Prediction
      if training_args.do_predict:
          logger.info("*** Predict ***")
          predictions, labels, metrics = trainer.predict(
              predict_dataset, metric_key_prefix="predict"
          )
  
          max_predict_samples = (
              data_args.max_predict_samples
              if data_args.max_predict_samples is not None
              else len(predict_dataset)
          )
          metrics["predict_samples"] = min(
              max_predict_samples, len(predict_dataset)
          )
  
          trainer.log_metrics("predict", metrics)
          trainer.save_metrics("predict", metrics)
  
          predictions = np.argmax(predictions, axis=1)
          output_predict_file = os.path.join(
              training_args.output_dir, "predictions.txt"
          )
          if trainer.is_world_process_zero():
              with open(output_predict_file, "w") as writer:
                  writer.write("index\tprediction\n")
                  for index, item in enumerate(predictions):
                      item = label_list[item]
                      writer.write(f"{index}\t{item}\n")
  
file_path: H2O/h2o_flexgen/benchmark/third_party/transformers/examples/pytorch/text-classification/run_xnli.py
imports: import logging
  import os
  import random
  import sys
  from dataclasses import dataclass, field
  from typing import Optional
  import datasets
  import numpy
  from datasets import load_dataset
  import evaluate
  import transformers
  from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed
  from transformers.trainer_utils import get_last_checkpoint
  from transformers.utils import check_min_version, send_example_telemetry
  from transformers.utils.versions import require_version
label_desc: Use image node_id 1 for calling a global function with example usage: main() and returns: tokenizer, metric