transformers
61 строка · 2.1 Кб
1#!/usr/bin/env python
2# coding: utf-8
3# Copyright 2020 The HuggingFace Team. All rights reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# This script creates a super tiny model that is useful inside tests, when we just want to test that
18# the machinery works, without needing to the check the quality of the outcomes.
19#
20# This version creates a tiny model through reduction of a normal pre-trained model, but keeping the
21# full vocab, merges file, and thus also resulting in a larger model due to a large vocab size.
22# This gives ~3MB in total for all files.
23#
24# If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated
25#
26#
27# It will be used then as "stas/tiny-wmt19-en-de"
28
29# Build
30from transformers import FSMTConfig, FSMTForConditionalGeneration, FSMTTokenizer
31
32
33mname = "facebook/wmt19-en-de"
34tokenizer = FSMTTokenizer.from_pretrained(mname)
35# get the correct vocab sizes, etc. from the master model
36config = FSMTConfig.from_pretrained(mname)
37config.update({
38"d_model": 4,
39"encoder_layers": 1, "decoder_layers": 1,
40"encoder_ffn_dim": 4, "decoder_ffn_dim": 4,
41"encoder_attention_heads": 1, "decoder_attention_heads": 1})
42
43tiny_model = FSMTForConditionalGeneration(config)
44print(f"num of params {tiny_model.num_parameters()}")
45
46# Test
47batch = tokenizer(["Making tiny model"], return_tensors="pt")
48outputs = tiny_model(**batch)
49
50print("test output:", len(outputs.logits[0]))
51
52# Save
53mname_tiny = "tiny-wmt19-en-de"
54tiny_model.half() # makes it smaller
55tiny_model.save_pretrained(mname_tiny)
56tokenizer.save_pretrained(mname_tiny)
57
58print(f"Generated {mname_tiny}")
59
60# Upload
61# transformers-cli upload tiny-wmt19-en-de
62