Gemma C++ 튜토리얼 (gemma.cpp)

gemma.cpp는 Gemma 모델의 경량 순수 C++ 추론 런타임 구현입니다.

Gemma에 관한 자세한 내용은 모델 카드를 참고하세요. gemma.cpp 관련 아티팩트를 비롯한 모델 가중치는 Kaggle에서 확인할 수 있습니다.

이 프로젝트의 대상은 누구인가요?

최신 LLM 추론 엔진은 정교한 시스템으로, 종종 기존 신경망 런타임 외에도 맞춤 기능을 제공합니다. 이를 통해 상위 알고리즘과 하위 계산의 공동 설계를 통한 연구 및 혁신의 기회가 생깁니다. 그러나 실험용으로 설계되지 않은 배포 중심 C++ 추론 런타임과 컴파일을 통해 하위 수준 계산을 추상화하는 Python 중심 ML 연구 프레임워크 사이에는 격차가 있습니다.

gemma.cpp는 완전한 일반성보다는 단순성과 직접성에 중점을 두고 Gemma 2B 및 7B 모델의 최소한의 구현을 제공합니다. 이는 ggml, llama.c, llama.rs와 같은 수직 통합 C++ 모델 구현에서 영감을 받았습니다.

gemma.cpp는 실험 및 연구 사용 사례를 타겟팅합니다. 특히 Google Highway 라이브러리를 통해 휴대용 SIMD를 사용하여 CPU 추론 및 추론 알고리즘의 설계 공간을 탐색합니다. 최소한의 종속 항목으로 다른 프로젝트에 간편하게 삽입할 수 있으며, 소규모 (약 2,000개 LoC) 핵심 구현과 약 4,000개 LoC의 지원 유틸리티를 사용하여 쉽게 수정할 수 있습니다.

프로덕션 중심의 에지 배포의 경우 JAX, Keras, PyTorch, Transformers와 같은 성숙한 Python 프레임워크를 사용하는 표준 배포 경로를 사용하는 것이 좋습니다 (여기에서 모든 모델 변형 확인).

크고 작은 커뮤니티 참여는 언제나 환영입니다. 이 프로젝트는 Google의 오픈소스 커뮤니티 가이드를 준수합니다.

빠른 시작

이 빠른 시작을 완료하려면 gemma.cpp를 클론하거나 다운로드해야 합니다.

시스템 요구사항

시작하기 전에 다음을 설치해야 합니다.

1단계: Kaggle에서 모델 가중치 및 토큰 생성기 가져오기

Kaggle의 Gemma 모델 페이지로 이동하여 '모델 변형

Gemma C++. On this tab, theVariation` 드롭다운에는 다음 옵션이 포함되어 있습니다. bfloat16 가중치 옵션은 정확성이 더 높고 8비트 전환 부동 소수점 가중치는 더 빠른 추론을 지원합니다.

2B 명령 조정 (it) 및 사전 학습 (pt) 모델:

모델 이름 설명
2b-it 20억 매개변수 명령 조정 모델, bfloat16
2b-it-sfp 20억 개의 매개변수로 조정된 명령 모델, 8비트 전환 부동 소수점
2b-pt 20억 개의 매개변수가 있는 사전 학습된 모델, bfloat16
2b-pt-sfp 20억 개의 매개변수 선행 학습 모델, 8비트 전환 부동 소수점

7B 명령 조정 (it) 및 사전 학습 (pt) 모델:

모델 이름 설명
7b-it 70억 매개변수 명령 조정 모델, bfloat16
7b-it-sfp 70억 개의 매개변수로 조정된 명령 모델, 8비트 전환 부동 소수점
7b-pt 70억 매개변수 선행 학습 모델, bfloat16
7b-pt-sfp 70억 개의 매개변수 선행 학습 모델, 8비트 전환 부동 소수점

참고: 시작하려면 2b-it-sfp부터 시작하는 것이 좋습니다.

2단계: 파일 추출

동의 양식을 작성하면 다운로드가 진행되어 tar 보관 파일 archive.tar.gz을 가져옵니다. archive.tar.gz에서 파일을 추출합니다 (몇 분 정도 걸릴 수 있음).

tar -xf archive.tar.gz

이렇게 하면 2b-it-sfp.sbs와 같은 모델 가중치와 토큰라이저 파일 (tokenizer.spm)이 포함된 파일이 생성됩니다. 이러한 파일을 편리한 디렉터리 위치 (예: 이 저장소의 build/ 디렉터리)로 이동하는 것이 좋습니다.

3단계: 빌드

빌드 시스템은 CMake를 사용합니다. Gemma 추론 런타임을 빌드하려면 빌드 디렉터리를 만들고 최상위 프로젝트 디렉터리에서 cmake를 사용하여 빌드 파일을 생성합니다.

(cd build && cmake ..)

그런 다음 make를 실행하여 ./gemma 실행 파일을 빌드합니다.

cd build make -j [number of parallel threads to use] gemma

예를 들면 make -j 8 gemma입니다. 성공하면 이제 build/ 디렉터리에 gemma 실행 파일이 생깁니다.

4단계: 실행

이제 build/ 디렉터리 내에서 gemma를 실행할 수 있습니다.

gemma에는 다음과 같은 필수 인수가 있습니다.

인수 설명 예시 값
--model 모델 유형입니다. 2b-it, 2b-pt, 7b-it, 7b-pt 등(위 참고)
--compressed_weights 압축된 가중치 파일입니다. 2b-it-sfp.sbs, ... (위 참고)
--tokenizer 토큰라이저 파일 이름입니다. tokenizer.spm

gemma는 다음과 같이 호출됩니다.

./gemma \
--tokenizer [tokenizer file] \
--compressed_weights [compressed weights file] \
--model [2b-it or 2b-pt or 7b-it or 7b-pt]

다음 구성의 호출 예시:

  • 압축된 가중치 파일 2b-it-sfp.sbs (2B 명령어 조정 모델, 8비트 전환된 부동 소수점).
  • 토크나이저 파일 tokenizer.spm
./gemma \
--tokenizer tokenizer.spm \
--compressed_weights 2b-it-sfp.sbs \
--model 2b-it

사용

gemma에는 상세도 플래그로 제어되는 다양한 사용 모드가 있습니다.

모든 사용 모드는 대화형이며 새 줄 입력 시 텍스트 생성을 트리거합니다.

상세 출력 사용 모드 세부정보
--verbosity 0 최소 생성 출력만 출력합니다. CLI 도구로 사용하기에 적합합니다.
--verbosity 1 기본값 표준 사용자 대상 터미널 UI
--verbosity 2 상세 추가 개발자 및 디버그 정보를 표시합니다.

대화형 터미널 앱

기본적으로 상세 수준은 1로 설정되어 필요한 인수와 함께 gemma이 호출될 때 터미널 기반 대화형 인터페이스를 표시합니다.

$ ./gemma [...]
  __ _  ___ _ __ ___  _ __ ___   __ _   ___ _ __  _ __
 / _` |/ _ \ '_ ` _ \| '_ ` _ \ / _` | / __| '_ \| '_ \
| (_| |  __/ | | | | | | | | | | (_| || (__| |_) | |_) |
 \__, |\___|_| |_| |_|_| |_| |_|\__,_(_)___| .__/| .__/
  __/ |                                    | |   | |
 |___/                                     |_|   |_|

tokenizer                     : tokenizer.spm
compressed_weights            : 2b-it-sfp.sbs
model                         : 2b-it
weights                       : [no path specified]
max_tokens                    : 3072
max_generated_tokens          : 2048

*Usage*
  Enter an instruction and press enter (%Q quits).

*Examples*

-   Write an email to grandma thanking her for the cookies.
-   What are some historical attractions to visit around Massachusetts?
-   Compute the nth fibonacci number in javascript.
-   Write a standup comedy bit about WebGPU programming.

> What are some outdoorsy places to visit around Boston?

[ Reading prompt ] .....................

**Boston Harbor and Islands:**

*   **Boston Harbor Islands National and State Park:** Explore pristine beaches, wildlife, and maritime history.
*   **Charles River Esplanade:** Enjoy scenic views of the harbor and city skyline.
*   **Boston Harbor Cruise Company:** Take a relaxing harbor cruise and admire the city from a different perspective.
*   **Seaport Village:** Visit a charming waterfront area with shops, restaurants, and a seaport museum.

**Forest and Nature:**

*   **Forest Park:** Hike through a scenic forest with diverse wildlife.
*   **Quabbin Reservoir:** Enjoy boating, fishing, and hiking in a scenic setting.
*   **Mount Forest:** Explore a mountain with breathtaking views of the city and surrounding landscape.

...

명령줄 도구로 사용

gemma 실행 파일을 명령줄 도구로 사용하려면 인수가 완전히 지정된 gemma.cpp의 별칭을 만드는 것이 유용할 수 있습니다.

alias gemma2b="~/gemma.cpp/build/gemma -- --tokenizer ~/gemma.cpp/build/tokenizer.spm --compressed_weights ~/gemma.cpp/build/2b-it-sfp.sbs --model 2b-it --verbosity 0"

위 경로를 다운로드한 모델 경로 및 토큰라이저 경로로 바꿉니다.

다음은 잘린 입력으로 gemma 프롬프트를 표시하는 예입니다 (위에서 정의한 gemma2b 별칭 사용).

cat configs.h | tail -35 | tr '\n' ' ' | xargs -0 echo "What does this C++ code do: " | gemma2b

참고: gemma.cpp의 CLI 사용은 실험용이며 컨텍스트 길이 제한사항을 고려해야 합니다.

위 명령어의 출력은 다음과 같이 표시됩니다.

$ cat configs.h | tail -35 | tr '\n' ' ' | xargs -0 echo "What does this C++ code do: " | gemma2b
[ Reading prompt ] ......................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
The code defines two C++ structs, `ConfigGemma7B` and `ConfigGemma2B`, which are used for configuring a deep learning model.

**ConfigGemma7B**:

*   `seq_len`: Stores the length of the sequence to be processed. It's set to 7168.
*   `vocab_size`: Stores the size of the vocabulary, which is 256128.
*   `n_layers`: Number of layers in the deep learning model. It's set to 28.
*   `dim_model`: Dimension of the model's internal representation. It's set to 3072.
*   `dim_ffw_hidden`: Dimension of the feedforward and recurrent layers' hidden representations. It's set to 16 * 3072 / 2.

**ConfigGemma2B**:

*   `seq_len`: Stores the length of the sequence to be processed. It's also set to 7168.
*   `vocab_size`: Size of the vocabulary, which is 256128.
*   `n_layers`: Number of layers in the deep learning model. It's set to 18.
*   `dim_model`: Dimension of the model's internal representation. It's set to 2048.
*   `dim_ffw_hidden`: Dimension of the feedforward and recurrent layers' hidden representations. It's set to 16 * 2048 / 2.

These structs are used to configure a deep learning model with specific parameters for either Gemma7B or Gemma2B architecture.