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 고속도로 라이브러리를 통한 휴대용 SIMD를 사용하여 CPU 추론 및 추론 알고리즘의 설계 공간을 살펴봅니다. 최소한의 종속 항목을 사용하여 다른 프로젝트에 간단하게 삽입할 수 있으며, 약 2,000개 LoC 핵심 구현 (지원 유틸리티의 약 4K LoC 포함)으로 쉽게 수정할 수도 있습니다.

프로덕션 지향 에지 배포의 경우 JAX, Keras, PyTorch, Transformer와 같은 완성형 Python 프레임워크를 사용하는 표준 배포 경로를 사용하는 것이 좋습니다 (모든 모델 변형 참조).

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

빠른 시작

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

시스템 요구사항

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

1단계: Kaggle에서 모델 가중치 및 tokenizer 가져오기

Kaggle의 Gemma 모델 페이지로 이동하여 '모델 변형'을 선택합니다.

Gemma C++. On this tab, theVariation` 드롭다운에는 다음 옵션이 포함되어 있습니다. bfloat16 가중치 옵션은 충실도가 높고, 8비트 전환 부동 소수점 가중치는 추론 속도를 높입니다.

20억 개의 명령 조정 (it) 및 선행 학습된 (pt) 모델:

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

70억 개의 명령 조정 (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 파일 (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 파일 이름입니다. 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 파일 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"

위 경로를 다운로드의 모델 및 tokenizer 경로로 바꾸세요.

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

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.