File size: 8,972 Bytes
3112326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3c41e8
 
 
1dcec6c
 
a3c41e8
 
 
 
 
1dcec6c
a3c41e8
1dcec6c
 
 
 
 
 
a3c41e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dcec6c
 
 
a3c41e8
 
 
 
 
1dcec6c
a3c41e8
1dcec6c
a3c41e8
 
 
 
 
 
 
 
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
---
language:
  - en
library_name: transformers
pipeline_tag: text-generation
tags:
  - qwen
  - loop-dfs
  - kenya
  - financial-services
  - customer-support
  - instruction-tuned
  - conversational
  - merged
base_model: Qwen/Qwen2.5-7B-Instruct
base_model_relation: finetune
license: mit
inference: true
widget:
  - text: "Who is the CEO of LOOP DFS Kenya?"
  - text: "Write python code to query transactions made to my account using merchanttransactioninquiry API"
  - text: "Explain LOOP FLEX."
  - text: "What is a current corporate partner for the LOOP NeoBank in Kenya?"
model-index:
  - name: LOOP DFS Qwen Merged 16-bit Model
    results: []
---

# LOOP DFS Qwen Merged 16-bit Model

### Revised `README.md`

````markdown
# LOOP DFS Qwen Merged 16-bit Model

This repository contains a merged 16-bit Qwen model fine-tuned for LOOP DFS assistance.

The model is designed to answer questions about LOOP DFS company information, products, services, partnerships, and documented API behavior.

## Generation configuration

The recommended generation settings are:

- `max_new_tokens`: 512
- `temperature`: 0.2
- `top_p`: 0.9
- `repetition_penalty`: 1.05

The complete system prompt is stored in `system_prompt.txt`.

Machine-readable inference settings are stored in `deployment_config.json`.

## Quick start

Install the required packages:

```bash
pip install -U transformers accelerate huggingface_hub sentencepiece torch
```

Load the model and its system prompt directly from this public repository:


```python
import torch
from huggingface_hub import hf_hub_download
from transformers import AutoModelForCausalLM, AutoTokenizer


MODEL_ID = "RayNene/Loop-DFS-Qwen-Merged"
MAX_NEW_TOKENS = 512


# Load the complete system prompt from the repository.
system_prompt_path = hf_hub_download(
    repo_id=MODEL_ID,
    filename="system_prompt.txt",
)

with open(system_prompt_path, "r", encoding="utf-8") as file:
    SYSTEM_PROMPT = file.read().strip()

if not SYSTEM_PROMPT:
    raise RuntimeError("system_prompt.txt is empty.")


# Select an appropriate inference data type.
if torch.cuda.is_available():
    inference_dtype = (
        torch.bfloat16
        if torch.cuda.is_bf16_supported()
        else torch.float16
    )
else:
    inference_dtype = torch.float32


# Load the tokenizer.
tokenizer = AutoTokenizer.from_pretrained(
    MODEL_ID,
    trust_remote_code=True,
)

if tokenizer.pad_token_id is None:
    tokenizer.pad_token = tokenizer.eos_token


# Load the merged model.
model = AutoModelForCausalLM.from_pretrained(
    MODEL_ID,
    torch_dtype=inference_dtype,
    device_map="auto",
    trust_remote_code=True,
    low_cpu_mem_usage=True,
)

model.eval()


# Configure valid end-of-response tokens.
terminator_ids = []

for token_id in [
    tokenizer.eos_token_id,
    tokenizer.convert_tokens_to_ids("<|im_end|>"),
]:
    if token_id is None:
        continue

    if token_id == tokenizer.unk_token_id:
        continue

    if token_id not in terminator_ids:
        terminator_ids.append(token_id)

if not terminator_ids:
    raise RuntimeError("No valid generation terminator was found.")


def clean_answer(answer):
    """Prevent accidental generation of another conversation turn."""
    stop_markers = [
        "<|im_end|>",
        "<|im_start|>system",
        "<|im_start|>user",
        "<|im_start|>assistant",
        "\nSystem:",
        "\nUser:",
    ]

    positions = [
        answer.find(marker)
        for marker in stop_markers
        if answer.find(marker) >= 0
    ]

    if positions:
        answer = answer[:min(positions)]

    return answer.strip()


def ask(question, history=None):
    """Generate one LOOP DFS assistant response."""
    if not isinstance(question, str) or not question.strip():
        raise ValueError("The question must be a non-empty string.")

    if history is None:
        history = []

    messages = [
        {
            "role": "system",
            "content": SYSTEM_PROMPT,
        },
        *history,
        {
            "role": "user",
            "content": question.strip(),
        },
    ]

    prompt = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True,
    )

    inputs = tokenizer(
        prompt,
        return_tensors="pt",
        add_special_tokens=False,
    )

    input_device = model.get_input_embeddings().weight.device

    inputs = {
        name: tensor.to(input_device)
        for name, tensor in inputs.items()
    }

    prompt_length = inputs["input_ids"].shape[1]

    with torch.inference_mode():
        output = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=True,
            temperature=0.2,
            top_p=0.9,
            repetition_penalty=1.05,
            eos_token_id=terminator_ids,
            pad_token_id=tokenizer.pad_token_id,
            use_cache=True,
        )

    generated_tokens = output[0, prompt_length:]

    answer = tokenizer.decode(
        generated_tokens,
        skip_special_tokens=True,
    )

    return clean_answer(answer)


answer = ask("Who is the CEO of LOOP DFS Kenya?")
print(answer)
```

## Interactive chat

The following starter code maintains conversation history and uses the complete system prompt loaded from `system_prompt.txt`:

```python
conversation = []

print("LOOP DFS Assistant")
print("Commands: clear | exit | quit")
print()

while True:
    try:
        user_message = input("You: ").strip()

        if not user_message:
            continue

        command = user_message.lower()

        if command in {"exit", "quit"}:
            print("Chat ended.")
            break

        if command == "clear":
            conversation.clear()
            print("Conversation history cleared.")
            print()
            continue

        response = ask(
            question=user_message,
            history=conversation,
        )

        print(f"\nLOOP DFS Assistant: {response}\n")

        conversation.extend(
            [
                {
                    "role": "user",
                    "content": user_message,
                },
                {
                    "role": "assistant",
                    "content": response,
                },
            ]
        )

    except KeyboardInterrupt:
        print("\nChat ended.")
        break
```

## Google Colab starter

In a new Google Colab notebook:

1. Select **Runtime β†’ Change runtime type β†’ GPU**.
2. Run the installation cell:

```python
!pip -q install -U transformers accelerate huggingface_hub sentencepiece
```

3. Run the Python code from the **Quick start** section.
4. Run the **Interactive chat** section.

No Hugging Face token is required because the repository is public.

## Loading the deployment configuration

Applications can load the recommended generation configuration directly from `deployment_config.json`:

```python
import json
from huggingface_hub import hf_hub_download


config_path = hf_hub_download(
    repo_id="RayNene/Loop-DFS-Qwen-Merged",
    filename="deployment_config.json",
)

with open(config_path, "r", encoding="utf-8") as file:
    deployment_config = json.load(file)

print(deployment_config)
```

It can then be applied during generation:

```python
output = model.generate(
    **inputs,
    max_new_tokens=deployment_config.get(
        "max_new_tokens",
        512,
    ),
    do_sample=deployment_config.get(
        "do_sample",
        True,
    ),
    temperature=deployment_config.get(
        "temperature",
        0.2,
    ),
    top_p=deployment_config.get(
        "top_p",
        0.9,
    ),
    repetition_penalty=deployment_config.get(
        "repetition_penalty",
        1.05,
    ),
    eos_token_id=terminator_ids,
    pad_token_id=tokenizer.pad_token_id,
    use_cache=True,
)
```

## Deployment requirements

Current company facts, product terms, fees, eligibility requirements, leadership information, partnerships, and API behavior should be supplied through approved retrieval sources or verified tools.

Authentication and authorization must be handled outside the conversation. The assistant must never collect passwords, PINs, OTPs, CVVs, secret keys, access tokens, or other authentication credentials through chat.

Financial transactions must be validated by application code, summarized for the user, and explicitly confirmed through an approved secure flow. The model must not be used as the transaction authorization layer.

## Repository files

- `system_prompt.txt` β€” complete production system prompt
- `deployment_config.json` β€” recommended generation and deployment settings
- `config.json` β€” model architecture configuration
- `generation_config.json` β€” model generation configuration, when included
- `tokenizer_config.json` β€” tokenizer configuration
- `tokenizer.json` β€” tokenizer vocabulary and rules, when included
- `*.safetensors` β€” merged model weights
````