Code for the paper "Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer"

Overview

T5: Text-To-Text Transfer Transformer

Build Status

The t5 library serves primarily as code for reproducing the experiments in Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. In the paper, we demonstrate how to achieve state-of-the-art results on multiple NLP tasks using a text-to-text transformer pre-trained on a large text corpus.

The bulk of the code in this repository is used for loading, preprocessing, mixing, and evaluating datasets. It also provides a way to fine-tune the pre-trained models released alongside the publication.

The t5 library can be used for future model development by providing useful modules for training and fine-tuning (potentially huge) models on mixtures of text-to-text tasks.

Table of Contents

Library

t5.data

t5.data is a package for defining Task objects that provide tf.data.Datasets.

Each Task is made up of:

  • a data source
  • text preprocessor function(s)
  • a SentencePiece model
  • metric function(s)

Additionally, you may optionally provide:

  • token preprocessor function(s)
  • postprocess function(s)

The data source can be an arbitrary function that provides a tf.data.Dataset, but we also provide simpler wrappers for datasets available in TensorFlow Datasets (TFDS) (a TfdsTask) or stored as text files with one example per line (a TextLineTask).

The text preprocessor converts the examples in the source dataset into the appropriate format for a text-to-text model with fields for inputs and targets. For example, the predefined t5.data.preprocessors.translate preprocessor converts inputs in the form

{'de': 'Das ist gut.', 'en': 'That is good.'}

to the form

{'inputs': 'translate German to English: Das ist gut.', 'targets': 'That is good.'}

In addition to text preprocessing, you can also use one or more token preprocessors to modify the inputs post-tokenization. We implemented our unsupervised pre-training objectives using these token preprocessors.

We provide many predefined preprocessors in t5.data.preprocessors, but you may also define your own.

The SentencePiece model is used to tokenize the input strings and decode the output tokens. You can create your own model with the google/sentencepiece library, or use our default one at t5.data.DEFAULT_SPM_PATH. If you create your own, you must use the flags --pad_id=0 --eos_id=1 --unk_id=2 --bos_id=-1 with spm_train to be compatible with our model code.

The metric function returns a score given the target and prediction from the model. You may also define a postprocess function to convert the target and prediction text to another format before calling the metric. We provide some predefined metrics in t5.evaluation.metrics.

Finally, t5.data contains a Mixture class that can be instantiated to combine multiple Task datasets for multi-task training using various functions for specifying the mixture rates.

t5.evaluation

t5.evaluation contains two core components:

  1. metrics to be used during evaluation
  2. utilities for applying these metrics at evaluation time

t5.models

t5.models contains shims for connecting T5 Tasks and Mixtures to a model implementation for training, evaluation, and inference.

Currently there are two shims available: One for the Mesh TensorFlow Transformer that we used in our paper and another for the Hugging Face Transformers library. The Hugging Face API is currently experimental and subject to change, but provides a simple and easy way to load, fine-tune, and evaluate our pre-trained models using PyTorch on a single GPU. If you want to use our largest models on TPUs and/or reproduce the results in our paper, you should use the MtfModel API and the t5_mesh_transformer binary. If you are interested fine-tuning our models on a GPU in PyTorch, you should try the HfPyTorchModel API. Since the HfPyTorchModel is experimental, the remainder of this README assumes usage of the MtfModel and its associated binary. A usage example of HfPyTorchModel is available here.

Usage

The easiest way to try out T5 is with a free TPU in our Colab Tutorial.

Below we provide examples for how to pre-train, fine-tune, evaluate, and decode from a model from the command-line with our codebase. You can use these instructions to reproduce our results, fine-tune one of our released checkpoints with your own data and/or hyperparameters, or pre-train a model from scratch.

Dataset Preparation

You may either use a new or pre-existing Task, or you may load examples from a preprocessed TSV file.

Using a Task

Depending on your data source (see above), you will need to prepare your data appropriately.

Task

If using a vanilla task, just make sure any file(s) loaded by your dataset_fn are accessible to the TPU (i.e., are in a GCS bucket), and you should be good to go!

TfdsTask

Most of our predefined Tasks use TensorFlow Datasets (TFDS) as their data source. When you run our training binary (see instructions below) with a TfdsTask, the dataset will automatically be downloaded and prepared on its first use. After preparation is complete, the dataset is cached to your local storage to avoid this overhead in future runs. If working in the cloud, we recommend you set the --t5_tfds_data_dir flag to point to a persistent storage location, such as a GCS bucket. This is a requirement when training on TPU.

C4

The C4 dataset we created for unsupervised pre-training is available in TensorFlow Datasets, but it requires a significant amount of bandwidth for downloading the raw Common Crawl scrapes (~7 TB) and compute for its preparation (~335 CPU-days). We suggest you take advantage of the Apache Beam support in TFDS, which enables distributed preprocessing of the dataset and can be run on Google Cloud Dataflow. With 500 workers, the job should complete in ~16 hours.

After defining MY_PROJECT and MY_BUCKET appropriately, you can build the dataset in DataFlow from GCP using the following commands:

pip install tfds-nightly[c4]
echo 'tfds-nightly[c4]' > /tmp/beam_requirements.txt
python -m tensorflow_datasets.scripts.download_and_prepare \
  --datasets=c4/en \
  --data_dir=gs://$MY_BUCKET/tensorflow_datasets \
  --beam_pipeline_options="project=$MY_PROJECT,job_name=c4,staging_location=gs://$MY_BUCKET/binaries,temp_location=gs://$MY_BUCKET/temp,runner=DataflowRunner,requirements_file=/tmp/beam_requirements.txt,experiments=shuffle_mode=service,region=$MY_REGION"

Read more in the TFDS Beam instructions.

TextLineTask

A TextLineTask is useful when your data source is a text file (or files) with one example per line. You can then use a text preprocessor to convert each line into a dictionary of inputs and targets.

Make sure your files are accessible to the TPU (i.e., are in a GCS bucket), and you should be good to go!

Using a TSV File Directly

Instead of defining a new Task, you may use a TSV file (or files) directly as your dataset where each line is formatted as <input>\t<target>.

However, there are a couple of caveats:

  • There is no way to define a text processor, so the TSV will need to contain your data in a preprocessed format.
  • There is also currently no way to set a token preprocessor, postprocess function, or metric function for evaluation when using a TSV file directly.

If you need any of these features, you must define a new Task, TfdsTask, or TextLineTask.

Similar to the above cases, your TSV file(s) must be accessible to the TPU (i.e., are in a GCS bucket).

Installation

To install the T5 package, simply run:

pip install t5[gcp]

Setting up TPUs on GCP

You will first need to launch a Virtual Machine (VM) on Google Cloud. Details about launching the VM can be found at the Google Cloud Documentation.

In order to run training or eval on Cloud TPUs, you must set up the following variables based on your project, zone and GCS bucket appropriately. Please refer to the Cloud TPU Quickstart guide for more details.

export PROJECT=your_project_name
export ZONE=your_project_zone
export BUCKET=gs://yourbucket/
export TPU_NAME=t5-tpu
export TPU_SIZE=v3-8
export DATA_DIR="${BUCKET}/your_data_dir"
export MODEL_DIR="${BUCKET}/your_model_dir"

Please use the following command to create a TPU device in the Cloud VM.

ctpu up --name=$TPU_NAME --project=$PROJECT --zone=$ZONE --tpu-size=$TPU_SIZE \
        --tpu-only --noconf

Training

In the command below, we train a model on the GLUE Benchmark MRPC task from scratch. You can change the MIXTURE_NAME gin parameter to use any of the tasks or mixtures provided in our package.

t5_mesh_transformer  \
  --tpu="${TPU_NAME}" \
  --gcp_project="${PROJECT}" \
  --tpu_zone="${ZONE}" \
  --model_dir="${MODEL_DIR}" \
  --t5_tfds_data_dir="${DATA_DIR}" \
  --gin_file="dataset.gin" \
  --gin_file="models/bi_v1.gin" \
  --gin_param="utils.tpu_mesh_shape.model_parallelism = 1" \
  --gin_param="utils.tpu_mesh_shape.tpu_topology = '${TPU_SIZE}'" \
  --gin_param="MIXTURE_NAME = 'glue_mrpc_v002'"

The full list of tasks and mixtures can be obtained by running:

python -c "import t5; print(t5.data.MixtureRegistry.names())"

You may also define additional tasks and mixtures in a new file and import it using the --module_import flag.

Alternatively, you could train with a TSV file where each line is formatted as <input>\t<target> (see above).

Fine-tuning

In order to fine-tune one of our pre-trained models, you need to pass the operative config of the pre-trained model to the training script. The operative config should be passed in as a gin_file flag. It specifies the model architecture and other hyperparameters. In addition, you need to specify the mixture to fine-tune on. For example, to fine-tune the T5-small model on the glue_mrpc_v002 mixture, please run:

t5_mesh_transformer  \
  --tpu="${TPU_NAME}" \
  --gcp_project="${PROJECT}" \
  --tpu_zone="${ZONE}" \
  --model_dir="${MODEL_DIR}" \
  --t5_tfds_data_dir="${DATA_DIR}" \
  --gin_file="dataset.gin" \
  --gin_param="utils.tpu_mesh_shape.model_parallelism = 1" \
  --gin_param="utils.tpu_mesh_shape.tpu_topology = '${TPU_SIZE}'" \
  --gin_param="MIXTURE_NAME = 'glue_mrpc_v002'" \
  --gin_file="gs://t5-data/pretrained_models/small/operative_config.gin"

The correct pre-trained checkpoint path is included in the operative config.

You may also define additional tasks and mixtures in a new file and import it using the --module_import flag.

Alternatively, you could fine-tune with a TSV file where each line is formatted as <input>\t<target> (see above). For example, you could try one of the paired translation datasets from WMT '19 News Commentary 14 training set (e.g., English-French). When using a TSV file, you would replace the MIXTURE_NAME flag with:

--gin_param="utils.run.train_dataset_fn = @t5.models.mesh_transformer.tsv_dataset_fn"
--gin_param="tsv_dataset_fn.filename = 'gs:/path/to/tsv'"

To fine-tune with the same hyperparameters we used in the paper (using a constant learning rate of 0.001), you can pass in this gin file which is included in the T5 package:

--gin_file="learning_rate_schedules/constant_0_001.gin"

The operative config for the pre-trained models are set so that there is effectively no limit on the number of train steps. If you'd like to train for a specific number of steps, you'll need to pass that in. Since the pre-trained model has already been trained for 1,000,000 steps, you should specify the total number of steps after pre-training and fine-tuning. For example, if you want to fine-tune for an additional 10,000 steps, you should pass

--gin_param="run.train_steps = 1010000"

You can also use a different batch size for fine-tuning. We set the batch size according to the total number of tokens in a batch. By default, a batch uses a sequence length of 512. To set the number of tokens in a batch, you should set

--gin_param = "tokens_per_batch=1048576"

Eval

In order to evaluate a model in the T5 framework, you need to use the eval.gin file, specify the model directory, decoding method, and which checkpoint step(s) to evaluate. So, to evaluate on the GLUE MRPC task using beam search on all checkpoints, use the following command:

t5_mesh_transformer \
  --tpu="${TPU_NAME}" \
  --gcp_project="${PROJECT}" \
  --tpu_zone="${ZONE}" \
  --model_dir="${MODEL_DIR}" \
  --gin_file="${MODEL_DIR}/operative_config.gin" \
  --t5_tfds_data_dir=${DATA_DIR} \
  --gin_file="eval.gin" \
  --gin_file="beam_search.gin" \
  --gin_param="run.dataset_split = 'validation'" \
  --gin_param="utils.tpu_mesh_shape.tpu_topology = '${TPU_SIZE}'" \
  --gin_param="MIXTURE_NAME = 'glue_mrpc_v002'" \
  --gin_param="eval_checkpoint_step = 'all'"

To evaluate a specific checkpoint, simply set the eval_checkpoint_step parameter to appropriate checkpoint.

--gin_param="eval_checkpoint_step = 100000"

You can also use greedy_decode.gin or sample_decode.gin instead of beam_search.gin in the command above.

Decode

In order to produce predictions from a model in the T5 framework, you need to specify the model directory, decoding method, and which checkpoint step(s) to use for decoding. Assuming you have a text file of input sequences stored at /path/to/intputs.txt, an example command would be:

t5_mesh_transformer \
  --tpu="${TPU_NAME}" \
  --gcp_project="${PROJECT}" \
  --tpu_zone="${ZONE}" \
  --model_dir="${MODEL_DIR}" \
  --gin_file="${MODEL_DIR}/operative_config.gin" \
  --gin_file="infer.gin" \
  --gin_file="sample_decode.gin" \
  --gin_param="input_filename = '/path/to/inputs.txt'"\
  --gin_param="output_filename = '/tmp/outputs.txt'"\
  --gin_param="utils.tpu_mesh_shape.tpu_topology = '${TPU_SIZE}'"\
  --gin_param="infer_checkpoint_step = 'all'"

To predict with a specific checkpoint, simply set the infer_checkpoint_step parameter to appropriate checkpoint.

--gin_param="infer_checkpoint_step = 100000"

You can also use beam_search.gin or greedy_decode.gin instead of sample_decode.gin in the command above.

Export

You may also want to export a SavedModel, which is useful for serving your trained model, (e.g., when deploying with ML Engine or in a Docker image).

t5_mesh_transformer \
  --gcp_project="${PROJECT}" \
  --tpu_zone="${ZONE}" \
  --model_dir="${MODEL_DIR}" \
  --use_model_api \
  --mode="export_predict" \
  --export_dir="/path/to/export/dir"

The command above exports the latest checkpoint in the model directory. To export a particular checkpoint, add the following flags:

  --checkpoint_mode="specific" \
  --checkpoint_steps=1000000

The t5-deploy notebook demonstrates exporting a SavedModel and packaging it in a Docker image for serving.

GPU Usage

If you would like to use GPU instead of TPUs, you can modify the above commands by removing TPU-specific flags (--tpu, --tpu_zone, --gcp_project) and setting the gin params for mesh_shape and mesh_devices based on your desired setup.

For example, if your machine has access to 6 GPUs and you'd like to do 3-way model parallelism and 2-way data parallelism, the fine-tuning command above would become:

t5_mesh_transformer  \
  --model_dir="${MODEL_DIR}" \
  --t5_tfds_data_dir="${DATA_DIR}" \
  --gin_file="dataset.gin" \
  --gin_param="utils.run.mesh_shape = 'model:3,batch:2'" \
  --gin_param="utils.run.mesh_devices = ['gpu:0','gpu:1','gpu:2','gpu:3','gpu:4','gpu:5']" \
  --gin_param="MIXTURE_NAME = 'glue_mrpc_v002'" \
  --gin_file="gs://t5-data/pretrained_models/small/operative_config.gin"

With a single GPU, the command is:

t5_mesh_transformer  \
  --model_dir="${MODEL_DIR}" \
  --t5_tfds_data_dir="${DATA_DIR}" \
  --gin_file="dataset.gin" \
  --gin_param="utils.run.mesh_shape = 'model:1,batch:1'" \
  --gin_param="utils.run.mesh_devices = ['gpu:0']" \
  --gin_param="MIXTURE_NAME = 'glue_mrpc_v002'" \
  --gin_file="gs://t5-data/pretrained_models/small/operative_config.gin"

Reproducing our experiments

We provide operative configs for all of the experiments in the paper in gs://t5-data/experiments. The experiments folder has different subdirectories corresponding to the different sections in our paper. For example, gs://t5-data/experiments/objectives contains the experiments from Section 3.3 ("Unsupervised objectives"). Each subdirectory of the objectives folder contains operative configs for some particular experiment (where loosely speaking an "experiment" is one of the rows in one of the tables in our paper).

Let's say you want to reproduce the results for the "Prefix language modeling" objective (the first row in Table 4). The operative configs for that experiment live in gs://t5-data/experiments/objectives/obj-prefix_lm. In the base directory, there is an operative config for pre-training the model (gs://t5-data/experiments/objectives/obj-prefix_lm/operative_config.gin). Then, there are subdirectories for each of the downstream fine-tuning mixtures we consider, each of which has its own operative config (for example, gs://t5-data/experiments/objectives/obj-prefix_lm/cnn_dailymail_v002/operative_config.gin). To run this experiment, first pre-train a model with the pre-training operative config:

export PRETRAIN_MODEL_DIR="${BUCKET}/obj-prefix_lm"
t5_mesh_transformer  \
  --tpu="${TPU_NAME}" \
  --gcp_project="${PROJECT}" \
  --tpu_zone="${ZONE}" \
  --model_dir="${PRETRAIN_MODEL_DIR}" \
  --gin_file="gs://t5-data/experiments/objectives/obj-prefix_lm/operative_config.gin" \
  --gin_param="utils.tpu_mesh_shape.model_parallelism = 1" \
  --gin_param="utils.tpu_mesh_shape.tpu_topology = '${TPU_SIZE}'"

Then, you can fine-tune the pre-trained model on CNN/Daily Mail like so:

export FINETUNE_MODEL_DIR="${BUCKET}/obj-prefix_lm/cnn_dailymail_v002"
t5_mesh_transformer  \
  --tpu="${TPU_NAME}" \
  --gcp_project="${PROJECT}" \
  --tpu_zone="${ZONE}" \
  --model_dir="${FINETUNE_MODEL_DIR}" \
  --gin_file="gs://t5-data/experiments/objectives/obj-prefix_lm/cnn_dailymail_v002/operative_config.gin" \
  --gin_param="init_checkpoint = '${PRETRAIN_MODEL_DIR}/model.ckpt-524288'" \
  --gin_param="utils.tpu_mesh_shape.model_parallelism = 1" \
  --gin_param="utils.tpu_mesh_shape.tpu_topology = '${TPU_SIZE}'"

Useful Options

Some training variants need multiple flags to be set at the same time. For each of the below variants, add the group of flags to ./third_party/py/t5/google/scripts/run_finetune.sh.

Deterministic training

  --train_gin_param="mesh_train_dataset_fn.seed=${SEED}" \
  --train_gin_param="utils.run.skip_seen_data = True" \

Language model

  --objective="lm" \
  --train_gin_param="utils.run.model_type = \"lm\"" \

Released Model Checkpoints

We have released the following checkpoints for pre-trained models described in our paper:

See here for a list of additional experimental pre-trained model checkpoints.

How to Cite

If you extend or use this work, please cite the paper where it was introduced:

@article{2020t5,
  author  = {Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu},
  title   = {Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer},
  journal = {Journal of Machine Learning Research},
  year    = {2020},
  volume  = {21},
  number  = {140},
  pages   = {1-67},
  url     = {http://jmlr.org/papers/v21/20-074.html}
}
Comments
  • Training T5 from scratch on a new language?

    Training T5 from scratch on a new language?

    Hi I was wondering if there are any guidelines or documentation as to pre-training T5 from scratch (not just to any particular downstream task) in a new language?

    Also is it possible to do the same with PyTorch under the current framework?

    Please let me know if this is not the right place to discuss this, thank you!

    opened by ritvik1512 24
  • How to get a probability for the generated text?

    How to get a probability for the generated text?

    Hi there,

    Thanks for releasing the code and examples for such a great model.

    I've followed the example and been able to train a model using my own dataset and everything is working now.

    I have one question though, is it possible to get a probability score for the generated text? When I run the the model in prediction mode, I can only see the inputs and outputs text.

    imported.signatures["serving_default"](tf.constant(["trivia question: What's the highest mountain in the world?"]))
     'inputs': <tf.Tensor: shape=(10,), dtype=string, numpy=
     array([b"trivia question: What's the highest mountain in the world?", b'',
            b'', b'', b'', b'', b'', b'', b'', b''], dtype=object)>,
     'outputs': <tf.Tensor: shape=(10,), dtype=string, numpy=
     array([b'travel - national', b'', b'', b'', b'', b'', b'', b'', b'', b''],
           dtype=object)>}
    

    Thanks, Allen

    opened by allen-q 22
  • Using the exported models

    Using the exported models

    First, thank you for being so helpful + patient with issues/questions. 🙏

    I have a successfully trained/evaluated model and now I am trying to use an exported model created using the construction explained here.

    Here are several efforts:

    (1) Using GC "AI Platform" to deploy models:

    Here I am getting the following error: Screen Shot 2020-03-25 at 7 21 07 PM

    Create Version failed. Model validation failed: Outer dimension for outputs must be unknown, outer dimension of 'SentenceTokenizer/SentenceTokenizer/SentencepieceDetokenizeOp:0' is 1 For more information on how to export Tensorflow SavedModel, see https://www.tensorflow.org/api_docs/python/tf/saved_model.
    

    See the figure below:

    (2) I tried following the code in the Colab:

    import tensorflow.compat.v1 as tf
    tf.reset_default_graph()
    TPU_ADDRESS="danielk-tpu-europe-west4-a-v3-8-no4"
    saved_model_path="gs://danielk-files/t5-models/squad1_1_race_string_mixture/small/export/1585135433"
    sess = tf.Session(TPU_ADDRESS)
    meta_graph_def = tf.saved_model.loader.load(sess, ["serve"], saved_model_path)
    signature_def = meta_graph_def.signature_def["serving_default"]
    
    def answer(question):
      return sess.run(
          fetches=signature_def.outputs["outputs"].name,
          feed_dict={signature_def.inputs["input"].name: [question]}
      )[0].decode('utf-8')
    
    
    for question in ["trivia question: where is the google headquarters?",
                     "trivia question: what is the most populous country in the world?",
                     "trivia question: who are the 4 members of the beatles?",
                     "trivia question: how many teeth do humans have?"]:
        print(answer(question))
    

    I am getting the following error:

    2020-03-26 02:31:17.361676: E tensorflow/core/common_runtime/session.cc:89] Not found: No session factory registered for the given session options: {target: "danielk-tpu-europe-west4-a-v3-8-no4" config: device_count { key: "CPU" value: 1 } device_count { key: "GPU" value: 0 } gpu_options { experimental { } }} Registered factories are {DIRECT_SESSION, GRPC_SESSION}.
    Traceback (most recent call last):
      File "predict_single_instance.py", line 5, in <module>
        sess = tf.Session(TPU_ADDRESS)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/client/session.py", line 1585, in __init__
        super(Session, self).__init__(target, graph, config=config)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/client/session.py", line 699, in __init__
        self._session = tf_session.TF_NewSessionRef(self._graph._c_graph, opts)
    tensorflow.python.framework.errors_impl.NotFoundError: No session factory registered for the given session options: {target: "danielk-tpu-europe-west4-a-v3-8-no4" config: device_count { key: "CPU" value: 1 } device_count { key: "GPU" value: 0 } gpu_options { experimental { } }} Registered factories are {DIRECT_SESSION, GRPC_SESSION}.
    

    Wondering if you have any suggestions.

    opened by danyaljj 22
  • Slow exported model when running on TPU

    Slow exported model when running on TPU

    I followed the instructions on T5's Colab to export a T5-base model and serve it on a TPU. However, I noticed that inference very slow: ~26 secs for a batch of 128 examples, each with 512 input tokens. Any idea what is going on?

    I'm sharing my Colab in case you want to take a look: https://colab.research.google.com/drive/1F31tPk4Cdq9cL5M6rVcbnSGNeG6s26Qv

    opened by rodrigonogueira4 22
  • Evaluation Loss

    Evaluation Loss

    Hi

    I want to compute evaluation loss on my test dataset. I have checked code but could not find any option to set loss as evaluation metric. I want to compute loss on evaluation data to see if model is overfitting or not and my task is prefix style language modelling.

    Is it possible to calculate loss on eval/test data?

    Thanks.

    opened by NaxAlpha 18
  • Predictions elicited from `hf_model.py` do no match that of HuggingFace

    Predictions elicited from `hf_model.py` do no match that of HuggingFace

    Hey there! 👋

    TLDR; I have this t5-small model that is fine-tuned on natural-questions. For this model, I get its predictions once using hf_model.py and another time using HF code. The outputs are different (and the outputs using HF seem to be more reasonable).

    This is a thread on using hf_model.py; I know that this code is not a well-tested code. Sharing these observations here in case they help you improve this model.

    1. When I try to make predictions using hf_model:
    import functools
    import t5
    import torch
    import transformers
    if torch.cuda.is_available():
        device = torch.device("cuda")
    else:
        device = torch.device("cpu")
    path = "/home/danielk/small_standard/pytorch_model/"
    model = t5.models.HfPyTorchModel(path, path, device)
    # Generate some predictions
    inputs = [
        "Who is the US president? ",
        "How many states are there in USA? ",
        "who got the first nobel prize in physics?",
        "when is the next deadpool movie being released?",
        "which mode is used for short wave broadcast service?"
    ]
    model.predict(
        inputs,
        sequence_length={"inputs": 32},
        batch_size=2,
        output_file=f"{path}/example_predictions.txt",
    )
    print("done making the predictions . . . ")
    

    and here is the output:

    2020-10-21 21:22:46.322911: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
    2020-10-21 21:22:46.324427: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1257] Device interconnect StreamExecutor with strength 1 edge matrix:
    2020-10-21 21:22:46.324456: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1263]      
    /home/danielk/text-to-text-transfer-transformer/t5/models/hf_model.py:547: UserWarning: Creating resources inside a function passed to Dataset.map() is not supported. Create each resource outside the function, and capture it inside the function to use it.
      dataset = dataset.map(
    INFO:absl:Who is the US president? 
      -> Who Who Donald Donald Donald Donald Donald Donald Donald Donald Donald Donald Donald Donald Donald Donald Donald Donald Donald
    INFO:absl:How many states are there in USA? 
      -> 5 states
    INFO:absl:who got the first nobel prize in physics?
      -> Wilhelm Conrad Röntgen
    INFO:absl:when is the next deadpool movie being released?
      -> 2018 2018 2018 2018 2018 2018 2018
    INFO:absl:which mode is used for short wave broadcast service?
      -> on on on on on on on on
    done making the predictions . . . 
    
    1. Now I try to use the same model using HF code:
    from transformers import T5Config, T5Tokenizer, T5ForConditionalGeneration
    
    path = "/home/danielk/small_standard/pytorch_model"
    model = T5ForConditionalGeneration.from_pretrained(path)
    tokenizer = T5Tokenizer.from_pretrained(path)
    model.eval()
    
    def run_model(input_string, **generator_args):
        input_ids = tokenizer.encode(input_string, return_tensors="pt")
        res = model.generate(input_ids, **generator_args)
        tokens = [tokenizer.decode(x) for x in res]
        print(tokens)
    
    run_model("how many states does the US has? ")
    run_model("who is the US president?")
    run_model("who got the first nobel prize in physics?")
    run_model("when is the next deadpool movie being released?")
    run_model("which mode is used for short wave broadcast service?")
    run_model("the south west wind blows across nigeria between?")
    

    Here is the output:

    2020-10-21 21:14:44.634221: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'libcudart.so.10.1'; dlerror: libcudart.so.10.1: cannot open shared object file: No such file or directory
    2020-10-21 21:14:44.634259: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
    ['50']
    ['Donald Trump']
    ['Wilhelm Conrad Röntgen']
    ['December 18, 2018']
    ['TCP port 25']
    ['the Nigerian and Pacific Oceans']
    
    opened by danyaljj 17
  • Model Distillation for T5?

    Model Distillation for T5?

    Hi there 👋

    I am interested in writing distillation functionality for T5. Wondering if I can get your wisdom on whether this is a reasonable path. I am summarizing my implementation idea below:

    1. In the mesh library I found a StudentTeacher class which is basically supposed to perform the distillation task. The class gets initialized with student and teacher models (both BiTransformers). It has a member method call_simple(.) that computes the loss for the student model (based on its distance to the gold label and the teacher's logits). My understanding is that this class should be enough to implement distillation.

    2. Looking into mesh_tensorflow/transformer/utils.py file, it seems to me that the current estimator functions for models already supports the aforementioned StudentTeacher class.

    3. As a corollary of the previous points, I think it should be possible to re-use MtfModel class, for an appropriate definition of model_type (bi_student_teacher instead of bitransformer):

    model = t5.models.MtfModel(
        model_type='bi_student_teacher',
       # and the rest of the parameters here 
    )
    

    One issue that is not clear to me is, how to specify the model-dirs for both teacher + student models, given that MtfModel(.) accepts only a single model parameter.

    Do you think this all makes sense?

    Sorry for the long text.

    FYI @sbhaktha

    opened by danyaljj 17
  • Run-time shape mismatch for TPUExecute argument

    Run-time shape mismatch for TPUExecute argument

    I am am getting the following error while trying to run evaluation:

            5254,     1]), 'targets_plaintext': b"bainbridge's", 'targets': array([7835, 9818,   31,    7,    1])}
    {'inputs_plaintext': b"question: (nikola_tesla) tesla went on to pursue his ideas of wireless lighting and electricity distribution in his high-voltage, high-frequency power experiments in new york and colorado springs, and made early (1893) pronouncements on the possibility of wireless communication with his devices. he tried to put these ideas to practical use in an ill-fated attempt at intercontinental wireless transmission, his unfinished wardenclyffe tower project. in his lab he also conducted a range of experiments with mechanical oscillators/generators, electrical discharge tubes, and early x-ray imaging. he also built a wireless controlled boat, one of the first ever exhibited. what were some of tesla's experiments?", 'inputs': array([  822,    10,    41,  4953,    32,   521,   834,  1422,   521,
              61,     3,  1422,   521,   877,    30,    12,  6665,   112,
             912,    13,  5419,  3598,    11,  6373,  3438,    16,   112,
             306,    18, 10897,   545,     6,   306,    18, 30989,   579,
           12341,    16,   126, 25453,    11,   945,     9,    26,    32,
            2141,     7,     6,    11,   263,   778,  9323,  4271,    61,
           29786,  4128,    30,     8,  5113,    13,  5419,  1901,    28,
             112,  1904,     5,     3,    88,  1971,    12,   474,   175,
             912,    12,  3236,   169,    16,    46,     3,  1092,    18,
              89,   920,  3332,    44,  1413, 27339,   138,  5419,  5790,
               6,   112,    73, 19420,   615,   537,    75,   120,  7398,
            7293,   516,     5,    16,   112,  7690,     3,    88,    92,
            4468,     3,     9,   620,    13, 12341,    28,  8168, 22117,
              40,  6230,    87,   729,    49,  6230,     6,  4850, 12445,
           17927,     1]), 'targets_plaintext': b'mechanical oscillators/generators, electrical discharge tubes, and early x-ray imaging', 'targets': array([ 8168, 22117,    40,  6230,    87,   729,    49,  6230,     6,
            4850, 12445, 17927,     6,    11,   778,     3,   226,    18,
            2866, 12586,     1])}
    {'inputs_plaintext': b'question: (steam_engine) the heat required for boiling the water and supplying the steam can be derived from various sources, most commonly from burning combustible materials with an appropriate supply of air in a closed space (called variously combustion chamber, firebox). in some cases the heat source is a nuclear reactor, geothermal energy, solar energy or waste heat from an internal combustion engine or industrial process. in the case of model or toy steam engines, the heat source can be an electric heating element. aside from firebox, what is another name for the space in which combustible material is burned in the engine?', 'inputs': array([  822,    10,    41,     7, 11650,   834, 20165,    61,     8,
            1678,   831,    21, 22151,     8,   387,    11,     3, 19327,
               8,  7222,    54,    36,     3,  9942,    45,   796,  2836,
               6,   167,  5871,    45,  9706,     3,   287,  3465,    17,
            2317,  1397,    28,    46,  2016,  1899,    13,   799,    16,
               3,     9,  3168,   628,    41,  9341,   796,   120, 27348,
           10751,     6,  1472,  2689,   137,    16,   128,  1488,     8,
            1678,  1391,    19,     3,     9,  6414, 24715,     6,   873,
            9269,  1982,   827,     6,  3693,   827,    42,  2670,  1678,
              45,    46,  3224, 27348,  1948,    42,  2913,   433,     5,
              16,     8,   495,    13,   825,    42,    12,    63,  7222,
            7277,     6,     8,  1678,  1391,    54,    36,    46,  2806,
            5866,  3282,     5,  5915,    45,  1472,  2689,     6,   125,
              19,   430,   564,    21,     8,   628,    16,    84,     3,
             287,     1]), 'targets_plaintext': b'combustion chamber', 'targets': array([27348, 10751,     1])}
     >>>>>>> creating dataset mixture . . .
     >>>>>> evaluations  . . .
     >>>> about to read csv . . .
     >>>> after reading csv . . .
     >>>> after mapping . . .
    WARNING:tensorflow:From /home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
    Instructions for updating:
    If using Keras pass *_constraint arguments to layers.
    2020-02-22 07:43:39.261890: W tensorflow/core/distributed_runtime/rpc/grpc_session.cc:370] GrpcSession::ListDevices will initialize the session with an empty graph and other defaults because the session has not yet been created.
     >>>> about to read csv . . .
     >>>> after reading csv . . .
     >>>> after mapping . . .
    WARNING:tensorflow:SimdMeshImpl ignoring devices ['', '', '', '', '', '', '', '']
    WARNING:tensorflow:Using default tf glorot_uniform_initializer for variable encoder/block_000/layer_000/SelfAttention/relative_attention_bias  The initialzer will guess the input and output dimensions  based on dimension order.
    WARNING:tensorflow:Using default tf glorot_uniform_initializer for variable decoder/block_000/layer_000/SelfAttention/relative_attention_bias  The initialzer will guess the input and output dimensions  based on dimension order.
    WARNING:tensorflow:Using default tf glorot_uniform_initializer for variable decoder/block_000/layer_000/SelfAttention/relative_attention_bias  The initialzer will guess the input and output dimensions  based on dimension order.
    WARNING:tensorflow:From /home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/ops/array_ops.py:1475: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
    Instructions for updating:
    Use tf.where in 2.0, which has the same broadcast rule as np.where
    WARNING:tensorflow:From /home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py:818: Variable.load (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
    Instructions for updating:
    Prefer Variable.assign which has equivalent behavior in 2.X.
    ERROR:tensorflow:Error recorded from infeed: From /job:worker/replica:0/task:0:
    Run-time shape mismatch for TPUExecute argument[98] (VarHandles_8915694147696093427/_7:96). Expected element_type: F32
    dimensions: 32000
    dimensions: 512
    layout {
      minor_to_major: 1
      minor_to_major: 0
      format: DENSE
    }
    is_dynamic_dimension: false
    is_dynamic_dimension: false
    ; got element_type: F32
    dimensions: 32128
    dimensions: 512
    layout {
      minor_to_major: 1
      minor_to_major: 0
      format: DENSE
    }
    is_dynamic_dimension: false
    is_dynamic_dimension: false
    
             [[node TPUReplicateMetadata (defined at /home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:1748) ]]
    
    Original stack trace for 'TPUReplicateMetadata':
      File "fine-tune-daniel.py", line 144, in <module>
        split="dev"
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/t5/models/mtf_model.py", line 252, in eval
        self._model_dir, dataset_fn, summary_dir, checkpoint_steps)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/mesh_tensorflow/transformer/utils.py", line 1264, in eval_model
        decodes = decode(estimator, input_fn, vocabulary, checkpoint_path)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/gin/config.py", line 1055, in gin_wrapper
        return fn(*new_args, **new_kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/mesh_tensorflow/transformer/utils.py", line 835, in decode
        for i, result in enumerate(result_iter):
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 3072, in predict
        yield_single_examples=yield_single_examples):
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/estimator.py", line 622, in predict
        features, None, ModeKeys.PREDICT, self.config)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 2857, in _call_model_fn
        config)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/estimator.py", line 1149, in _call_model_fn
        model_fn_results = self._model_fn(features=features, **kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 3393, in _model_fn
        ctx, model_fn_wrapper, dequeue_fn)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 3648, in _predict_on_tpu_system
        device_assignment=ctx.device_assignment)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/tpu/tpu.py", line 1277, in split_compile_and_shard
        name=name)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/tpu/tpu.py", line 927, in split_compile_and_replicate
        num_replicas=num_replicas, use_tpu=use_tpu, **metadata_kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/ops/gen_tpu_ops.py", line 6105, in tpu_replicate_metadata
        name=name)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/op_def_library.py", line 794, in _apply_op_helper
        op_def=op_def)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/util/deprecation.py", line 507, in new_func
        return func(*args, **kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py", line 3357, in create_op
        attrs, op_def, compute_device)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py", line 3426, in _create_op_internal
        op_def=op_def)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py", line 1748, in __init__
        self._traceback = tf_stack.extract_stack()
    
    ERROR:tensorflow:Closing session due to error From /job:worker/replica:0/task:0:
    Run-time shape mismatch for TPUExecute argument[98] (VarHandles_8915694147696093427/_7:96). Expected element_type: F32
    dimensions: 32000
    dimensions: 512
    layout {
      minor_to_major: 1
      minor_to_major: 0
      format: DENSE
    }
    is_dynamic_dimension: false
    is_dynamic_dimension: false
    ; got element_type: F32
    dimensions: 32128
    dimensions: 512
    layout {
      minor_to_major: 1
      minor_to_major: 0
      format: DENSE
    }
    is_dynamic_dimension: false
    is_dynamic_dimension: false
    
             [[node TPUReplicateMetadata (defined at /home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:1748) ]]
    
    Original stack trace for 'TPUReplicateMetadata':
      File "fine-tune-daniel.py", line 144, in <module>
        split="dev"
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/t5/models/mtf_model.py", line 252, in eval
        self._model_dir, dataset_fn, summary_dir, checkpoint_steps)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/mesh_tensorflow/transformer/utils.py", line 1264, in eval_model
        decodes = decode(estimator, input_fn, vocabulary, checkpoint_path)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/gin/config.py", line 1055, in gin_wrapper
        return fn(*new_args, **new_kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/mesh_tensorflow/transformer/utils.py", line 835, in decode
        for i, result in enumerate(result_iter):
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 3072, in predict
        yield_single_examples=yield_single_examples):
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/estimator.py", line 622, in predict
        features, None, ModeKeys.PREDICT, self.config)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 2857, in _call_model_fn
        config)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/estimator.py", line 1149, in _call_model_fn
        model_fn_results = self._model_fn(features=features, **kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 3393, in _model_fn
        ctx, model_fn_wrapper, dequeue_fn)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 3648, in _predict_on_tpu_system
        device_assignment=ctx.device_assignment)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/tpu/tpu.py", line 1277, in split_compile_and_shard
        name=name)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/tpu/tpu.py", line 927, in split_compile_and_replicate
        num_replicas=num_replicas, use_tpu=use_tpu, **metadata_kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/ops/gen_tpu_ops.py", line 6105, in tpu_replicate_metadata
        name=name)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/op_def_library.py", line 794, in _apply_op_helper
        op_def=op_def)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/util/deprecation.py", line 507, in new_func
        return func(*args, **kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py", line 3357, in create_op
        attrs, op_def, compute_device)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py", line 3426, in _create_op_internal
        op_def=op_def)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py", line 1748, in __init__
        self._traceback = tf_stack.extract_stack()
    
    ERROR:tensorflow:Error recorded from prediction_loop: Step was cancelled by an explicit call to `Session::Close()`.
    WARNING:tensorflow:Reraising captured error
    Traceback (most recent call last):
      File "fine-tune-daniel.py", line 144, in <module>
        split="dev"
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/t5/models/mtf_model.py", line 252, in eval
        self._model_dir, dataset_fn, summary_dir, checkpoint_steps)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/mesh_tensorflow/transformer/utils.py", line 1264, in eval_model
        decodes = decode(estimator, input_fn, vocabulary, checkpoint_path)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/gin/config.py", line 1078, in gin_wrapper
        utils.augment_exception_message_and_reraise(e, err_str)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/gin/utils.py", line 49, in augment_exception_message_and_reraise
        six.raise_from(proxy.with_traceback(exception.__traceback__), None)
      File "<string>", line 3, in raise_from
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/gin/config.py", line 1055, in gin_wrapper
        return fn(*new_args, **new_kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/mesh_tensorflow/transformer/utils.py", line 835, in decode
        for i, result in enumerate(result_iter):
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 3078, in predict
        rendezvous.raise_errors()
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/error_handling.py", line 136, in raise_errors
        six.reraise(typ, value, traceback)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/six.py", line 703, in reraise
        raise value
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/error_handling.py", line 109, in catch_errors
        yield
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 536, in _run_infeed
        session.run(self._enqueue_ops)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/client/session.py", line 956, in run
        run_metadata_ptr)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/client/session.py", line 1180, in _run
        feed_dict_tensor, options, run_metadata)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/client/session.py", line 1359, in _do_run
        run_metadata)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/client/session.py", line 1384, in _do_call
        raise type(e)(node_def, op, message)
    tensorflow.python.framework.errors_impl.InvalidArgumentError: From /job:worker/replica:0/task:0:
    Run-time shape mismatch for TPUExecute argument[98] (VarHandles_8915694147696093427/_7:96). Expected element_type: F32
    dimensions: 32000
    dimensions: 512
    layout {
      minor_to_major: 1
      minor_to_major: 0
      format: DENSE
    }
    is_dynamic_dimension: false
    is_dynamic_dimension: false
    ; got element_type: F32
    dimensions: 32128
    dimensions: 512
    layout {
      minor_to_major: 1
      minor_to_major: 0
      format: DENSE
    }
    is_dynamic_dimension: false
    is_dynamic_dimension: false
    
             [[node TPUReplicateMetadata (defined at /home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:1748) ]]
    
    Original stack trace for 'TPUReplicateMetadata':
      File "fine-tune-daniel.py", line 144, in <module>
        split="dev"
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/t5/models/mtf_model.py", line 252, in eval
        self._model_dir, dataset_fn, summary_dir, checkpoint_steps)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/mesh_tensorflow/transformer/utils.py", line 1264, in eval_model
        decodes = decode(estimator, input_fn, vocabulary, checkpoint_path)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/gin/config.py", line 1055, in gin_wrapper
        return fn(*new_args, **new_kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/mesh_tensorflow/transformer/utils.py", line 835, in decode
        for i, result in enumerate(result_iter):
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 3072, in predict
        yield_single_examples=yield_single_examples):
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/estimator.py", line 622, in predict
        features, None, ModeKeys.PREDICT, self.config)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 2857, in _call_model_fn
        config)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/estimator.py", line 1149, in _call_model_fn
        model_fn_results = self._model_fn(features=features, **kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 3393, in _model_fn
        ctx, model_fn_wrapper, dequeue_fn)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py", line 3648, in _predict_on_tpu_system
        device_assignment=ctx.device_assignment)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/tpu/tpu.py", line 1277, in split_compile_and_shard
        name=name)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/tpu/tpu.py", line 927, in split_compile_and_replicate
        num_replicas=num_replicas, use_tpu=use_tpu, **metadata_kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/ops/gen_tpu_ops.py", line 6105, in tpu_replicate_metadata
        name=name)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/op_def_library.py", line 794, in _apply_op_helper
        op_def=op_def)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/util/deprecation.py", line 507, in new_func
        return func(*args, **kwargs)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py", line 3357, in create_op
        attrs, op_def, compute_device)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py", line 3426, in _create_op_internal
        op_def=op_def)
      File "/home/danielk/anaconda3/envs/env37/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py", line 1748, in __init__
        self._traceback = tf_stack.extract_stack()
    
    

    the evaluation code looks like this, following the instructions in the notebook.

        model.batch_size = train_batch_size * 4
        model.eval(
            mixture_or_task_name="natural_questions",
            checkpoint_steps="all"
        )
    
    opened by danyaljj 17
  • Running inference

    Running inference

    Hi, I am trying to run inference on exported model. I am using tensorflow serving to deploy the model. After deploying, when I send the request, I get this error:

    out = requests.post('http://localhost:8501/v1/models/t5:predict', json=dict(inputs=['hello']))
    

    Error message:

    image

    Can anyone help me what I am doing wrong here? Thanks

    opened by NaxAlpha 15
  • Add custom logging to `seqio.evaluation.Evaluator`.

    Add custom logging to `seqio.evaluation.Evaluator`.

    Add custom logging to seqio.evaluation.Evaluator.

    This CL adds the ability to pass a function to the Evaluator via the log_fn parameter. When running evaluation this function with the resulting task metrics. If a log_fn isn't provided it will default to using the TensorboardLogging object in seqio.evaluation which serves as example of a custom logging. This object has equivalent functionality to the old _log_eval_results method.

    This also includes some updates the the evaluation tests so the default _log_fn is set when we mock the Evaluator's __init__ As well as tests for the cases where both a summary_dir and a log_fn are provided to the Evaluator

    cla: no 
    opened by copybara-service[bot] 14
  • 11B model training on TPU V3-512 Crashes during training

    11B model training on TPU V3-512 Crashes during training

    Hello,

    We have started large scale training for the 11B model on TPU V3-512, but the model keeps crashing and trying to recover during training:

    I0626 06:03:25.061087 139703188657984 basic_session_run_hooks.py:614] Calling checkpoint listeners before saving checkpoint 8300...
    INFO:tensorflow:Before Save.
    I0626 06:03:25.061593 139703188657984 ops.py:5742] Before Save.
    INFO:tensorflow:About to write a checkpoint
    I0626 06:03:29.075753 139703188657984 ops.py:5744] About to write a checkpoint
    INFO:tensorflow:Saving checkpoints for 8300 into gs://xxxxxxxx/11b/model.ckpt.
    I0626 06:03:29.076128 139703188657984 basic_session_run_hooks.py:618] Saving checkpoints for 8300 into gs://prot-transformers-eu/t5/models/un
    iref100/11b/model.ckpt.
    INFO:tensorflow:An error was raised. This may be due to a preemption in a connected worker or parameter server. The current session will be c
    losed and a new session will be created. This error may also occur due to a gRPC failure caused by high memory or network bandwidth usage in
    the parameter servers. If this error occurs repeatedly, try increasing the number of parameter servers assigned to the job. Error: From /job:
    worker/replica:0/task:15:
    All 10 retry attempts failed. The last failure: Unavailable: Error executing an HTTP request: HTTP response code 503
             when resuming upload gs://xxx/11b/model.ckpt-8300_temp_289083b0ae5e4c4891b42a91ff3cf66f/
             [[node save/SaveV2_7 (defined at /site-packages/mesh_tensorflow/transformer/utils.py:720) ]]
    
    Errors may have originated from an input operation.
    Input Source operations connected to node save/SaveV2_7:
     encoder/block_000/layer_000/SelfAttention/relative_attention_bias/Read/ReadVariableOp (defined at /site-packages/mesh_tensorflow/ops.py:4020
    )
    

    The error usually occurs when it tries to save a new checkpoint, when it happens it doesn't store the checkpoint and it reloads the previous checkpoint.

    I also notice the loss is heavily affected when this issue occurs, the blue line is the base version trained on Colab pro and the green line is the 11B version trained on the TPU pod.

    Screenshot 2020-06-26 at 09 53 22

    And ideas what could be the cause of this problem and how to overcome it ?

    @adarob @craffel @sharannarang @nshazeer , Your feedback is highly appreciated.

    opened by agemagician 14
  • Upgrade GLUE Version to 2.0.0

    Upgrade GLUE Version to 2.0.0

    GLUE 1.0.0 was causing errors with TFDS as it is outdated. Upgrading to 2.0.0 fixed the issue.

    ValueError: The version of the dataset you are trying to use (glue/cola/1.0.0) is too old for this version of TFDS so cannot be generated.Either sync to a previous version of TFDS to first prepare the data or use another version of the dataset. Available fordownload_and_prepare: ['2.0.0']

    opened by fadebek1 1
  • CUDA OOM with HF Model

    CUDA OOM with HF Model

    Hi, has the HF model been tested to train on CUDA? I am getting OOM errors no matter how small the batch size is. Im using a V100 32GB. A code snippet is attached below. I've profiled the individual steps of hf_model.train using nvidia-smi and narrowed down the issue to here. The GPU memory spikes to fill up 32GB after the dataset is loaded. Is all of the data being loaded onto the GPU? Is this supposed to happen? Is there a way to disable this behavior? The error message also supports this as PyTorch only reserved 2.8GB for the model itself.

    import t5.data.mixtures
    import functools
    import t5.models
    import seqio
    import torch
    import tensorflow_datasets as tfds
    from transformers import Adafactor
    
    
    model = t5.models.HfPyTorchModel("google/t5-v1_1-base", "/tmp" , torch.device("cuda"))
    
    TaskRegistry = seqio.TaskRegistry
    for b in tfds.text.glue.Glue.builder_configs.values():
         task = TaskRegistry.get("glue_%s_v002" % b.name)
         task.source._tfds_dataset._name = task.source._tfds_dataset._name.replace("1.0.0", "2.0.0")
    
    model.train(
         "glue_v002_proportional",
         262144,
         5000
         {"inputs": 512, "targets": 512},
         "train",
         16,
         functools.partial(Adafactor, lr=1e-3, relative_step=False),
            )
    
    OutOfMemoryError: CUDA out of memory. Tried to allocate 192.00 MiB (GPU 0; 31.75 GiB total capacity;
    2.71 GiB already allocated; 45.75 MiB free; 2.79 GiB reserved in total by PyTorch) If reserved 
    memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.
    
    opened by fadebek1 0
  • model.finetune(...) does not show the loss of the model

    model.finetune(...) does not show the loss of the model

    Hello,

    I just ran the following jupyter notebook: t5-trivia.ipynb and it works well, however, when I run model.finetune(...) does not show the loss of the model.

    Any idea how I can solve it?

    Besides, I add the output I got when I ran the fine-tuning:

    INFO:root:system_path_file_exists:gs://t5-data/pretrained_models/base/operative_config.gin
    ERROR:root:Path not found: gs://t5-data/pretrained_models/base/operative_config.gin
    INFO:root:Skipping import of unknown module `t5.data.sentencepiece_vocabulary` (skip_unknown=True).
    From /usr/local/lib/python3.7/dist-packages/tensorflow/python/training/training_util.py:397: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
    Instructions for updating:
    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.
    WARNING:absl:Using an uncached FunctionDataset for training is not recommended since it often results in insufficient shuffling on restarts, resulting in overfitting. It is highly recommended that you cache this task before training with it or use a data source that supports lower-level shuffling (e.g., FileDataSource).
    INFO:absl:Load dataset info from gs://sql-alias/models/data/trivia_qa/unfiltered.nocontext/1.1.0
    INFO:absl:Reusing dataset trivia_qa (gs://sql-alias/models/data/trivia_qa/unfiltered.nocontext/1.1.0)
    INFO:absl:Constructing tf.data.Dataset trivia_qa for split train, from gs://sql-alias/models/data/trivia_qa/unfiltered.nocontext/1.1.0
    From /usr/local/lib/python3.7/dist-packages/seqio/dataset_providers.py:1479: sample_from_datasets_v2 (from tensorflow.python.data.experimental.ops.interleave_ops) is deprecated and will be removed in a future version.
    Instructions for updating:
    Use `tf.data.Dataset.sample_from_datasets(...)`.
    SimdMeshImpl ignoring devices ['', '', '', '', '', '', '', '']
    Using default tf glorot_uniform_initializer for variable encoder/block_000/layer_000/SelfAttention/relative_attention_bias  The initialzer will guess the input and output dimensions  based on dimension order.
    Using default tf glorot_uniform_initializer for variable decoder/block_000/layer_000/SelfAttention/relative_attention_bias  The initialzer will guess the input and output dimensions  based on dimension order.
    From /usr/local/lib/python3.7/dist-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py:758: Variable.load (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
    Instructions for updating:
    Prefer Variable.assign which has equivalent behavior in 2.X.
    

    Thank you

    opened by JessicaLopezEspejel 6
  • How should I speed up T5 exported saved_model by using TF-TRT ?

    How should I speed up T5 exported saved_model by using TF-TRT ?

    THE ISSUES SECTION IS ONLY FOR FILING BUGS. PLEASE ASK YOUR QUESTION ON THE DISCUSSION TAB. My env:

    Docker image: nvcr.io/nvidia/tensorflow:22.05-tf2-py3, TRT: 8.2.5.1, CUDA: 11.7 tf 2.8

    The original saved_model tooks 300ms when batch_size=32 and sen_length=128, it's too long for deploy. So I wanted to speed up t5 by using tf-trt. But when I convert saved_model using below code, tf-trt doesn't work:

    from tensorflow.python.compiler.tensorrt import trt_convert as trt
    import numpy as np
    import tensorflow_text
    import tensorflow as tf
    
    tf.compat.v1.disable_v2_behavior()
    
    input_saved_model_dir = 'exported_model/batch32_length128_0810/1660123651'
    output_saved_model_dir = 'trt_saved_model/batch32_length128_0810/1/'
    converter = trt.TrtGraphConverter(
        input_saved_model_dir=input_saved_model_dir,
        max_workspace_size_bytes=(11<32),
        max_batch_size=32,
        minimum_segment_size=50,
        precision_mode='FP32',
        is_dynamic_op=True,
        maximum_cached_engines=1)
    
    converter.convert()
    converter.save(output_saved_model_dir)
    
    

    Before using the code, you should add some code in tensorflow/python/compiler/tensorrt/trt_convert.py. The reference is here Could some body help me about this?

    opened by chenl-keep 0
  • using A100(40G)*8 gpus server to train T5-3b,it reports OOM resource is exhausted problem

    using A100(40G)*8 gpus server to train T5-3b,it reports OOM resource is exhausted problem

    Why ?I used model:8 batch 1 settings and 8 batchsize {input:1024, output:512}, there is still a OOM。 But I see Pytorch can train T5-3b at V100 32G * 8 , whether It was caused by Mesh-tensorflow‘s less efficient than deepspeed?? I want to figure out the problem?? actually I want use T5 because Tensorflow is easy for deployment. Why deepspeed can train larger model than mesh_tensorflow????

    opened by flyingwaters 0
Releases(v0.4.0)
Code to use Augmented Shapiro Wilks Stopping, as well as code for the paper "Statistically Signifigant Stopping of Neural Network Training"

This codebase is being actively maintained, please create and issue if you have issues using it Basics All data files are included under losses and ea

Justin Terry 32 Nov 9, 2021
Code of paper: A Recurrent Vision-and-Language BERT for Navigation

Recurrent VLN-BERT Code of the Recurrent-VLN-BERT paper: A Recurrent Vision-and-Language BERT for Navigation Yicong Hong, Qi Wu, Yuankai Qi, Cristian

YicongHong 109 Dec 21, 2022
Code associated with the "Data Augmentation using Pre-trained Transformer Models" paper

Data Augmentation using Pre-trained Transformer Models Code associated with the Data Augmentation using Pre-trained Transformer Models paper Code cont

null 44 Dec 31, 2022
Code for CVPR 2021 paper: Revamping Cross-Modal Recipe Retrieval with Hierarchical Transformers and Self-supervised Learning

Revamping Cross-Modal Recipe Retrieval with Hierarchical Transformers and Self-supervised Learning This is the PyTorch companion code for the paper: A

Amazon 69 Jan 3, 2023
This repository will contain the code for the CVPR 2021 paper "GIRAFFE: Representing Scenes as Compositional Generative Neural Feature Fields"

GIRAFFE: Representing Scenes as Compositional Generative Neural Feature Fields Project Page | Paper | Supplementary | Video | Slides | Blog | Talk If

null 1.1k Dec 27, 2022
Code for ACL 2021 main conference paper "Conversations are not Flat: Modeling the Intrinsic Information Flow between Dialogue Utterances".

Conversations are not Flat: Modeling the Intrinsic Information Flow between Dialogue Utterances This repository contains the code and pre-trained mode

ICTNLP 90 Dec 27, 2022
Code from the paper "High-Performance Brain-to-Text Communication via Handwriting"

Code from the paper "High-Performance Brain-to-Text Communication via Handwriting"

Francis R. Willett 305 Dec 22, 2022
source code for paper: WhiteningBERT: An Easy Unsupervised Sentence Embedding Approach.

WhiteningBERT Source code and data for paper WhiteningBERT: An Easy Unsupervised Sentence Embedding Approach. Preparation git clone https://github.com

null 49 Dec 17, 2022
Pytorch code for ICRA'21 paper: "Hierarchical Cross-Modal Agent for Robotics Vision-and-Language Navigation"

Hierarchical Cross-Modal Agent for Robotics Vision-and-Language Navigation This repository is the pytorch implementation of our paper: Hierarchical Cr

null 44 Jan 6, 2023
Code for our paper "Mask-Align: Self-Supervised Neural Word Alignment" in ACL 2021

Mask-Align: Self-Supervised Neural Word Alignment This is the implementation of our work Mask-Align: Self-Supervised Neural Word Alignment. @inproceed

THUNLP-MT 46 Dec 15, 2022
Code for our ACL 2021 paper - ConSERT: A Contrastive Framework for Self-Supervised Sentence Representation Transfer

ConSERT Code for our ACL 2021 paper - ConSERT: A Contrastive Framework for Self-Supervised Sentence Representation Transfer Requirements torch==1.6.0

Yan Yuanmeng 478 Dec 25, 2022
Code for our ACL 2021 (Findings) Paper - Fingerprinting Fine-tuned Language Models in the wild .

?? Fingerprinting Fine-tuned Language Models in the wild This is the code and dataset for our ACL 2021 (Findings) Paper - Fingerprinting Fine-tuned La

LCS2-IIITDelhi 5 Sep 13, 2022
Code for our paper "Transfer Learning for Sequence Generation: from Single-source to Multi-source" in ACL 2021.

TRICE: a task-agnostic transferring framework for multi-source sequence generation This is the source code of our work Transfer Learning for Sequence

THUNLP-MT 9 Jun 27, 2022
Code and datasets for our paper "PTR: Prompt Tuning with Rules for Text Classification"

PTR Code and datasets for our paper "PTR: Prompt Tuning with Rules for Text Classification" If you use the code, please cite the following paper: @art

THUNLP 118 Dec 30, 2022
null 189 Jan 2, 2023
Code for paper "Which Training Methods for GANs do actually Converge? (ICML 2018)"

GAN stability This repository contains the experiments in the supplementary material for the paper Which Training Methods for GANs do actually Converg

Lars Mescheder 884 Nov 11, 2022
This is the code for the EMNLP 2021 paper AEDA: An Easier Data Augmentation Technique for Text Classification

The baseline code is for EDA: Easy Data Augmentation techniques for boosting performance on text classification tasks

Akbar Karimi 81 Dec 9, 2022
This repository contains the code for EMNLP-2021 paper "Word-Level Coreference Resolution"

Word-Level Coreference Resolution This is a repository with the code to reproduce the experiments described in the paper of the same name, which was a

null 79 Dec 27, 2022