llama_for_causal_lm.cpp 1.64 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
12
LlamaForCausalLM::LlamaForCausalLM(const LlamaConfig &config,
                                   const infinicore::Device &device,
                                   infinicore::DataType dtype,
                                   engine::distributed::RankInfo rank_info) {
13

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

17
    // Initialize base model
Your Name's avatar
Your Name committed
18
    INFINICORE_NN_MODULE_INIT(model, config, device, dtype, rank_info);
19
20
21
22
23
24
25
26

    // 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);
}

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

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

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

37
    return {logits};
38
39
}

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

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

48
} // namespace infinilm::models::llama