🔟Apple Silicon Fine-tuning Gemma-2B with MLX

About MLX

MLX의 핵심은 애플의 디바이스에서 딥 러닝에 접근하는 방식에 대한 패러다임의 전환을 의미합니다. MLX는 통합 메모리 아키텍처(UMA)와 Apple Silicon의 놀라운 아키텍처를 활용하여 외부 처리 장치나 특수 가속기 없이도 Apple의 하드웨어에서 직접 원활하고 효율적인 모델 추론, 훈련 및 배포를 가능하게 합니다.

MLX는 M1, M2, M3, M4에서 가속이 가능한 차원 벡터로 Numpy의 array와 Pytorch의 tensor로 변환이 가능합니다.

Pytorch 사용 시 Benchmark를 보면 M3 Max의 MLX 사용 시에 NVIDIA V100에 근접함을 할 수 있습니다.

https://medium.com/towards-data-science/how-fast-is-mlx-a-comprehensive-benchmark-on-8-apple-silicon-chips-and-4-cuda-gpus-378a0ae356a0

Fine-tuning Gemma-2B with MLX

애플 실리콘에 최적화된 MLX 라이브러리를 사용하여 최신 Gemma-2B-Inst를 MacBook 로컬에서 실행하고 LMX LoRA Fine-tuning 후에 Huggingface Hub에 push 해보겠습니다.

circle-info

주의 사항: Apple Silicon M 시리즈 맥북 사양 중 메모리 16G 이상에서 실행하시기 바랍니다.

Setup Environments

필요한 라이브러리를 설치합니다. 또한 Apple Silicon이 탑재된 Mac이 필요합니다. 이 경우에는 M3 Max 128GB가 장착된 MacBook Pro를 사용했습니다.

MLX Inference with Gemma Model

여기서는 gemma의 2b instruct 모델인 gemma-7b-it을 사용하겠습니다.

Apple의 MacOS 전용 딥러닝 프레임워크인 mlx_lm library를 사용합니다.

google/gemma-2b-it 모델을 사용하려며 huggingface google 페이지에서 Acknowledge License를 클릭하여 사용을 신청하고 승인 후 활용 가능합니다. 신청후 승인은 5분이내에 이뤄집니다.

mlx-exples 리포지토리에 있는 일부 코드를 읽어보면 transformer tokenizer에 apply_chat_template 메서드가 있는 경우 해당 템플릿을 사용하여 프롬프트를 생성하는 것처럼 보입니다.

따라서 생성할 때 질문 자체만 포함된 프롬프트를 입력합니다.

이것이 토큰 생성기가 generate() 메서드에서 내부적으로 수행하는 작업입니다:

Fine-tuning the Gemma model with LoRA using MLX

Huggigface hub에 공개된 teknium의 데이터 세트에서 fine-tuning을 통해 어떤 결과를 얻을 수 있는지 살펴보겠습니다.

이것은 단지 예시일 뿐이므로 600회 반복에 대해서만 fine-tuning 할 것입니다.

Preparing Dataset

https://huggingface.co/datasets/teknium/trismegistus-project

topic
domain_task_type
id
system_prompt_used
source
conversations

0

'Big Man' society

Task

570a8404-3270-4aba-a47c-660359440835

You are a master of the esoteric, occult, 'Big...

DomainExpert_Occult

[{'from': 'human', 'value': 'Compose a compreh...

1

'Big Man' society

Task

ddf44765-8756-46db-a945-672050905fc0

You are a master of the esoteric, occult, 'Big...

DomainExpert_Occult

[{'from': 'human', 'value': 'Develop an intric...

2

'Big Man' society

Task

9ef38c3a-31ed-48d7-94d2-75fc588bcb2e

You are a master of the esoteric, occult, 'Big...

DomainExpert_Occult

[{'from': 'human', 'value': 'Write an extensiv...

3

'Big Man' society

Task

6dea7781-0f74-4692-8d1d-762c6585c280

You are a master of the esoteric, occult, 'Big...

DomainExpert_Occult

[{'from': 'human', 'value': 'Develop an intric...

4

'Black Books' of European necromancy

Task

188c6c15-d2b7-448b-b93c-505aeca2a458

You are a master of the esoteric, occult, 'Bla...

DomainExpert_Occult

[{'from': 'human', 'value': 'Devise an intrica...

converstaion에 Q와 A에 대한 텍스트가 들어 있는 것을 볼 수 있습니다. 이를 Gemma의 프롬프트 형식으로 포맷하고 jsonl 파일에 저장합니다.

system_prompt_used
question
answer

0

You are a master of the esoteric, occult, 'Big...

Compose a comprehensive biography of a renowne...

Title: The Mystifying Odyssey of Eliphas Black...

1

You are a master of the esoteric, occult, 'Big...

Develop an intricate numerology system that de...

I. Foundational Numerology\n\nThe 'Big Man' so...

2

You are a master of the esoteric, occult, 'Big...

Write an extensive biography of a prominent oc...

Title: Nathaniel Ziester: A Life in Shadows - ...

3

You are a master of the esoteric, occult, 'Big...

Develop an intricate system of numerology, inc...

Title: The Numerological Riddles of the Big Ma...

4

You are a master of the esoteric, occult, 'Bla...

Devise an intricate multi-step process for the...

Step 1: Assess the condition of the grimoire\n...

...

...

...

...

13523

You are a master of the esoteric, occult, Reap...

In the context of the Reappropriated Goddess m...

Answer: To regain women's empowerment and infl...

13524

You are a master of the esoteric, occult, Reap...

Write a section of a grimoire explaining the c...

Title: The Reappropriated Goddess in the Occul...

13525

You are a master of the esoteric, occult, Reap...

Write a section of a grimoire specifically foc...

Title: The Reappropriated Goddess: A Journey i...

13526

You are a master of the esoteric, occult, Reap...

Create a detailed introductory section for a g...

Title: The Reappropriated Goddess: A Grimoire ...

13527

You are a master of the esoteric, occult, Reap...

Write an introductory section of a grimoire, f...

Title: The Reappropriated Goddess: Foundations...

13528 rows × 3 columns

Gemma는 별도의 시스템 프롬프트에 대해 학습되지 않은 것 같으므로 아래와 같이 시스템 프롬프트와 사용자 프롬프트를 구분하는 별도의 형식을 만들어 보겠습니다.

데이터를 두 개의 개별 jsonl 형식 파일에 저장해 보겠습니다.

  • Train set: data/train.jsonl

  • Valid set: data/valid.jsonl

LoRA Fine-tuning with MLX

이제 데이터가 준비되었으니 미세 조정을 시작해 보겠습니다!

mlx_lm으로 LoRA를 실행할 때 다음 명령을 사용하여 다양한 옵션을 확인할 수 있습니다.

And here's how we run the training. This will take a while to finish. Let's run the training.

Inference Fine-tuned Gemma model using MLX

다음 스크립트를 사용하여 명령줄에서 LoRA 가중치로 추론을 수행할 수 있습니다.

하지만 특정 프롬프트 형식을 사용하여 미세 조정했으므로 모델에 프롬프트를 표시할 때마다 이 형식을 사용해야 합니다.

여전히 apply_chat_template와 동일한 토큰화기를 사용하므로 apply_chat_template에서 제공될 내용 없이 프롬프트를 준비해야 합니다.

프롬프트의 형식을 지정하는 간단한 함수를 만들어 보겠습니다.

Fusing LoRA Weights

마지막으로 학습된 LoRA 가중치를 모델 자체에 병합해 보겠습니다.

아래 명령은 사용 가능한 옵션을 보여줍니다:

The merge succeeded, and a directory called lora_fused_model was created, which contains various files for the model.

아래 스크립트를 사용하여 메타데이터 속성을 사용하여 .safetensors 파일을 다시 작성하는 것입니다. (.safetensors구현 방식을 고려할 때 파일을 저장할 때 for 루프가 작동하지 않으므로(텐서에 대한 모든 참조를 제거해야 하는 등...) 몇 개의 세이프텐서 파일을 수동으로 다시 작성해 보겠습니다.)

Model Push to HF

모델을 업로드하려면 먼저 Huggigface write token을 저장해야 합니다. 액세스 토큰을 설정하려면 다음과 같이 하세요:

  • 여기에서 토큰을 생성합니다(반드시 'Write' 토큰을 생성해야 함): https://huggingface.co/settings/tokens

  • huggingface-cli 도구를 다운로드하고 'huggingface-cli 로그인'을 실행합니다.

  • 메시지가 표시되면 토큰을 붙여넣습니다.

Load & Inference Model

Local 결합 모델을 로드하고 추론을 실행해 보겠습니다.

융합 모델의 생성 속도는 융합하지 않고 LoRA 가중치로 실행하는 것보다 훨씬 빠릅니다.

  • LoRA 생성: 초당 6.002 토큰 생성

  • 융합 모델 생성: 17.849 토큰-초당

Optional: Test pushed HF

업로드된 모델이 제대로 업로드되었는지 확인하기 위해 Huggingface에서 업로드된 모델을 다운로드하고 추론을 실행해 보겠습니다.

We can also run it using transformers directly, although without the benefit of utilizing MLX/Apple Silicon to the fullest.

Last updated