llama_for_causal_lm.cpp 1.61 KB
Newer Older
1
#include "llama_for_causal_lm.hpp"
Your Name's avatar
Your Name committed
2
#include "infinicore/context/context.hpp"
3
4
#include "infinicore/nn/linear.hpp"
#include "infinicore/ops.hpp"
Ceng's avatar
Ceng committed
5
#include <iostream>
6
7
8

namespace infinilm::models::llama {

Your Name's avatar
Your Name committed
9
10
11
LlamaForCausalLM::LlamaForCausalLM(const LlamaConfig &config,
                                   const infinicore::Device &device,
                                   engine::distributed::RankInfo rank_info) {
12

Ceng's avatar
Ceng committed
13
    // Initialize module's device_ member
14
    device_ = device;
Ceng's avatar
Ceng committed
15

16
17
    const auto &dtype{config.dtype};

18
    // Initialize base model
19
    INFINICORE_NN_MODULE_INIT(model, config, device, rank_info);
20
21
22
23
24
25
26
27

    // Initialize language modeling head
    // Note: If tie_word_embeddings is true, we would share weights with embed_tokens
    // For now, we create a separate linear layer
    INFINICORE_NN_MODULE_INIT(lm_head, config.hidden_size, config.vocab_size, false,
                              dtype, device);
}

28
29
30
LlamaForCausalLM::Output LlamaForCausalLM::forward(const Input &input) const {
    const auto &[input_ids, position_ids, kv_cache] = input;

31
    // 1. Forward through base model to get hidden states
32
    auto position_ids_device = position_ids->to(device_);
Ceng's avatar
Ceng committed
33
    auto hidden_states = model_->forward(input_ids, position_ids_device, kv_cache);
34
35
36
37

    // 2. Apply language modeling head to get logits
    auto logits = lm_head_->forward(hidden_states);

38
    return {logits};
39
40
}

Ceng's avatar
Ceng committed
41
42
43
44
void LlamaForCausalLM::reset_cache(size_t pos) {
    model_->reset_cache(pos);
}

45
46
47
48
void LlamaForCausalLM::reset_cache(const cache::CacheConfig &new_config, size_t pos) {
    model_->reset_cache(new_config, pos);
}

49
} // namespace infinilm::models::llama