File size: 5,482 Bytes
fcd988f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16874d1
fcd988f
 
 
 
e987f7e
0ac3752
 
fcd988f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
---
license: mit
language:
- en
base_model:
- unsloth/Llama-3.2-1B-bnb-4bit
pipeline_tag: text-generation
tags:
- topic-modeling
- code
- github
- c4
- common-crawl
- wikipedia
- book3
- gutenburg
- arxiv
datasets:
- AmanPriyanshu/Dynamic-Topic-RedPajama-Data-1T-100k-SubSample-max-1k-tokens
---

# AmanPriyanshu/Dynamic-Topic-Modeling-Llama-3.2-1B-bnb-4bit

This repository contains code and documentation for the Llama 3.2 1B variant of our dynamic topic modeling series, based on the [RedPajama dataset subset we created for dynamic topic-modeling](https://amanpriyanshu.github.io/blogs/posts/2024/dynamic-topic-modeling/). Link to dataset: [AmanPriyanshu/Dynamic-Topic-RedPajama-Data-1T-100k-SubSample-max-1k-tokens](https://huggingface.co/datasets/AmanPriyanshu/Dynamic-Topic-RedPajama-Data-1T-100k-SubSample-max-1k-tokens)

## Model Comparisons

| Model | Parameters | Loss |
|-------|------------|------------|
| [Dynamic-Topic-Modeling-Llama-3.2-1B-bnb-4bit](https://huggingface.co/AmanPriyanshu/Dynamic-Topic-Modeling-Llama-3.2-1B-bnb-4bit) | 1B | 2.3959 |


## Model Overview

- Base Model: Unsloth/Llama-3.2-1B-bnb-4bit
- Fine-tuned Version: AmanPriyanshu/Dynamic-Topic-Modeling-Llama-3.2-1B-bnb-4bit
- Task: Hierarchical Topic Generation
- Training Data: 100k samples from RedPajama-1T

## Dataset Details

The model was trained on a carefully curated subset of the RedPajama-1T dataset:
- 100,000 documents
- Maximum 1,024 tokens per document
- Three-level hierarchical topic annotations
- Original sources include: CommonCrawl, C4, GitHub, Books, ArXiv, Wikipedia, StackExchange

## Model Architecture & Training

Key Configuration:
- Sequence Length: 2048 tokens
- LoRA Parameters:
  - Rank: 16
  - Alpha: 16
  - Target Modules: q_proj, k_proj, v_proj, up_proj, down_proj, o_proj, gate_proj
  - RSLoRA enabled

Training Parameters:
- Batch Size: 4
- Gradient Accumulation Steps: 2
- Learning Rate: 3e-4
- Epochs: 1
- Optimizer: AdamW 8-bit
- Weight Decay: 0.01
- Warmup Steps: 10

## Usage

### Installation
```bash
pip install unsloth transformers torch
```

### Inference Code
```python
from unsloth import FastLanguageModel
import torch
from transformers import TextStreamer

class LlamaInference:
    def __init__(self, model_path: str, device: str = "cuda"):
        self.device = device
        self.model, self.tokenizer = FastLanguageModel.from_pretrained(
            model_name=model_path,
            max_seq_length=2048,
            load_in_4bit=True,
            dtype=None,
        )
        self.model = FastLanguageModel.for_inference(self.model)
        self.model.eval()

    def generate_response(
        self,
        prompt: str,
        max_new_tokens: int = 512,
        temperature: float = 0.7,
        top_p: float = 0.9,
        stream: bool = True
    ) -> str:
        messages = [{"from": "human", "value": prompt}]
        inputs = self.tokenizer.apply_chat_template(
            messages,
            tokenize=True,
            add_generation_prompt=True,
            return_tensors="pt"
        ).to(self.device)

        streamer = TextStreamer(self.tokenizer) if stream else None
        
        with torch.no_grad():
            outputs = self.model.generate(
                input_ids=inputs,
                max_new_tokens=max_new_tokens,
                temperature=temperature,
                top_p=top_p,
                streamer=streamer,
                use_cache=True,
                pad_token_id=self.tokenizer.pad_token_id,
                eos_token_id=self.tokenizer.eos_token_id,
            )
        
        if not stream:
            response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
            response = response.split("assistant\n")[-1].strip()
            return response
```

### Example Usage
```python
model_path = "AmanPriyanshu/Dynamic-Topic-Modeling-Llama-3.2-1B-bnb-4bit"
inferencer = LlamaInference(model_path)
response = inferencer.generate_response("Your text here", stream=False)
```

## Output Format

The model generates hierarchical topics in the format:
`Domain > High-Level Topic > Specific Topic`

Example:

Input: """Machine learning (ML) is a field of study in artificial intelligence concerned with the development and study of statistical algorithms that can learn from data and generalize to unseen data, and thus perform tasks without explicit instructions.[1] Advances in the field of deep learning have allowed neural networks to surpass many previous approaches in performance.[2] ML finds application in many fields, including natural language processing, computer vision, speech recognition, email filtering, agriculture, and medicine.[3][4] The application of ML to business problems is known as predictive analytics. Statistics and mathematical optimization (mathematical programming) methods comprise the foundations of machine learning. Data mining is a related field of study, focusing on exploratory data analysis (EDA) via unsupervised learning.[6][7] From a theoretical viewpoint, probably approximately correct (PAC) learning provides a framework for describing machine learning."""

Output: "Machine Learning > Definition > Overview"

## License

This project is released under the MIT License.

## Citation

If you use this model or dataset in your research, please cite:

```bibtex
@misc{dynamic-topic-llama,
    author = {Aman Priyanshu},
    title = {Dynamic Topic Modeling Llama 3.2 1B},
    year = {2024},
    publisher = {HuggingFace}
}
```