計算を行った動機
現在、自己回帰型の transformer の使い方が一般的で、驚異的な成果を上げている。しかし、推論時に低廉なシステムでより早く計算したいニーズがある場合、自己回帰型は不利である。そこで、自己回帰型でない計算で推論できるモデルを探していた。そんな時に、transformer-decoder のあとに crf 層をつけて計算すると、推論時に Viterbi アルゴリズムにより動的計画法で、自己回帰的ではない、非自己回帰型の推論計算が可能なことが分かった。
推論の計算速度は早く、隣り合った単語の繰り返しはないが、生成したキャプションの長さが短めで若干の n-gram の繰り返しが見られた。これを改善するためには、どうしたらよいか思案していた。LLM では、RLHF という強化学習で、人間の求める答えに近い回答をするように学習させているということを知っていた。そこで、とりあえず、強化学習を使ってキャプションの長さを長くすることはできないかと始めたのが、この強化学習である。初めての強化学習なので、足りない点も多々あるかと思いますが、よろしくおねがいします。
画像キャプショニングモデル。
画像キャプショニングモデルは、 CLIP + MLP_CONNECTOR + BERT + CRF 層 である。feature extracotor + encoder として 事前学習済の CLIP を使い、decorder としては事前学習済の BERT を用いた。両者をつなぐ MLP_CONNECTOR は、linear 層を 2 つと avg_pooling による シーケンス方向のダウンサンプリングを行っている。CLIP の出力の隠れ次元数が 1024 で BERT の隠れ次元数が 1024 なので、2つの linear 層では、次元数の変更は行っていない。
MLP_CONNECTOR については、Google の AIモードとかなり具体的な議論をしました。
ここでは、BERTの出力を nn.LayerNorm と nn.Linear に通して ( batch_size, seq_len, vocab_size )にしたものを放出確率 emissions とする。CRF 層では、シーケンス t -1 から t への遷移確率を導入し、放出確率+遷移確率が尤も大きくなるように学習する。CRF 層では、遷移確率に low_rank = 32 を導入して、遷移確率 E ( voacab_size, vocab_size ) を E1 ( vocab_size, low_rank ) * E2 (vocab_size, low_rank ) に分解して近似する。分解するメリットは、E のままだと、vocab_size = 30000 とかで、 vocab_size ** 2 のメモリーが必要であるが、 E1 E2 にすれば、2 * vocab_size * low_rank のメモリーで済む。また、尤度を計算するときの分母(分配関数)を計算するためには、時刻 t-1 のvocab_size個のラベルから 時刻tの V = vocab_size 個のラベルへの遷移確率を計算する必要がある。計算量は O( vocab_size * vocab_size )である。これを、時刻1 から Tについて計算するので、総計算量は、O( T * V * V )となります。そこで、beam = 256 を導入し、vocab_size のうち、放出確率が上位の beam = 256 のみを計算することにして、計算量を O( T * beam * beam ) にします。残りは、確率的に小さいので、寄与が少ないということで無視します。
SFT のモデル
強化学習を行う前に、モデルを v7 データセットを用いて、教師ありファインチューニングした。
CRF 層では、放出確率 emissions と 教師 caption を入力して、crf_loss を得る。crf_loss では、時刻 t における生成キャプション preds( t )が 教師キャプション caption( t )であるクロスエントロピー損失だけではなく、遷移確率を使って、preds( t-1, t ) と cpation( t-1, t )の遷移確率も考慮に入れて損失を計算する。 SFT では、emissions と教師キャプションのクロスエントロピーと crf_loss の和を損失として学習を行った。推論は、放出確率と学習した分解された遷移確率を使って Vitervi アルゴリズムによって行う。
SFT の学習
SFT の学習は、v7 データセットを使って、5エポック行った。学習中の loss, crf_loss, ce_loss, WER, BLEU のグラフを掲載する。
loss = crf_loss + 0.3 * ce_loss。 crf_loss は上述であり、ce_loss は、上述の放出確率 emissions と教師キャプションのクロスエントロピーロスである。 BLEU は、nltk の function 7 で計算している。5エポック学習後のテストでは、21個テストデータに対して、
test 21 average WER : 0.6775551576793031
test 21 average BLEU: 0.39627249627428923
であった。
強化学習モデル
放出確率 emissions を 確率的 Vieterbi サンプリング
でサンプリングすることにより、preds と sample_log_probs を計算し、preds を使って rewards, advantages を計算する。こちらでも、生成キャプションの推論は Viterbi アルゴリズムで行う。強化学習は、advantage の計算に GAE を用いた PPO のアルゴリズムで行った。GAE は、本来なら画像キャプショニングのモデルと同じネットワークをもう一つつくり、その最終 Linear 層だけ変えると良い。しかし、今回は、計算時間と計算資源の関係で、画像キャプショニングのモデルのネットワークを使い最終の Linear 層だけ修正して実現した。
報酬設計
報酬としては、cider, rougeL, clip_score, bert_score と、繰り返しによるペナルティ、生成した文章の長さによるペナルティ、ユニーク n-gram 比率を考慮した。
rewards = 1.0 * reward_ord + rep_coef * reward_repeat + len_coef * reward_length + unr_coef * reward_unr
ここで、reward_ord は reward_ordinary の略である。
reward_ord = 1.0 * reward_cider + rouge_coef * reward_rouge + clip_coef * clip_score + bert_coef * bert_score
である。
gae
critical_value は、crfの最終の beam_probs を nn.LayerNorm と nn.Linear(beam, 1 )に通した値です。gae_loss は、
targets = (clitical_value+ advantages).detach()
gae_loss = nn.MSELoss()( targets, critical_value )
を損失として、学習を行った。backward と step は、policy_loss と同時に行った。
advantages と advantages_norm
GAE と PPO については、Google の AI モードにかなり教わりました。
zeros = torch.zeros((critical_value.size(0), 1), device=critical_value.device, dtype=torch.float)
values_cat = torch.cat((critical_value, zeros), dim=1)
advantages = generalized_advantage_estimation(rewards_t, values_cat, gamma=config.gamma, lam=config.lam)
advantages_norm = (advantages - advantages.mean()) / (advantages.std() + eps) # bsz * seq_len
def generalized_advantage_estimation(rewards, values, gamma=0.99, lam=0.95):
B, T = rewards.size()
# 各タイムステップでのTD誤差 (delta_t) を計算
# delta_t = R_t + gamma * V(s_{t+1}) - V(s_t)
# values[:, :-1] は V(s_t)、values[:, 1:] は V(s_{t+1}) に対応
deltas = rewards + gamma * values[:, 1:] - values[:, :-1]
# deltas の形状は (B, T)
advantages = torch.zeros((B, T), device=rewards.device, dtype=torch.float)
# 最後のタイムステップのadvantageは delta_t そのもの
advantages[:, T-1] = deltas[:, T-1]
for t in range(T - 2, -1, -1):
advantages[:, t] = deltas[:, t] + gamma * lam * advantages[:, t+1]
return advantages
policy_loss
policy_loss は、sample_log_probs と一つ前の sample_log_probs を detach() した last_sample_log_probs を使って
ratio = torch.exp(sample_log_probs - last_sample_log_probs) # bsz * seq_len
policy_loss_1 = - advantages_norm * ratio
policy_loss_2 = - advantages_norm * torch.clamp(ratio, 1 - config.clip_range, 1 + config.clip_range)
policy_loss = - torch.min(policy_loss_1, policy_loss_2).mean() # bsz * seq_len の平均
で求めた。
損失
loss = 1.0 * policy_loss + ent_coef * entropy_loss + gae_coef * gae_loss + kl_coef * kl_div_loss + crf_coef * crf_loss + ce_coef * ce_loss
で求めた。entropy_loss は entropy を -1 倍したもの、kl_div_loss は、SFT のモデルで生成した probs からあまり離れないようにするための reference_model の selected_log_probsと 強化学習中の selected_log_probs の kl_diverggence loss である。crf_loss は、前述の crf_loss、 ce_loss は bert のemissions のクロスエントロピー損失である。
学習
最初は、Google の AI モードのアドバイスを聞きながら、パラメーターを調整していたが、一向に良いパラメーターセットが見つからない。そのうち、AI モードで Optuna のことを知ったので、Optuna を使ってパラメーターを詰めていくことにした。調整したパラメーターは、21個にのぼる。
パラメーターについて
パラメーターの一覧を掲載する。
lr_clip = 0.0 固定 clip は学習対象外フローズンとした。
lr_con = 1.66e-11 1 mlp_connector の学習率 本番学習の学習率は、第一回目の Optuna で見つかった学習率の 1/10 にしている。掲載は 1/10 を掲載している。
lr_bert = 2.19e-9 1 bert の学習率
lr_cri = 7.20e-6 1 gae の critical_value を計算する nn.LayerNorm と nn.Linear の学習率
lr_others = 5.82e-8 1 残り、CRF の E1, E2 パラメーターなどの学習率
weight_decay = 0.01 1 AdamW の weigth_decay
betas = (0.9, 0.999 ) 固定 AdamW の betas
warmup = 0.1 固定 線形学習率スケジューラーの全工程に対する warmup 比率
clip_range 2 PPO の ε
clip_grad_threshold 2 gradient norm の値
ord_coef = 1.0 # 固定 reward_ord の係数
cider_coef = 1.0 # 固定 reward_cider の係数
rouge_coef = 2.53 1 reward_rouge の係数
clip_coef = 1.65 1 reward_clip の係数
bert_coef = 6.68 1 reward_bert の係数
rep_coef = 5.84 1 reward_repeat の係数
repeat_thresh = [3,2,2,2]固定 repeat_penalty の n_gram の n に対する何回繰り返したらカウントするか。ngram_cnt を重み付き繰り返し数として。
penalty = - torch.clamp( torch.pow( 2, ngram_cnt -1 ) / seq_len, max = 1.0 )
repeat_weight = [1,1,1,1]固定 repeat_penalty の n_gram の n に対するカウントの重み。
ngram_cnt[b] += counts_per_ngram[mask].sum().float() * self.repeat_weight[n-1]
len_coef 2 length penalty の係数。length_penalty は、生成キャプションの長さ(最大長97 で 1になるように規格化)が教師キャプションと同じ長さ(最大長 97 が 1になるように規格化)だと 0 でそれから離れると MSE (二乗)で大きくなる。 -1 倍している。
unr_coef 2 unique_ngram_ratio
policy_coef = 1.0 #固定 policy_loss の係数
crf_coef 2 crf_loss の係数
ce_coef 2 ce_loss の係数。
ent_coef = 0.00269 1 entropy_loss の係数。
gae_coef 2 gae_loss の係数
kl_coef = 0.0401 1 kl_div_loss の係数。
gamma = 0.972 1 gae のγ
lam = 0.974 1 gae のλ
temp = 0.710 1 確率的 Viterbi サンプリングの softmax 温度。
1は一回目の Optuna 実行でサーチ、2 は二回目の実行でサーチ。
1回目でサーチを行ったパラメータの後に書いてある temp = 0.710 などの 0.710 はサーチで得られた値
Optuna によるパラメーターサーチ
Optuna のパラメーターサーチは、2回に分けて行われた。1回めは、14個、2回めは7個である。Optuna に渡す avg_reward は、上述のrewards ではなく、係数をすべて 1.0 にした rewards を新たに計算して渡した。5step に一回 枝刈りの判定を行った。Optuna の 1trial は、v7 の全データの 1/10 で 1エポックとした。1 trial におよそ 1時間かかった。枝刈りは、percentile 指定で行い上位65% を残した。1回めのサーチは n_trial = 200, 2回めのサーチは n_trial = 64 とした。1回目のサーチも2回目のサーチも、パラメーターの選別は、係数をすべて 1 として計算した avg_reward の良いものではなく、学習データで生成したキャプションについて評価基準、繰り返し、長さ、意味、文法の観点を元に、自然なパラメーターを選んだ。1回目のサーチで1セット選び、これを固定して2回目のサーチを行い5セットのパラメーターを選んだ。
二回目のパラメータサーチで得られたパラメーター
trial # #1 #5 #23 #34 #52
clip_range 0.268270043 0.235377263 0.139785854 0.135008251 0.104653457
clip_grad_threshold 0.399105998 1.374960427 1.296959831 0.884833044 1.727669834
len_coef 4.896378846 4.17401912 3.452924092 3.692636954 2.096280068
unr_coef 2.484457109 3.786249266 4.279625607 4.623101113 2.492827654
crf_coef 0.824120399 0.204998384 0.145146436 0.266517683 0.078483045
ce_coef 0.848698605 0.661358677 0.547371698 0.391427467 0.688275677
gae_coef 3.841572958 3.885689751 4.939326199 4.534116254 2.168931096
得られたパラメター候補による学習結果
Optuna 1回目のサーチで得られた 14個のパラメータ1セットを固定し、Optuna 2回目で得られたパラメータ 7個× 5セットについて、v7 データセット 1エポックの強化学習を行った。テストデータで評価した結果を掲載する。
test data(80データ、batch_size = 8 )
rougeL cider clip bert
#1 0.560 0.525 0.245 0.852
#5 0.569 0.424 0.247 0.856
#23 0.571 0.409 0.246 0.855
#34 0.571 0.403 0.247 0.854
#52 0.573 0.410 0.248 0.854
cider は、batch_size 内でのTF-IDF を使っているため batch_size に敏感なようである。
test data( 320データ、batch_size = 80 )
rougeL cider clip bert
#34 0.582 0.252 0.245 0.845
生成されたキャプション(サンプル)
hypo: [CLS] in this image we can see some food items. [SEP]
refe: [CLS] in this i can see there are red colored strawberries. [SEP]
本番強化学習の時に設定した学習率が小さかったのか、SFT と大きな差がないと感じています。時間がとれたら、学習率を2倍とかにした学習を行ってみたいと思います。
hypo: [CLS] in this image we can see some food items. [SEP]
refe: [CLS] in this i can see there are red colored strawberries. [SEP]
hypo: [CLS] in this image we can see a woman sitting on the chairs. in front of them there are sitting on the table. [SEP]
refe: [CLS] there are few persons sitting on the chairs. here we can see monitors, keyboards, tables, and devices. [SEP]
hypo: [CLS] in this image we can see a man is a woman standing on the background we can see a wall. [SEP]
refe: [CLS] this image is taken outdoors. at the bottom of the there is a floor. in the background there are a few buildings with walls, windows and balconies. in the middle of the image two men and a woman are standing on the floor and they are with smiling faces. [SEP]
hypo: [CLS] in this image we can see few plants and there are flowers. in the background there are plants. [SEP]
refe: [CLS] in this image in front there are plants. in the background of the image there is sky. [SEP]
hypo: [CLS] in this image we can see a woman in the image, we can see a wall. [SEP]
refe: [CLS] this is a black and white image. in this image we can see women wearing spectacles. [SEP]
hypo: [CLS] in this image we can see a plate. [SEP]
refe: [CLS] as we can see in the image there is a white color plate. in plate there is a dish. [SEP]
hypo: [CLS] in this image we can see a woman is holding a guitar. in front of a guitar. [SEP]
refe: [CLS] this image is clicked in a musical concert where there is a woman standing and she is holding a guitar in her hand. she is wearing black color dress. there is a mic in front of her and there is a bottle. she is holding a stick. there are speakers back side and there are some musical instruments on the bottom left corner. [SEP]
hypo: [CLS] in this image we can see a dog on the ground. [SEP]
refe: [CLS] in this image, we can see a black color dog, there is a blurred background. [SEP]
these pics. cider : 0.7612070921384236
these pics. rouge: 0.5736757759784076
these pics. clip_score: tensor(0.2328)
these pics. bert_score: 0.8674782291054726
学習に用いたソースコード
参考のためにソースコードを共有させていただきます。
お役に立てれば幸いです。
GRPO の計算コードを github に掲載しておきます。
PPO による計算結果を Qiita に掲載したころから、慢性の下痢に見舞われ、2週間くらい下痢が続いています。最初は、体の不調でも GRPO の計算を続けていましたが、あまりにも調子が悪いので、今は計算を止めています。そこで、画像キャプショニングの GRPO による強化学習のコードを github に掲載しておきます。参考になれば幸いです。
GRPO の学習では、報酬を計算するサンプル数(8とか)が多いため報酬の計算で計算時間を食ってしまい。PPO + GAE の計算よりかなり計算時間がかかるようになったため、実装を見直した。見直しところの要点を書かせていただきます。
複数サンプルの報酬計算方針。
複数サンプルは、サンプル数を N, バッチサイズを bsz、シーケンス数を seq_len として [N,bsz,seq_len] である。このまま計算すると、複数サンプルを samples として
rewards = [ _computer_reward( sample ) for sample in samples]
となるが、
samples1 = samples.view( N*bsz, seq_len )
rewards1 = _compute_reware( samples1 )
rewards = rewards1.view( N, bsz, seq_len )
とした。
生成したサンプルキャプションのバッチデコード
報酬を計算する生成した複数サンプルのキャプションを、バッチデコードした。tokenizer には、
model_id = "google-bert/bert-large-uncased"
tokenizer = BertTokenizer.from_pretrained(model_id)
pad_token_id = tokenizer.pad_token_id
cls_token_id = tokenizer.cls_token_id
sep_token_id = tokenizer.sep_token_id
sos_token_id = tokenizer.encode( [ "[unused0]" ] )[1]
eos_token_id = tokenizer.encode( [ "[unused1]" ] )[1]
を使っているため、batch_decode ができる。
preds1 = preds.clone().to(self.device )
targets1 = targets.clone().to(self.device )
preds1[preds1 == eos_token_id] = pad_token_id
decoded = self.tokenizer.batch_decode(preds1, skip_special_tokens=False)
preds_str = [s.replace("[PAD]", "").replace("[unused1]", "").strip() for s in decoded]
preds_str2 = self.tokenizer.batch_decode(preds1, skip_special_tokens = True )
targets1[targets1 == eos_token_id] = pad_token_id
decoded = self.tokenizer.batch_decode(targets1, skip_special_tokens=False)
targets_str = [s.replace("[PAD]", "").replace("[unused1]", "").strip() for s in decoded]
入力は、 preds と targets です。clone しないで、
preds[preds == eos_token_id] = pad_token_id
とすると、preds が書き換わってしまい。他でつかえなくなるため、clone する。bert-large-uncase には、eos_token_id はないが、前出の
の論文で、[CLS]のあとに[unused1]を二つ付けるように書いてあったので、そのように学習させたため、eos_token_id が入っているので、pad_token_id に置き換えた。preds_str の中に、[CLS] と [SEP] を残すために、skip_special_tokens=False で batch_decode して、[PAD] と [unused1] を削除した。targets_str も基本的に同じである。preds_str2 は [CLS],[SEP] がいらないため、skip_special_tokens=True で batch_decode することができた。pred_str2 はclip_score の計算に使う。
### 注意事項
transformers 4系では、
eos_token_id = tokenizer.encode( [ "[unused1]" ] )[1]
decoded ~ tokenizer.decode( eos_token_id )
ができたが、transformers 5系では、
eos_token_id = tokenizer.encode( [ "[unused1]" ] )[1]
ができなかいようです。
clip_score
clip_score の計算には、
from torchmetrics.multimodal import CLIPScore
略
self.metric = CLIPScore(model_name_or_path="openai/clip-vit-base-patch32").to(self.device)
を用いた。一般に、clip_score で計算できる値はバッチ平均なので、バッチひとつひとつに対応させるためには、batch ひとつ一つに対応した画像とキャプションを、 batch_images, batch_prompts として、
batch_clip_score = [ self.metric( image, prompt ) for in zip( batch_images, batch_prompts ]
のようにしなければならない。これだととても計算時間がかかる。そこで、
with autocast(str(self.device),enabled=self.use_amp):
with torch.no_grad():
processed = self.metric.processor(text=preds_str2, images=imgs2, return_tensors="pt", padding=True, \
truncation=True, max_length=77, do_resize=False, do_rescale=False ).to(self.device)
outputs = self.metric.model(**processed)
# 特徴量の正規化
image_features = outputs.image_embeds / outputs.image_embeds.norm(p=2, dim=-1, keepdim=True)
text_features = outputs.text_embeds / outputs.text_embeds.norm(p=2, dim=-1, keepdim=True)
individual_scores = torch.clamp( (image_features.to(self.device) * \
text_features.to(self.device)).sum(axis=-1), min=0)
clip_scores = individual_scores[:,None].expand( -1, seq_len ) / 100.0
reward_clip = clip_scores
のように、batch で計算できるように工夫した。これは、Google の AIモードに助けてもらった。
ここで、self.metric.processor では、77 seq_len 以上の preds_str2 を切り詰めた。加えて、collate_function で 画像サイズを 224 * 224 にすることにより do_resize = False, 画像の値を [0,1] にするいことにより、do_rescale = False とした。resize と rescale は、processor で行うより、num_workers >=1 の collate_functionで行った方が早いらしいです。
transforms2 = v2.Compose([
v2.Resize((224, 224)),
v2.ToImage(),
v2.ToDtype(torch.float32, scale=True),
#v2.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
])
def collate_func(batch: Sequence[Tuple[Union[torch.Tensor, str]]], pad_index, length_max ):
imgs1, imgs2, tokens = zip(*batch)
max_length = length_max
#max_length = 0
#for target in tokens:
# if max_length < len( target ):
# max_length = len( target )
targets = []
lengths = []
for target in tokens:
pad_len = max_length - len( target )
#print( "target:", target )
input2= F.pad( target, (0, pad_len), mode='constant', value = pad_index)
targets.append( input2 )
lengths.append( len( target ) )
imgs1 = torch.stack( imgs1, dim = 0 )
imgs2 = torch.stack( imgs2, dim = 0 )
targets = torch.stack( targets, dim = 0 )
lengths = torch.tensor( lengths, requires_grad
return imgs1, imgs2, targets, lengths
ここで、imgs1 は、画像キャプショニングに使う 336*336 の画像で、imgs2 が clip_score の計算に使う 224 * 224 の画像です。メモリ的には問題ないようです。
bert_score
bert_score の計算には、
from evaluate import load
略
self.bert = load('bertscore' )
略
model_name = 'distilbert-base-uncased'
bert_scores = self.bert.compute(
predictions=preds_str,
references=targets_str,
model_type=model_name,
use_fast_tokenizer=True,
lang='en',
device=self.device,
batch_size=config.batch_size * config.num_samples, # メモリ許容範囲で大きく設定
rescale_with_baseline=False
)['f1']
reward_bert = torch.tensor( bert_scores ).to( self.device )[:,None].expand( -1, seq_len )
を使いました。時間短縮のため、distribert です。
文章の長さのペナルティ
文章の長さが短めだったので、教師キャプションと同じ長さになるとペナルティが0で、それからはずれると MSE 的にマイナスになるペナルティを設定しました。長さを、固定長の 97 seq_len で割って [0,1] にしています。
def compute_length_reward(self, preds, targets):
# preds.size(1) を L として取得
max_len = preds.size(1)
# 1から始まるインデックスを作成 (長さとして計算するため)
arange_index = torch.arange(1, max_len + 1, device=self.device).float()
def get_length(tokens):
# eosの位置を特定
eos_mask = (tokens == eos_token_id)
# 最初のeosだけを抽出
first_eos = (eos_mask.int().cumsum(dim=1) == 1) & eos_mask
# eosがある場合はその位置(1-indexed)を、ない場合は最大長を返す
lengths = torch.sum(first_eos.float() * arange_index, dim=1)
# eosが一度も出現しなかった行は 0 になっているので、max_len で埋める
no_eos_mask = (eos_mask.sum(dim=1) == 0)
lengths[no_eos_mask] = float(max_len)
# 正規化 (0.0 ~ 1.0)
return lengths / max_len
pred_lengths = get_length(preds)
target_lengths = get_length(targets)
#
# MSEの計算 (負の値を報酬とする)
# reduction='none' なので [batch_size] の形
reward_lengths = - ((pred_lengths - target_lengths) ** 2)
# [batch_size, 1] にしてから [batch_size, seq_len] に拡張
reward = reward_lengths.unsqueeze(1).expand(-1, max_len)
return reward
unique_ngram_ratio
def unique_ngram_ratio(self, preds):
bsz, seq_len = preds.size()
ng = 5
device = preds.device
# 1. 各シーケンスの有効な長さを特定 (eosまで)
# cumsumを使って最初のeos以降をマスクする
eos_mask = (preds == eos_token_id)
first_eos_idx = (eos_mask.cumsum(dim=1) == 1) & eos_mask
# eosがない場合はseq_lenとする
lengths = torch.where(first_eos_idx.any(dim=1),
first_eos_idx.float().argmax(dim=1),
torch.tensor(seq_len, device=device)).unsqueeze(1)
unr_list = []
# n-gramのサイズごとに一括処理
for n in range(1, ng + 1):
# unfoldで全n-gramを抽出: (bsz, seq_len - n + 1, n)
if seq_len < n:
unr_list.append(torch.zeros(bsz, 1, device=device))
continue
ngrams = preds.unfold(1, n, 1)
num_ngrams = ngrams.size(1)
# マスク作成: 有効な長さ(eos前)に含まれるn-gramのみを残す
# n-gramの開始位置が (length - n + 1) 未満である必要がある
ngram_indices = torch.arange(num_ngrams, device=device).expand(bsz, -1)
valid_mask = ngram_indices < (lengths - n + 1)
# 非常に大きい値で無効なn-gramを埋める(uniqueカウントから除外するため)
# または、バッチを跨いでユニーク判定するためにハッシュ化
# ここでは各バッチ行ごとにユニーク数を数える必要があるため、
# 完全なベクトル化には torch.unique の制限(バッチ非対応)を回避する工夫が必要
# 解決策: 各行をユニークなオフセットでシフトして全体でuniqueをとる手法
# ただし、シンプルさとメモリ効率のため、ngループのみ残すのが現実的です。
# 行ごとのUniqueカウント (Vectorized version of unique per row)
# 完全にforを消す場合、各n-gramを1つのスカラにパッキング(ハッシュ)して処理
if n == 1:
packed = ngrams.squeeze(-1)
else:
# 各要素を大きな基数でシフトして足し合わせ、1つの整数にする
max_val = preds.max() + 1
coeffs = max_val ** torch.arange(n, device=device)
packed = (ngrams * coeffs).sum(dim=-1)
# 無効な位置にユニークな(重ならない)負の値を代入
invalid_fill = -1 - torch.arange(bsz * num_ngrams, device=device).reshape(bsz, num_ngrams)
packed = torch.where(valid_mask, packed.float(), invalid_fill.float())
# 行ごとにユニーク数をカウント
# Note: PyTorchのuniqueはバッチ未対応なため、以下が最速の回避策の一つ
def count_unique_rowwise(t, mask):
# ソートして隣接要素との差を見ることでユニーク数を算出
t_sorted, _ = torch.sort(t, dim=1)
diffs = (t_sorted[:, 1:] != t_sorted[:, :-1]).int()
# 最初の要素 + 変化があった回数 - 無効値の数(バッチ内の無効分を補正)
unique_counts = diffs.sum(dim=1) + 1
# 無効な埋め草(すべてユニークに設定済み)の数を引いて、
# 有効なものが1つもなければ0にする処理
invalid_count = (~mask).sum(dim=1)
return (unique_counts - invalid_count).float()
row_unique = count_unique_rowwise(packed, valid_mask)
row_total = valid_mask.sum(dim=1).clamp(min=1).float()
unr_list.append(row_unique / row_total)
# 結果の整形
unr_tensor = torch.stack(unr_list, dim=1) # (bsz, ng)
return torch.mean(unr_tensor, dim=1)[:, None].expand(-1, seq_len)
ngram_repeat のペナルティ
def calc_ngram_repeat_fast(self, preds):
# preds が書き換わらないよう、この関数内では元の値を保護する
bsz, seq_len = preds.size()
ngram_cnt = torch.zeros(bsz, device=preds.device, dtype=torch.float)
base_ignore = [pad_token_id, eos_token_id, cls_token_id, sep_token_id]
extra_ignore = [a_token_id, the_token_id, period_token_id, comma_token_id, and_token_id, in_token_id]
ng = 4
for n in range(1, ng + 1 ):
if seq_len < n:
continue
current_ignore_ids = base_ignore + (extra_ignore if n == 1 else [])
# ignore_mask は bool なので preds に影響しません
ignore_mask = torch.isin(preds, torch.tensor(current_ignore_ids, device=preds.device))
# 【重要】unfoldの後に .clone() を入れてメモリを切り離す
ngrams = preds.unfold(dimension=1, size=n, step=1).clone()
num_ngrams = ngrams.size(1)
ngram_ignore_mask = ignore_mask.unfold(dimension=1, size=n, step=1).any(dim=-1)
if n > 1:
# 語彙サイズに基づくハッシュ化
vocab_size_max = max(preds.max().item(), 100000)
weights = torch.pow(torch.tensor([vocab_size_max], device=preds.device),
torch.arange(n, device=preds.device)).long()
hashed_ngrams = (ngrams.long() * weights).sum(dim=-1)
else:
hashed_ngrams = ngrams.squeeze(-1).long()
# これで hashed_ngrams を書き換えても、clone 済みのデータなので preds は安全
invalid_val = -1
hashed_ngrams[ngram_ignore_mask] = invalid_val
for b in range(bsz):
b_ngrams = hashed_ngrams[b]
valid_b_ngrams = b_ngrams[b_ngrams != invalid_val]
if valid_b_ngrams.numel() == 0:
continue
unique_vals, counts = torch.unique(valid_b_ngrams, return_counts=True)
#mask = counts >= self.repeat_thresh[n-1]
#ngram_cnt[b] += counts[mask].sum().float() * self.repeat_weight[n-1]
## しきい値以上のものを取り出す
#mask = counts >= self.repeat_thresh[n-1]
## しきい値を超えた分(リピート分)だけを抽出して加算
## 例: thresh=2 で 3回出たら、3 - (2-1) = 2回分。
## もし「最初の1回は常に無料」にしたいなら、さらに -1 する等の調整もアリです。
#repeat_counts = counts[mask] - (self.repeat_thresh[n-1] - 1)
#ngram_cnt[b] += repeat_counts.sum().float() * self.repeat_weight[n-1]
mask = counts > self.repeat_thresh[n-1]
if mask.any():
# 超過した数だけを純粋に加算する
# 例: thresh=2 で 3回出たら、3 - 2 = 1回分のリピート
# 例: thresh=1 で 2回出たら、2 - 1 = 1回分のリピート
repeat_counts = counts[mask] - self.repeat_thresh[n-1]
ngram_cnt[b] += repeat_counts.sum().float() * self.repeat_weight[n-1]
#print( "DEBUG: ngram_cnt.mean():", ngram_cnt.mean() )
#print( "DEBUG: seq_len:", seq_len )
penalty = - (ngram_cnt / seq_len).clamp(max=1.0)
return penalty[:, None].expand(-1, seq_len)
#return penalty[:, None]
repeat_thresh=(2,1,1,1)は何回リピートしたら数えるかという閾値。repeat_weight=(1,1,1,1)はリピート回数に乗じる重みです。
2026年6月4日追記
ようやく、生成したキャプションから repeat を減らす強化学習の仕方が分かりました。github に置いたソースの ImgCap_RL_GRPO_6_4_optuna.ipynb で、repeat が減少することが確認できました。ソースを置いておきます。ご参考になれば幸いです。学習用のデータセットは COCO に変更しました。
計算の要領
ここでは、強化学習で repeat を減らすために効果的だった repeat_penalty の要領について説明させていただきます。上記の calc_ngram_repeat_fastの要領で n_gram のリピートの数を数えます。このとき、a, the, [CLS], [SEP], ",", "." などは除外します。各 n_gram のリピート数に重みをつけて加えて ngram_cnt を計算します。
ngram_cnt = 1 * 1gram のリピート数 + 2 * 2gram のリピート数 + 3 * 3gram のリピート数 + 4 * 4gram のリピート数
ngram_cnt から repeat_penalty を次式で非線形に求めます。
reoeat_penalty = - torch.pow( ngram_cnt, 2.0 )
この repeat_penalty は私の場合 -60 とかになりました。reward に加えます。
reward = 各言語スコアの報酬 + rep_coef * repeat_penalty + len_coef * len_penalty + unr_coef * unique_ngram_ratio
repeat_penalty 以外は -2 から 2 くらいの範囲の数で、repeat_penalty が 0 から -80 くらいの間の数です。rep_coef は 0 とか 3 くらいの間の数です。参考になれば幸いです。
H100 が欲しい。現在、RTX PRO 6000 が発売されてますが、未だに RTX A6000 で学習を行っています。RTX A6000 でメモリーと計算時間を考慮すると、 CRF層に beam = 256 の top-k 近似を行わないと計算がまともにできないという認識です。しかし、H100 だと、扱う語彙数を 4000 くらいに絞れば、top-k 近似を行わずに計算できるらしいです。近似は近似でしかないので、許されることなら H100 で、top-k 近似なしで計算したいです。






