Views
No views yet
1from transformers import AutoTokenizer, AutoModelWithLMHead
2import torch
3
4tokenizer = AutoTokenizer.from_pretrained("gorkemgoknar/gpt2-turkish-writer")
5model = AutoModelWithLMHead.from_pretrained("gorkemgoknar/gpt2-turkish-writer")
6
7# Get sequence length max of 1024
8tokenizer.model_max_length=1024
9
10model.eval() # disable dropout (or leave in train mode to finetune)
111# input sequence
2text = "Bu yazıyı bilgisayar yazdı."
3inputs = tokenizer(text, return_tensors="pt")
4
5# model output
6outputs = model(**inputs, labels=inputs["input_ids"])
7loss, logits = outputs[:2]
8predicted_index = torch.argmax(logits[0, -1, :]).item()
9predicted_text = tokenizer.decode([predicted_index])
10
11# results
12print('input text:', text)
13print('predicted text:', predicted_text)
14
15# input text:
16# predicted text:
171# input sequence
2text = "Bu yazıyı bilgisayar yazdı."
3inputs = tokenizer(text, return_tensors="pt")
4
5# model output using Top-k sampling text generation method
6sample_outputs = model.generate(inputs.input_ids,
7 pad_token_id=50256,
8 do_sample=True,
9 max_length=50, # put the token number you want
10 top_k=40,
11 num_return_sequences=1)
12
13# generated sequence
14for i, sample_output in enumerate(sample_outputs):
15 print(">> Generated text {}\n\n{}".format(i+1, tokenizer.decode(sample_output.tolist())))
16
17# >> Generated text
18#
19| epoch | train_loss | valid_loss | accuracy | perplexity | time |
|---|---|---|---|---|---|
| 0 | 4.497828 | 4.549605 | 0.277328 | 94.595070 | 2:09:58 |
| 1 | 4.503929 | 4.519456 | 0.275071 | 91.785645 | 2:04:30 |
| 2 | 3.612716 | 3.921146 | 0.344802 | 50.458256 | 2:03:22 |
| 3 | 3.777645 | 4.072006 | 0.326130 | 58.674530 | 1:56:14 |
| 4 | 2.934462 | 3.801303 | 0.363719 | 44.759476 | 1:58:55 |