File size: 6,758 Bytes
7e7a152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
"""Training uses the frozen common-v3 semantic messages and native observations."""
import copy,json,math
from pathlib import Path
from evaluation.fourtask_common_v3.contract import messages,parse_action

def track_for(profile,row):
 return 'vision_only' if not row.get('audio_path') or not profile['audio'] else 'vision_mono' if (profile['kind']=='omni' or profile.get('native_audio_track')=='vision_mono') else 'vision_stereo'

def waveform(row,track):
 if track=='vision_only':return None
 import numpy as np,soundfile as sf
 from scipy.signal import resample_poly
 with sf.SoundFile(row['audio_path']) as f:sr=f.samplerate;wave=f.read(frames=sr*10,dtype='float32',always_2d=True)
 assert wave.shape==(sr*10,2) and np.isfinite(wave).all()
 if track=='vision_mono':
  g=math.gcd(sr,16000);return resample_poly(wave.mean(1),16000//g,sr//g).astype(np.float32)
 from omini.data.staqa_preprocessing import prepare_staqa_waveform
 return prepare_staqa_waveform(wave,sr).cpu().numpy()

def batch(row,actor):
 import torch
 from training.hvs_audio_fourtask.data import load_image
 track=track_for(actor.profile,row)
 decision=int(row['id'].rsplit(':',1)[-1])+int(row.get('recovery_prefix_steps',0))+1
 pose=list(map(int,row['pose']));answer=row['answers'][0]
 assert parse_action(answer,pose) is not None
 ms=messages(row['instruction'],pose,row['history_actions'],decision,track)
 pics=[load_image(d) for d in row['observations']]
 assert len(pics)==len(row['history_actions'])+1
 audio=waveform(row,track)
 if hasattr(actor,'prepare_inputs'):
  b=actor.prepare_inputs(ms,pics,audio);n=b['input_ids'].shape[1]
  end='<turn|>' if actor.kind=='gemma4' else '<|im_end|>'
  eid=actor.proc.tokenizer.convert_tokens_to_ids(end);assert eid is not None and eid!=actor.proc.tokenizer.unk_token_id
  target=actor.proc.tokenizer.encode(answer,add_special_tokens=False)+[eid]
  b['input_ids']=torch.cat([b['input_ids'],torch.tensor([target])],1);b['attention_mask']=torch.ones_like(b['input_ids'])
  # Qwen2-VL's rotary-position path consumes ``mm_token_type_ids`` when
  # present.  Different transformer minor versions expose this tensor under
  # slightly different names, so extend every sequence-aligned processor
  # field rather than only the two historical names.  Leaving one field at
  # the prompt length makes the attention mask longer than the token-type
  # tensor and crashes in get_rope_index during full-parameter SFT.
  for k,v in list(b.items()):
   if not hasattr(v,'ndim'):continue
   if v.ndim == 2 and v.shape[0] == 1 and v.shape[1] == n:
    b[k]=torch.cat([v,torch.zeros((1,len(target)),dtype=v.dtype,device=v.device)],1)
   elif v.ndim == 1 and v.shape[0] == n:
    b[k]=torch.cat([v,torch.zeros((len(target),),dtype=v.dtype,device=v.device)],0)
  b['labels']=b['input_ids'].clone();b['labels'][:,:n]=-100
  assert b['input_ids'].shape[1]<=4096
  return b
 native=copy.deepcopy(ms)
 for m in native:
  if actor.kind=='omni' and isinstance(m['content'],str):m['content']=[dict(type='text',text=m['content'])]
  if isinstance(m['content'],list):
   for c in m['content']:
    if c['type']=='audio':
     if actor.kind=='omni':c.clear();c.update(type='audio',audio='canonical_10s_recording')
     else:c.clear();c.update(type='text',text='<|audio_start|>'+'<|audio_pad|>'*41+'<|audio_end|>')
 kw=dict(images=pics,return_tensors='pt',padding=True)
 if actor.kind=='omni':
  kw['images_kwargs']=dict(min_pixels=3136,max_pixels=65536)
  if audio is not None:kw.update(audio=[audio],audio_kwargs=dict(sampling_rate=16000,truncation=False,max_length=480000,return_attention_mask=True))
 text=actor.proc.apply_chat_template(native,tokenize=False,add_generation_prompt=True)
 b=dict(actor.proc(text=[text],**kw));n=b['input_ids'].shape[1]
 # Some Qwen2-VL processor revisions return mm_token_type_ids before
 # placeholder expansion (shorter than input_ids).  Normalize it to the
 # actual prompt length before appending the supervised action tokens.
 for k,v in list(b.items()):
  if not hasattr(v,'ndim') or v.ndim not in (1,2):continue
  m=v.shape[-1]
  if (v.ndim==2 and v.shape[0]==1 or v.ndim==1) and m!=n:
   if m<n:
    pad=torch.zeros((*v.shape[:-1],n-m),dtype=v.dtype,device=v.device);b[k]=torch.cat([v,pad],-1)
   else:b[k]=v[..., :n]
 target=actor.proc.tokenizer.encode(answer,add_special_tokens=False)+[actor.proc.tokenizer.convert_tokens_to_ids('<|im_end|>')]
 b['input_ids']=torch.cat([b['input_ids'],torch.tensor([target])],1);b['attention_mask']=torch.ones_like(b['input_ids'])
 b['labels']=b['input_ids'].clone();b['labels'][:,:n]=-100
 if audio is not None and actor.kind!='omni':b['audio']=torch.from_numpy(audio).unsqueeze(0)
 assert b['input_ids'].shape[1]<=4096
 return b

def configure(model,training=True):
 model.train(training)
 for key in ['freeze_audio_encoder','freeze_llm','freeze_vision_tower','freeze_vision_merger']:
  if hasattr(model.config,key):setattr(model.config,key,False)
 core=getattr(model,'llm',model)
 if training:core.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant':False})
 else:core.gradient_checkpointing_disable()
 for c in [core.config,getattr(core.config,'text_config',None)]:
  if c is not None:c.use_cache=not training

def save(model,path):
 from safetensors.torch import save_file
 path=Path(path);tmp=path.with_suffix('.tmp')
 save_file({k:v.detach().cpu().contiguous().clone() for k,v in model.state_dict().items()},str(tmp));tmp.replace(path)

def restore(model,path):
 from safetensors import safe_open
 import torch
 values=model.state_dict()
 with safe_open(str(path),framework='pt',device='cpu') as f:
  assert set(values)==set(f.keys())
  with torch.no_grad():
   for k,v in values.items():v.copy_(f.get_tensor(k).to(v))

class Optimizer:
 """FP32 master parameters/moments on host; train all model parameters."""
 def __init__(self,model,cfg):self.params=dict(model.named_parameters());self.state={};self.cfg=cfg
 def zero_grad(self):
  for p in self.params.values():p.grad=None
 def step(self,factor):
  import torch
  with torch.no_grad():
   for n,p in self.params.items():
    if p.grad is None:continue
    g=p.grad.detach().float().cpu()
    if n not in self.state:self.state[n]=dict(w=p.detach().float().cpu().clone(),m=torch.zeros_like(g),v=torch.zeros_like(g),t=0)
    s=self.state[n];s['t']+=1;s['m'].mul_(.9).add_(g,alpha=.1);s['v'].mul_(.999).addcmul_(g,g,value=.001)
    lr=self.cfg['vision_audio_learning_rate'] if any(k in n for k in ['visual.','audio_tower.','audio_encoder.','vision_tower.','vision_model.','multi_modal_projector.','encoder.']) else self.cfg['learning_rate']
    lr*=factor;den=s['v'].sqrt().div_(math.sqrt(1-.999**s['t'])).add_(1e-8)
    s['w'].mul_(1-lr*.01).addcdiv_(s['m'],den,value=-lr/(1-.9**s['t']));p.copy_(s['w'].to(p))