😊
[wip] MetaのSONARを触ってみる
はじめに
2024/12/11にMetaによってLCM(Large Concept Model)が発表されました。
従来のLLMでは単語毎にトークンを割り振っていましたが、LCMでは文章に対してトークンを割り振ることでより長大な文章を高精度に扱えるように試みているようです(ざっくり)。
そのエンコード・デコードに用いられるSONAR (https://github.com/facebookresearch/SONAR) がGoogleColabでも弄れたので使ってみた結果をメモしました!
準備
sonar本体と依存パッケージのインストール
!apt install libsndfile1
!pip3 install torch=="2.5.1" --extra-index-url "https://download.pytorch.org/whl/cu121" --upgrade
!pip3 install fairseq2=="v0.3.0rc1" --pre --extra-index-url "https://fair.pkg.atmeta.com/fairseq2/whl/rc/pt2.5.1/cu121" --upgrade
!pip3 install sonar-space
公式ドキュメントによると、現時点(2025/01/22)ではfairseq2 (https://github.com/facebookresearch/fairseq2) はv0.3.0rc1にしか対応してないことに注意。
モデルの用意
from sonar.inference_pipelines.text import TextToEmbeddingModelPipeline, EmbeddingToTextModelPipeline
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
t2vec_model = TextToEmbeddingModelPipeline(
encoder="text_sonar_basic_encoder",
tokenizer="text_sonar_basic_encoder",
device=device,
)
vec2text_model = EmbeddingToTextModelPipeline(
decoder="text_sonar_basic_decoder",
tokenizer="text_sonar_basic_encoder",
device=device,
)
使ってみる
文章はこちらから拝借:https://en.wikipedia.org/wiki/Mount_Fuji
エンコード(English→Vector)
- code
sentences = [
"Mount Fuji is an active stratovolcano located on the Japanese island of Honshu, with a summit elevation of 3,776m.",
"It is the highest mountain in Japan, the second-highest volcano located on an island in Asia, and seventh-highest peak of an island on Earth.",
"Mount Fuji last erupted from 1707 to 1708.",
"The mountain is located about 100 km southwest of Tokyo and is visible from the Japanese capital on clear days.",
]
embeddings = t2vec_model.predict(sentences, source_lang="eng_Latn")
print(embeddings.shape)
- output
torch.Size([4, 1024])
各文章で長さ1024でベクトル化される。
デコード(Vector→English)
- code
reconstructed = vec2text_model.predict(embeddings, target_lang="eng_Latn", max_seq_len=512)
print(reconstructed)
- output
[
'Mount Fuji is an active stratovolcano located on the Japanese island of Honshu, with a summit elevation of 3,776m.',
'It is the highest mountain in Japan, the second highest volcano located on an island in Asia, and the seventh highest peak of an island on Earth.',
'Mount Fuji last erupted from 1707 to 1708.',
'The mountain is located about 100 km southwest of Tokyo and is visible from the Japanese capital on clear days.'
]
元の文章へ復元できてる!
デコード(Vector→Japanese)
- code
reconstructed = vec2text_model.predict(embeddings, target_lang="jpn_Jpan", max_seq_len=512)
print(reconstructed)
- output
[
'富士山は,日本のホンジュ島に位置するアクティブ・ストラトバルクであり,高度は3,776mです.',
'日本で最も高い山であり,アジアにある島で2番目に高い火山であり,地球上で7番目に高い山頂です.',
'富士山は1707年から1708年まで噴火した.',
'この山は東京から南西約100kmに位置し,晴れた日には日本の首都から見える.'
]
Google翻訳の劣化版くらいの精度はありそうでちゃんと文章のニュアンスを捉えられてそう!
本州や成層火山は日本語の学習データに登録されてなかったのかもしれない
Discussion