image2text

Untitled

Jul 28th, 2019
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. LA X ]
  2. # Welcome PyTorch-Transformers (formely known as pytorch-pretrained-bert)!
  3. import torch
  4. from pytorch_transformers import *
  5. # Simple and standard API for 6 transformer architectures & 27 pretrained model weights:
  6. MODELS = [(BertModel, R I EI LT 'bert-base-uncased'),
  7. (OpenAIGPTModel, OpenAIGPTTokenizer, 'openai-gpt'),
  8. (GPT2Model, GPT2Tokentizer, o[l
  9. (TransfoXLModel, TransfoXLTokenizer, 'transfo-x1-wt103'),
  10. (XLNetModel, XLNetTokenizer, 'xlnet-base-cased'),
  11. (XLMModel, XLMTokentizer, ‘xlm-mlm-enfr-1024")]
  12. # Let's encode some text in a sequence of hidden-states using each model:
  13. for model_class, tokenizer_class, pretrained_weights in MODELS:
  14. # Load pretrained model/tokenizer
  15. tokenizer = tokenizer_class.from_pretrained(pretrained_weights)
  16. model = model_class.from_pretrained(pretrained_weights)
  17. # Encode text
  18. input_ids = torch.tensor([tokenizer.encode("Here is some text to encode")])
  19. last_hidden_states = model(input_ids)[0] # Models outputs are now tuples
  20. # Models can return full list of hidden-states & attentions weights at each layer
  21. model = model_class.from_pretrained(pretrained_weights,
  22. output_hidden_states=True,
  23. output_attentions=True)
  24. input_ids = torch.tensor([tokenizer.encode("Let's see hidden-states and attentions")])
  25. all_hidden_states, all_attentions = model(input_ids)[-2:]
  26. # Models are compatible with Torchscript
  27. model = model_class.from_pretrained(pretrained_weights, torchscript=True)
  28. traced_model = torch.jit.trace(model, (input_ids,))
  29. # Simple serialization for models and tokenizers
  30. model.save_pretrained('./directory/to/save/') # save
  31. model = model_class.from_pretrained('./directory/to/save/') # re-load
  32. # SOTA examples for GLUE, SQUAD, text generation...
Advertisement
Add Comment
Please, Sign In to add comment