Coder Social home page Coder Social logo

microsoft / mutransformers Goto Github PK

View Code? Open in Web Editor NEW
65.0 5.0 10.0 2.41 MB

some common Huggingface transformers in maximal update parametrization (µP)

Home Page: https://arxiv.org/abs/2203.03466

License: MIT License

Python 22.59% Jupyter Notebook 77.41%

mutransformers's Introduction

muTransformers

This repo implements muP (paper) for selected PyTorch models in Huggingface Transformers. The primary purpose of this repo is as a clean demonstration of how to inject muP into different variants of transformers. As a secondary purpose, one can also use the models here as provided.

Installation

Go to this project directory and do

pip install -r requirements.txt
pip install -e .

Injecting muP into Existing Transformers

Taking BERT as an example, there are two files modeling_bert.py and configuration_bert.py in mutransformers/models/bert/ we copied from Huggingface Transformers and made a small number of modifications to implement muP. Our modifications in these files can all be found by searching for ### muP.

These files are copied from Huggingface Transformers v4.16.2. We provide the original files as _original_*.py for easy comparison, for example, _original_modeling_bert.py.

Coord Check

Coordinate checking is a way of verifying that muP is implemented correctly just like gradient checking is a way of verifying that autograd is implemented correctly. You can find the coord check results in tests/coordcheck/CoordCheck.ipynb. You can rerun the notebook yourself as well after installation.

For example, the coord check for BERT in standard parametrization (SP) shows many activations blow up with width, but the same for BERT in muP shows activation scale consistent with width.

Basic Usage of Models

The models here can be used for your training purposes as well, though we have not made sure to replicate the original numbers of each of these transformer models. The models in this package can be used as follows, taking BERT as an example:

from mutransformers import BertConfig, BertForMaskedLM
from mup import make_base_shapes, set_base_shapes, MuAdamW
from functools import partial
# define a base model
base_config = BertConfig(
    hidden_size=256,
    intermediate_size=256,
    num_attention_heads=16,
)
base_model = BertForMaskedLM(config=base_config)
# define a delta models where we vary all "widths" we want to vary
delta_config = BertConfig(
    hidden_size=200,
    intermediate_size=300,
    num_attention_heads=5,
)
delta_model = BertForMaskedLM(config=delta_config)
# define a base shape object based on comparing delta_model against base_model
base_shapes = make_base_shapes(base_model, delta_model, savefile='bert256.bsh')

# define target model
target_config = BertConfig(
    hidden_size=1024,
    intermediate_size=1024*4,
    num_attention_heads=32,
)
target_model = BertForMaskedLM(config=target_config)

# set base shapes
set_base_shapes(target_model, base_shapes)
# you can alternatively load base shape from file
# set_base_shapes(target_model, 'bert256.bsh')

# re-initialize
target_model.apply(target_model._init_weights)

# make sure to use mup optimizers for training
optimizer = MuAdamW(target_model.parameters(), lr=1e-3)

# train
...

For more general information on how to use mup, see the muP package documentation.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

mutransformers's People

Contributors

microsoft-github-operations[bot] avatar microsoftopensource avatar thegregyang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

mutransformers's Issues

Differences between paper and actual implementation in _init_weight function

Hi, i have some questions about initialization function in _init_weights for every models(roberta, bert, gpt2).

In appendix B.1, it says that it is divided by d_model, but it is actually divided by d_model/d_model, 0 = width_mult. Why is it implemented like this?

Paper shown
image

implement code

def constant_std_init_(tensor, sampler_):
    assert hasattr(tensor, 'infshape'), 'Please call set_base_shapes(...)'
    if tensor.infshape.ninf() <= 1:
        sampler_(tensor)
    elif tensor.infshape.ninf() == 2:
        sampler_(tensor, scale=tensor.infshape.width_mult()**-0.5)
    else:
        raise NotImplementedError()
    return tensor

def normal_(tensor, mean=0, std=1):
    '''Drop-in replacement of `torch.nn.init.normal_`.
    Note:
        -  if using this function, ensure `mean` and `std` do not depend on
           fan-in, fan-out, or other notions of width, e.g. if mean = 0, std =
           1.
        - `tensor` should have `infshape` attribute set by `set_base_shapes`.
    '''
    if mean != 0:
        assert tensor.infshape.ninf() == 1, 'Sampler for (inf, inf) tensors should have mean 0'
    def sampler_(tensor, scale=1):
        _no_grad_normal_(tensor, mean=mean*scale, std=std*scale)
    return constant_std_init_(tensor, sampler_)

Additionally, I don't understand the application of Table 8 to Word unembedding. Why is it N(0, sigma^2 / d_model0)?
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.