* Add pip install update to resolve import error
Add pip install upgrade tensorflow-gpu to remove error below:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-094fadb93f3f> in <module>()
1 import torch
----> 2 from transformers import AutoModel, AutoTokenizer, BertTokenizer
3
4 torch.set_grad_enabled(False)
4 frames
/usr/local/lib/python3.6/dist-packages/transformers/__init__.py in <module>()
133
134 # Pipelines
--> 135 from .pipelines import (
136 Conversation,
137 ConversationalPipeline,
/usr/local/lib/python3.6/dist-packages/transformers/pipelines.py in <module>()
46 import tensorflow as tf
47
---> 48 from .modeling_tf_auto import (
49 TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
50 TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
/usr/local/lib/python3.6/dist-packages/transformers/modeling_tf_auto.py in <module>()
49 from .configuration_utils import PretrainedConfig
50 from .file_utils import add_start_docstrings
---> 51 from .modeling_tf_albert import (
52 TFAlbertForMaskedLM,
53 TFAlbertForMultipleChoice,
/usr/local/lib/python3.6/dist-packages/transformers/modeling_tf_albert.py in <module>()
22 import tensorflow as tf
23
---> 24 from .activations_tf import get_tf_activation
25 from .configuration_albert import AlbertConfig
26 from .file_utils import (
/usr/local/lib/python3.6/dist-packages/transformers/activations_tf.py in <module>()
52 "gelu": tf.keras.layers.Activation(gelu),
53 "relu": tf.keras.activations.relu,
---> 54 "swish": tf.keras.activations.swish,
55 "silu": tf.keras.activations.swish,
56 "gelu_new": tf.keras.layers.Activation(gelu_new),
AttributeError: module 'tensorflow_core.python.keras.api._v2.keras.activations' has no attribute 'swish'
```
I have tried running the colab after this change and it seems to work fine (all the cells run with no errors).
* Update notebooks/02-transformers.ipynb
only need to upgrade tensorflow, not tensorflow-gpu.
Co-authored-by: Lysandre Debut <lysandre@huggingface.co>
Co-authored-by: Lysandre Debut <lysandre@huggingface.co>
22 KiB
22 KiB
In [ ]:
!pip install transformers
!pip install --upgrade tensorflowIn [2]:
import torch
from transformers import AutoModel, AutoTokenizer, BertTokenizer
torch.set_grad_enabled(False)Out [2]:
<torch.autograd.grad_mode.set_grad_enabled at 0x7f10b441e890>
In [3]:
# Store the model we want to use
MODEL_NAME = "bert-base-cased"
# We need to create the model and tokenizer
model = AutoModel.from_pretrained(MODEL_NAME)
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)In [4]:
# Tokens comes from a process that splits the input into sub-entities with interesting linguistic properties.
tokens = tokenizer.tokenize("This is an input example")
print("Tokens: {}".format(tokens))
# This is not sufficient for the model, as it requires integers as input,
# not a problem, let's convert tokens to ids.
tokens_ids = tokenizer.convert_tokens_to_ids(tokens)
print("Tokens id: {}".format(tokens_ids))
# Add the required special tokens
tokens_ids = tokenizer.build_inputs_with_special_tokens(tokens_ids)
# We need to convert to a Deep Learning framework specific format, let's use PyTorch for now.
tokens_pt = torch.tensor([tokens_ids])
print("Tokens PyTorch: {}".format(tokens_pt))
# Now we're ready to go through BERT with out input
outputs, pooled = model(tokens_pt)
print("Token wise output: {}, Pooled output: {}".format(outputs.shape, pooled.shape))Tokens: ['This', 'is', 'an', 'input', 'example'] Tokens id: [1188, 1110, 1126, 7758, 1859] Tokens PyTorch: tensor([[ 101, 1188, 1110, 1126, 7758, 1859, 102]]) Token wise output: torch.Size([1, 7, 768]), Pooled output: torch.Size([1, 768])
In [5]:
# tokens = tokenizer.tokenize("This is an input example")
# tokens_ids = tokenizer.convert_tokens_to_ids(tokens)
# tokens_pt = torch.tensor([tokens_ids])
# This code can be factored into one-line as follow
tokens_pt2 = tokenizer("This is an input example", return_tensors="pt")
for key, value in tokens_pt2.items():
print("{}:\n\t{}".format(key, value))
outputs2, pooled2 = model(**tokens_pt2)
print("Difference with previous code: ({}, {})".format((outputs2 - outputs).sum(), (pooled2 - pooled).sum()))input_ids: tensor([[ 101, 1188, 1110, 1126, 7758, 1859, 102]]) token_type_ids: tensor([[0, 0, 0, 0, 0, 0, 0]]) attention_mask: tensor([[1, 1, 1, 1, 1, 1, 1]]) Difference with previous code: (0.0, 0.0)
In [6]:
# Single segment input
single_seg_input = tokenizer("This is a sample input")
# Multiple segment input
multi_seg_input = tokenizer("This is segment A", "This is segment B")
print("Single segment token (str): {}".format(tokenizer.convert_ids_to_tokens(single_seg_input['input_ids'])))
print("Single segment token (int): {}".format(single_seg_input['input_ids']))
print("Single segment type : {}".format(single_seg_input['token_type_ids']))
# Segments are concatened in the input to the model, with
print()
print("Multi segment token (str): {}".format(tokenizer.convert_ids_to_tokens(multi_seg_input['input_ids'])))
print("Multi segment token (int): {}".format(multi_seg_input['input_ids']))
print("Multi segment type : {}".format(multi_seg_input['token_type_ids']))Single segment token (str): ['[CLS]', 'This', 'is', 'a', 'sample', 'input', '[SEP]'] Single segment token (int): [101, 1188, 1110, 170, 6876, 7758, 102] Single segment type : [0, 0, 0, 0, 0, 0, 0] Multi segment token (str): ['[CLS]', 'This', 'is', 'segment', 'A', '[SEP]', 'This', 'is', 'segment', 'B', '[SEP]'] Multi segment token (int): [101, 1188, 1110, 6441, 138, 102, 1188, 1110, 6441, 139, 102] Multi segment type : [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
In [7]:
# Padding highlight
tokens = tokenizer(
["This is a sample", "This is another longer sample text"],
padding=True # First sentence will have some PADDED tokens to match second sequence length
)
for i in range(2):
print("Tokens (int) : {}".format(tokens['input_ids'][i]))
print("Tokens (str) : {}".format([tokenizer.convert_ids_to_tokens(s) for s in tokens['input_ids'][i]]))
print("Tokens (attn_mask): {}".format(tokens['attention_mask'][i]))
print()Tokens (int) : [101, 1188, 1110, 170, 6876, 102, 0, 0] Tokens (str) : ['[CLS]', 'This', 'is', 'a', 'sample', '[SEP]', '[PAD]', '[PAD]'] Tokens (attn_mask): [1, 1, 1, 1, 1, 1, 0, 0] Tokens (int) : [101, 1188, 1110, 1330, 2039, 6876, 3087, 102] Tokens (str) : ['[CLS]', 'This', 'is', 'another', 'longer', 'sample', 'text', '[SEP]'] Tokens (attn_mask): [1, 1, 1, 1, 1, 1, 1, 1]
In [8]:
from transformers import TFBertModel, BertModel
# Let's load a BERT model for TensorFlow and PyTorch
model_tf = TFBertModel.from_pretrained('bert-base-cased')
model_pt = BertModel.from_pretrained('bert-base-cased')In [9]:
# transformers generates a ready to use dictionary with all the required parameters for the specific framework.
input_tf = tokenizer("This is a sample input", return_tensors="tf")
input_pt = tokenizer("This is a sample input", return_tensors="pt")
# Let's compare the outputs
output_tf, output_pt = model_tf(input_tf), model_pt(**input_pt)
# Models outputs 2 values (The value for each tokens, the pooled representation of the input sentence)
# Here we compare the output differences between PyTorch and TensorFlow.
for name, o_tf, o_pt in zip(["output", "pooled"], output_tf, output_pt):
print("{} differences: {:.5}".format(name, (o_tf.numpy() - o_pt.numpy()).sum()))output differences: 1.6236e-05 pooled differences: -1.3039e-08
In [10]:
from transformers import DistilBertModel
bert_distil = DistilBertModel.from_pretrained('distilbert-base-cased')
input_pt = tokenizer(
'This is a sample input to demonstrate performance of distiled models especially inference time',
return_tensors="pt"
)
%time _ = bert_distil(input_pt['input_ids'])
%time _ = model_pt(input_pt['input_ids'])CPU times: user 232 ms, sys: 0 ns, total: 232 ms Wall time: 21.1 ms CPU times: user 511 ms, sys: 0 ns, total: 511 ms Wall time: 43.9 ms
In [11]:
# Let's load German BERT from the Bavarian State Library
de_bert = BertModel.from_pretrained("dbmdz/bert-base-german-cased")
de_tokenizer = BertTokenizer.from_pretrained("dbmdz/bert-base-german-cased")
de_input = de_tokenizer(
"Hugging Face ist eine französische Firma mit Sitz in New-York.",
return_tensors="pt"
)
print("Tokens (int) : {}".format(de_input['input_ids'].tolist()[0]))
print("Tokens (str) : {}".format([de_tokenizer.convert_ids_to_tokens(s) for s in de_input['input_ids'].tolist()[0]]))
print("Tokens (attn_mask): {}".format(de_input['attention_mask'].tolist()[0]))
print()
output_de, pooled_de = de_bert(**de_input)
print("Token wise output: {}, Pooled output: {}".format(outputs.shape, pooled.shape))Tokens (int) : [102, 12272, 9355, 5746, 30881, 215, 261, 5945, 4118, 212, 2414, 153, 1942, 232, 3532, 566, 103] Tokens (str) : ['[CLS]', 'Hug', '##ging', 'Fac', '##e', 'ist', 'eine', 'französische', 'Firma', 'mit', 'Sitz', 'in', 'New', '-', 'York', '.', '[SEP]'] Tokens (attn_mask): [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] Token wise output: torch.Size([1, 7, 768]), Pooled output: torch.Size([1, 768])



