Llama-cpp로 Code LlaMa 실행하기

AI|2024. 1. 24. 15:41

Llama-cpp를 이용하면 GPU없이도 CPU만으로 일반 컴퓨터에서 Llama2를 실행할 수 있습니다. 이번 글에서는 그 과정을 살펴보겠습니다.

빌드하기

Ubuntu 22.04에서 테스트했습니다.

git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
make

모델 다운로드

아래 사이트에 가면 LlaMa2 모델을 다운로드 받는 방법이 나옵니다.

https://github.com/facebookresearch/llama

Meta 웹사이트에서 등록을해서 메일로 download URL을 받습니다. 받은 URL은 24시간만 유효하니 미리 모두 받는 것을 권장합니다.

https://ai.meta.com/resources/models-and-libraries/llama-downloads/

git clone https://github.com/facebookresearch/codellama
./download.sh  "email로 받은 URL"

...

Enter the list of models to download without spaces (7b,13b,34b,7b-Python,13b-Python,34b-Python,7b-Instruct,13b-Instruct,34b-Instruct), or press Enter for all:

 

모델 변환하기

로컬 PC에서 실행하려면 모델을 변환해야 합니다.

CodeLlama-7b 모델을 예로 하겠습니다.

우선 다운로드 받은 모델을 ggml 형식으로 변환합니다. 

python3 convert.py models/CodeLlama-7b/

바로 Inference 해보았습니다. multiply함수를 자바로 생성해주었습니다.

llama.cpp$ ./main -m ./models/CodeLlama-7b/ggml-model-f16.gguf -p "int multiply("
Log start
main: build = 1939 (57744932)
main: built with cc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 for x86_64-linux-gnu
main: seed  = 1706076174
llama_model_loader: loaded meta data with 16 key-value pairs and 291 tensors from ./models/CodeLlama-7b/ggml-model-f16.gguf (version GGUF V3 (latest))
llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.
llama_model_loader: - kv   0:                       general.architecture str              = llama
..
..

	repeat_last_n = 64, repeat_penalty = 1.100, frequency_penalty = 0.000, presence_penalty = 0.000
	top_k = 40, tfs_z = 1.000, top_p = 0.950, min_p = 0.050, typical_p = 1.000, temp = 0.800
	mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000
sampling order: 
CFG -> Penalties -> top_k -> tfs_z -> typical_p -> top_p -> min_p -> temp 
generate: n_ctx = 512, n_batch = 512, n_predict = -1, n_keep = 0


 int multiply(int n1, int n2) {
        if (n1 == 0 || n2 == 0) { // base case
            return 0;
        } else {
            return add(multiply(n1, n2 - 1), n1);
        }
    }

    public static int multiply2(int n1, int n2) {
        if (n1 == 0 || n2 == 0) { // base case
            return 0;
        } else {
            int result = n1 + multiply2(n1, n2 - 1); // 折半计算
            return result;
        }
    }

    public static void main(String[] args) {
        System.out.println("0 * 1 = " + multiply(0, 1));
        System.out.println("1 * 2 = " + multiply(1, 2));
        System.out.println("1 * 3 = " + multiply(1, 3));
        System.out.println("1 * 4 = " + multiply(1, 4));
        System.out.println("2 * 3 = " + multiply(2, 3));
        System.out.println("2 * 5 = " + multiply(2, 5));
        System.out.println("3 * 10 = " + multiply(3, 10));
        System.out.println("3 * 4 = " + multiply(3, 4));
        System.out.println("4 * 8 = " + multiply(4, 8));
        System.out.println("5 * 6 = " + multiply(5, 6));
        System.out. [end of text]

llama_print_timings:        load time =   59120.92 ms
llama_print_timings:      sample time =      49.16 ms /   398 runs   (    0.12 ms per token,  8095.19 tokens per second)
llama_print_timings: prompt eval time =     427.50 ms /     4 tokens (  106.88 ms per token,     9.36 tokens per second)
llama_print_timings:        eval time =  116470.88 ms /   397 runs   (  293.38 ms per token,     3.41 tokens per second)
llama_print_timings:       total time =  117027.28 ms /   401 tokens
Log end

그런데 1분정도 시간이 걸렸습니다. 이제 4비트 모델로 변환해서 성능을 높여보겠습니다.

4비트 모델로 변환하기 (Quantization)

./quantize ./models/CodeLlama-7b/ggml-model-f16.gguf ./models/CodeLlama-7b/ggml-model-q4_0.gguf q4_0

Inference 해보기

-n 으로 token수를 지정할 수 있습니다.

llama.cpp$ ./main -m ./models/CodeLlama-7b/ggml-model-q4_0.gguf -n 256 -p "int multiply("
Log start
main: build = 1939 (57744932)
main: built with cc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 for x86_64-linux-gnu
main: seed  = 1706076680
llama_model_loader: loaded meta data with 17 key-value pairs and 291 tensors from ./models/CodeLlama-7b/ggml-model-q4_0.gguf (version GGUF V3 (latest))
llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.
llama_model_loader: - kv   0:                       general.architecture str              = llama
llama_model_loader: - kv   1:                               general.name str              = models
llama_model_loader: - kv   2:                       llama.context_length u32              = 16384
llama_model_loader: - kv   3:                     llama.embedding_length u32              = 4096
llama_model_loader: - kv   4:                          llama.block_count u32              = 32
llama_model_loader: - kv   5:                  llama.feed_forward_length u32              = 11008
llama_model_loader: - kv   6:                 llama.rope.dimension_count u32              = 128
llama_model_loader: - kv   7:                 llama.attention.head_count u32              = 32
llama_model_loader: - kv   8:              llama.attention.head_count_kv u32              = 32
llama_model_loader: - kv   9:     llama.attention.layer_norm_rms_epsilon f32              = 0.000010
llama_model_loader: - kv  10:                       llama.rope.freq_base f32              = 1000000.000000
llama_model_loader: - kv  11:                          general.file_type u32              = 2
llama_model_loader: - kv  12:                       tokenizer.ggml.model str              = llama
llama_model_loader: - kv  13:                      tokenizer.ggml.tokens arr[str,32016]   = ["<unk>", "<s>", "</s>", "<0x00>", "<...
llama_model_loader: - kv  14:                      tokenizer.ggml.scores arr[f32,32016]   = [0.000000, 0.000000, 0.000000, 0.0000...
llama_model_loader: - kv  15:                  tokenizer.ggml.token_type arr[i32,32016]   = [2, 3, 3, 6, 6, 6, 6, 6, 6, 6, 6, 6, ...
llama_model_loader: - kv  16:               general.quantization_version u32              = 2
llama_model_loader: - type  f32:   65 tensors
llama_model_loader: - type q4_0:  225 tensors
llama_model_loader: - type q6_K:    1 tensors
llm_load_vocab: mismatch in special tokens definition ( 264/32016 vs 259/32016 ).
llm_load_print_meta: format           = GGUF V3 (latest)
llm_load_print_meta: arch             = llama
llm_load_print_meta: vocab type       = SPM
llm_load_print_meta: n_vocab          = 32016
llm_load_print_meta: n_merges         = 0
llm_load_print_meta: n_ctx_train      = 16384
llm_load_print_meta: n_embd           = 4096
llm_load_print_meta: n_head           = 32
llm_load_print_meta: n_head_kv        = 32
llm_load_print_meta: n_layer          = 32
llm_load_print_meta: n_rot            = 128
llm_load_print_meta: n_embd_head_k    = 128
llm_load_print_meta: n_embd_head_v    = 128
llm_load_print_meta: n_gqa            = 1
llm_load_print_meta: n_embd_k_gqa     = 4096
llm_load_print_meta: n_embd_v_gqa     = 4096
llm_load_print_meta: f_norm_eps       = 0.0e+00
llm_load_print_meta: f_norm_rms_eps   = 1.0e-05
llm_load_print_meta: f_clamp_kqv      = 0.0e+00
llm_load_print_meta: f_max_alibi_bias = 0.0e+00
llm_load_print_meta: n_ff             = 11008
llm_load_print_meta: n_expert         = 0
llm_load_print_meta: n_expert_used    = 0
llm_load_print_meta: rope scaling     = linear
llm_load_print_meta: freq_base_train  = 1000000.0
llm_load_print_meta: freq_scale_train = 1
llm_load_print_meta: n_yarn_orig_ctx  = 16384
llm_load_print_meta: rope_finetuned   = unknown
llm_load_print_meta: model type       = 7B
llm_load_print_meta: model ftype      = Q4_0
llm_load_print_meta: model params     = 6.74 B
llm_load_print_meta: model size       = 3.56 GiB (4.54 BPW) 
llm_load_print_meta: general.name     = models
llm_load_print_meta: BOS token        = 1 '<s>'
llm_load_print_meta: EOS token        = 2 '</s>'
llm_load_print_meta: UNK token        = 0 '<unk>'
llm_load_print_meta: LF token         = 13 '<0x0A>'

sampling: 
	repeat_last_n = 64, repeat_penalty = 1.100, frequency_penalty = 0.000, presence_penalty = 0.000
	top_k = 40, tfs_z = 1.000, top_p = 0.950, min_p = 0.050, typical_p = 1.000, temp = 0.800
	mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000
sampling order: 
CFG -> Penalties -> top_k -> tfs_z -> typical_p -> top_p -> min_p -> temp 
generate: n_ctx = 512, n_batch = 512, n_predict = 256, n_keep = 0


 int multiply(int a, int b) {
	return a * b;
}

int divide(int a, int b) {
	return a / b;
}
```

We can add some simple validation to the function to make sure the input values are sane.  We'll just ensure that `a` and `b` are greater than zero:

```csharp
[DllImport("MyMath")]
public static extern int multiply(int a, int b);

[DllImport("MyMath")]
public static extern int divide(int a, int b);

// Note that we've added the [SuppressUnmanagedCodeSecurity] attribute here.  
[SuppressUnmanagedCodeSecurity] 
unsafe private static TDelegate LoadFunction<TDelegate>(string functionName) where TDelegate : class {
    var ptr = GetProcAddress(LoadLibrary("MyMath"), functionName);
    if (ptr == IntPtr.Zero)
        throw new InvalidOperationException($"Failed to get address for: '{functionName}'");

	var fp = Marshal.GetDelegateForFunctionPointer<TDelegate>(ptr);
   
llama_print_timings:        load time =     227.93 ms
llama_print_timings:      sample time =      33.48 ms /   256 runs   (    0.13 ms per token,  7647.27 tokens per second)
llama_print_timings: prompt eval time =     144.80 ms /     4 tokens (   36.20 ms per token,    27.62 tokens per second)
llama_print_timings:        eval time =   24956.50 ms /   255 runs   (   97.87 ms per token,    10.22 tokens per second)
llama_print_timings:       total time =   25187.38 ms /   259 tokens
Log end

이번에는 C#  코드가 나왔네요. finetuning이  안된 모델이라서 아무렇게나(?) 코드가 생성됩니다. 4bit로 quantization를 하니까 성능이 2배 정도 빨라졌습니다. 

13478367200 Jan 23 19:47 ggml-model-f16.gguf
 3825898016 Jan 23 19:52 ggml-model-q4_0.gguf

모델 크기는 3배 이상 줄어들었습니다. 32비트를 4비트로 줄였으니, 당연한 결과겠지요.

참고 

* https://blog.gopenai.com/how-to-run-llama-2-and-code-llama-on-your-laptop-without-gpu-3ab68dd15d4a

댓글()