Question on how to pass pretrained parameters to a self-defined optimizer
🐛 Bug
Hi, group,
I am new to fairseq. I encounter a problem in deploying it. In my project, I have defined a new optimizer. I know the file should be put into fairseq/optimu/my_optimizer.py.
But the problem is that in my_optimizer.py, I have a new paprameter, as, pretrain_params=None.
We need to computer differences between pretrain_params and params.
My question is how I can pass pretrain_params to this optimizer. In huggingface, I can do the following, optimizer_grouped_parameters = [ { "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay) and args.model_type in n], "weight_decay": args.weight_decay, "anneal_w": args.recadam_anneal_w, "pretrain_params": [p_p for p_n, p_p in pretrained_model.named_parameters() if not any(nd in p_n for nd in no_decay) and args.model_type in p_n] }, ...,]
optimizer = my_optimizerr(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon, anneal_fun=args.recadam_anneal_fun, anneal_k=args.recadam_anneal_k, anneal_t0=args.recadam_anneal_t0, pretrain_cof=args.recadam_pretrain_cof)
Not sure where fairseq can do this? I tried to do this in fairseq/trainer.py. But not clear where we can load the pretrained_checkpoint.pt and pass it where for my_optimizer.py to consume.
May you guys help with this? Thanks in advance,
To Reproduce
Steps to reproduce the behavior (always include the command you ran):
- Run cmd '....'
- See error
Code sample
Expected behavior
Environment
- fairseq Version (e.g., 1.0 or master):
- PyTorch Version (e.g., 1.0)
- OS (e.g., Linux): linux
- How you installed fairseq (
pip, source): I am using the latest whole fairseq source package - Build command you used (if compiling from source): pip install editable .
- Python version: 3.6
- CUDA/cuDNN version: cuda 9
- GPU models and configuration: v100
- Any other relevant information:
Additional context
you can try using this:
https://github.com/pytorch/fairseq/blob/master/fairseq/optim/composite.py
you would have to mark parameters with their group name in your model
something like this:
for p in self.submodel.parameters():
p.param_group = "submodel"
then you can set up a composite config with different optimizer parameters, something like this:
optimizer:
_name: composite
groups:
default:
lr: [0.0004]
optimizer:
_name: adam
adam_betas: [0.5,0.98]
adam_eps: 1e-06
weight_decay: 0
lr_scheduler:
_name: fixed
warmup_updates: 0
submodel:
lr: [ 0.0005 ]
optimizer:
_name: adam
adam_betas: [0.5,0.98]
adam_eps: 1e-06
weight_decay: 0.0001
lr_scheduler:
_name: fixed
warmup_updates: 0
lr_scheduler: pass_through
Thanks for your nice answer. Yet, I am still not sure how we can handle this. Now, what I am doing is directly load pretrained model from my_optimizer. But I found that loaded parameters cannot match running parameters. Not sure if I can call some function to make loaded params be consistent with running parameters. The following lines are how I load my pretrained model parameters,
from fairseq.models.bart import BARTModel pretrained_model = BARTModel.from_pretrained(model_name_or_path=model_name_or_path, checkpoint_file=pretrained_ckpt) pretrain_params = [p_p for p_n, p_p in pretrained_model.state_dict().items()]
In [178]: total_length = 0 ...: for para in pretrain_params: ...: shape = list(para.size()) ...: j = 1 ...: for i in shape: ...: j *= i ...: total_length += j
In [178]: total_length
Out[178]: 509284441
The total length of running params is: 406290432.
May you give me more guidance?
Thanks a lot,
If we can read running parameters with their full dictionary values, then, we can easily do operations on both sets of parameters. That would be great!
Hey, it looks that the problem lies in pretrained_model = BARTModel.from_pretrained(model_name_or_path=model_name_or_path. right now, I changed the strategy. I define a function to use running model to load pretrained model.
def get_pretrained_model_paras(self):
load_on_all_ranks = True
#filename = self.cfg.task.finetune_from_model # something similar
print(self.cfg)
#self.cfg.task = 'translation'
#self.cfg.model = 'bart_large'
task = tasks.get_task(self.cfg.task)
model = task.build_model(self.cfg, self.cfg.task)
filename = self.cfg.model_name_or_path + '/' + self.cfg.pretrained_ckpt
state = checkpoint_utils.load_checkpoint_to_cpu(
filename, load_on_all_ranks=load_on_all_ranks
)
model.load_state_dict(state["model"], strict = True, model_cfg = self.cfg.model)
params = list(
filter(
lambda p: p.requires_grad,
chain(self.model.parameters(), self.criterion.parameters()),
)
) # from def _build_optimizer(self)
return params
However, I encounter a problem in build_model. It complains that,
TypeError: super(type, obj): obj must be an instance or subtype of type.
What can I do in order to fix the error? Thanks,
the signature of build_model is:
def build_model(self, cfg: FairseqDataclass):
where cfg is the model config. so you need to call it like this:
task.build_model(cfg.model)
Hey, I already found the solution to this part.
Let me copy my scripts here. In future, if others need this, it may help them as well. Great thanks for your help!
my_optimizer.py
import logging import math from collections.abc import Collection from dataclasses import dataclass, field import argparse import numpy as np import torch import torch.distributed as dist import torch.optim from fairseq.dataclass import FairseqDataclass from fairseq.optim import FairseqOptimizer, register_optimizer from fairseq.optim.fused_adam import get_fused_adam_class from omegaconf import II, DictConfig from fairseq import checkpoint_utils from fairseq import options from itertools import chain from fairseq import tasks from fairseq.dataclass.utils import convert_namespace_to_omegaconf from typing import Dict, Optional, Any, List, Tuple, Callable logger = logging.getLogger(name)
def get_pretrained_model_paras(self): load_on_all_ranks = True #task = tasks.setup_task(self.cfg.task) #model = task.build_model(self.cfg.model) #filename = self.cfg.task.finetune_from_model # something similar print(self.cfg) modify_parser: Optional[Callable[[argparse.ArgumentParser], None]] = None parser = options.get_training_parser() args = options.parse_args_and_arch(parser, modify_parser=modify_parser) cfg = convert_namespace_to_omegaconf(args) #self.cfg.task = 'translation' #self.cfg.model = 'bart_large' #cfg = convert_namespace_to_omegaconf(self.cfg) #task = tasks.get_task('translation') task = tasks.setup_task(cfg.task) #cls = task.setup_task(self.cfg) #task = tasks.setup_task(cfg.task) model = task.build_model(cfg.model) criterion = task.build_criterion(cfg.model) filename = self.cfg.model_name_or_path + '/' + self.cfg.pretrained_ckpt state = checkpoint_utils.load_checkpoint_to_cpu( filename, load_on_all_ranks=load_on_all_ranks ) model.load_state_dict(state["model"], strict = True, model_cfg = cfg.model) params = list( filter( lambda p: p.requires_grad, chain(model.parameters(), criterion.parameters()), ) ) # from def _build_optimizer(self) return params
On Fri, Feb 12, 2021 at 12:02 PM Alexei Baevski [email protected] wrote:
the signature of build_model is:
def build_model(self, cfg: FairseqDataclass):
where cfg is the model config. so you need to call it like this:
task.build_model(cfg.model)
— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/pytorch/fairseq/issues/3225#issuecomment-778422531, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAO7YZHWJQC73Z34ZEPTOHDS6WCLRANCNFSM4XLJVEUA .
But I have a question here is that it looks that in the optimizer function as following, class FairseqAdam(FairseqOptimizer): """Adam optimizer for fairseq.
Important note: this optimizer corresponds to the "AdamW" variant of
Adam in its weight decay behavior. As such, it is most closely
analogous to torch.optim.AdamW from PyTorch.
"""
def __init__(self, cfg: DictConfig, params):
the data type of params can be a list of flatten vector or a list of tensors. I wonder whether there is a parameter for us to determine which one? thanks,
After more investigation for a while, I found that the flatten is controlled by --fp16. Basically, in fairseq/optim/fp16-optimizer.py, there is a function as below.
@classmethod
def build_fp32_params(cls, args, params, flatten=True):
# create FP32 copy of parameters and grads
if flatten:
is_pipeline_parallel = getattr(
args, "pipeline_model_parallel", False
) and getattr(args, "distributed_no_spawn", False)
total_param_size = sum(p.data.numel() for p in params)
#devices = [torch.cuda.current_device()]
devices = [torch.device('cpu')]
if is_pipeline_parallel:
devices = list(set(args.pipeline_devices))
fp32_params = {}
for device in devices:
if is_pipeline_parallel:
device_param_size = sum(
p.data.numel() for p in params if p.device.index == device
)
device_params = [p for p in params if p.device.index == device]
else:
device_param_size = total_param_size
device_params = params
fp32_params[device] = (
device_params[0].new(0).float().new(device_param_size)
)
offset = 0
for p in device_params:
numel = p.data.numel()
fp32_params[device][offset : offset + numel].copy_(p.data.view(-1))
offset += numel
fp32_params[device] = torch.nn.Parameter(fp32_params[device])
fp32_params[device].grad = fp32_params[device].data.new(
device_param_size
)
return fp32_params
else:
fp32_params = []
for p in params:
p32 = torch.nn.Parameter(p.data.float())
p32.grad = torch.zeros_like(p32.data)
if hasattr(p, "param_group"):
p32.param_group = p.param_group
fp32_params.append(p32)
return fp32_params
In build_optimizer of the script, whether flatten or not is controlled by the following bool.
flatten = not getattr(cfg.common, "fp16_no_flatten_grads", False)
I tried to use similar way to do the flatten for my reading of pretrained params. But I found the following line is quite slow. I am curious about how I can efficiently do this.
params = list(
filter(
lambda p: p.requires_grad,
chain(model.parameters(), criterion.parameters()),
)
) # from def _build_optimizer(self)
#if all(isinstance(p, dict) for p in params):
# params = [t for p in params for t in p.values()]
params = [torch.flatten(p) for p in params]
**_params = list(chain(*filter(lambda p: p.requires_grad, params)))_**
Thanks,
Hey, I finally figure out how to efficiently get a flattened params. Based on build_fp32_params of fairseq/optim/fp16_optimzer.py, I changed my function as following. It can efficiently obtained the flattened pretrained parameters in about 30 seconds. That is awesome!
def get_pretrained_model_paras(self):
load_on_all_ranks = True
modify_parser: Optional[Callable[[argparse.ArgumentParser], None]] = None
parser = options.get_training_parser()
args = options.parse_args_and_arch(parser, modify_parser=modify_parser)
cfg = convert_namespace_to_omegaconf(args)
task = tasks.setup_task(cfg.task)
model = task.build_model(cfg.model)
criterion = task.build_criterion(cfg.model)
filename = self.cfg.model_name_or_path + '/' + self.cfg.pretrained_ckpt
state = checkpoint_utils.load_checkpoint_to_cpu(
filename, load_on_all_ranks=load_on_all_ranks
)
model.load_state_dict(state["model"], strict = True, model_cfg = cfg.model)
params = list(
filter(
lambda p: p.requires_grad,
chain(model.parameters(), criterion.parameters()),
)
)
device_params = params
total_param_size = sum(p.data.numel() for p in params)
total_params = (
device_params[0].new(0).float().new(total_param_size)
)
offset = 0
for p in device_params:
numel = p.data.numel()
total_params[offset: offset + numel].copy_(p.data.view(-1))
offset += numel
total_params = torch.nn.Parameter(total_params)
total_params.grad = total_params.data.new(
total_param_size
)
return total_params