File size: 20,837 Bytes
6bde718 013b69f 6bde718 16cd86b 6bde718 16cd86b 6bde718 16cd86b 6bde718 16cd86b 364b5d4 d9130e5 3559e8d bec11c7 3559e8d 58000b1 d9130e5 58000b1 d9130e5 58000b1 d9130e5 58000b1 d9130e5 58000b1 d9130e5 58000b1 d9130e5 58000b1 d9130e5 44319e3 8348df6 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 f33b03c 364b5d4 ecee486 364b5d4 b97bbfa 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ecee486 364b5d4 ed4a067 de24132 364b5d4 44319e3 364b5d4 16cd86b 6bde718 9447cb0 47173a2 8905658 6bde718 2092913 051503e bec11c7 f6ed970 571ea1b 051503e 571ea1b f6ed970 571ea1b ca95c4e b96a77d 8905658 8d8e209 8905658 8d8e209 a39d9bc c13272f 8d8e209 8905658 8d8e209 8905658 8d8e209 dc17918 e754b06 6a4d52c dc17918 b0302cd 6a4d52c dc17918 a39d9bc 7876f42 bec11c7 ed8f868 f5973df 7876f42 f5973df a0817a1 bec11c7 f5973df 4645ed5 a0817a1 f5973df bec11c7 a0817a1 |
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 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 |
---
base_model:
- winglian/llama-3-8b-256k-PoSE
- Locutusque/Llama-3-Orca-1.0-8B
- NousResearch/Meta-Llama-3-8B
- abacusai/Llama-3-Smaug-8B
- beomi/Llama-3-Open-Ko-8B-Instruct-preview
- NousResearch/Meta-Llama-3-8B-Instruct
library_name: transformers
tags:
- mergekit
- merge
---
# π°π· SmartLlama-3-Ko-8B-256k-PoSE
<a href="https://ibb.co/rs8DhB8"><img src="https://i.ibb.co/8cv1wyv/Smart-Llama-3-Ko-8-B-256k-Po-SE.png" alt="Smart-Llama-3-Ko-8-B-256k-Po-SE" border="0"></a>
SmartLlama-3-Ko-8B-256k-[PoSE](https://huggingface.co/papers/2309.10400) is an advanced AI model that integrates the capabilities of several advanced language models, designed to excel in a variety of tasks ranging from technical problem-solving to multilingual communication, especially with its extended context length of 256k tokens. This model is uniquely positioned to handle larger and more complex datasets and longer conversational contexts, making it ideal for deep learning applications requiring extensive text understanding and generation.
## π Merge Details
### Component Models and Contributions
- **NousResearch/Meta-Llama-3-8B and Meta-Llama-3-8B-Instruct**: These models provide a solid foundation for general language understanding and instruction-following capabilities.
- **winglian/llama-3-8b-256k-PoSE**: Utilizes Positional Skip-wise Training (PoSE) to extend Llama's context length to 256k, significantly improving the model's ability to handle extensive texts and complex instructions, enhancing performance in tasks requiring long-duration focus and memory.
- **Locutusque/Llama-3-Orca-1.0-8B**: Specializes in mathematical, coding, and writing tasks, bringing precision to technical and creative outputs.
- **abacusai/Llama-3-Smaug-8B**: Improves the model's performance in real-world, multi-turn conversations, which is crucial for applications in customer service and interactive learning environments.
- **beomi/Llama-3-Open-Ko-8B-Instruct-preview**: Focuses on improving understanding and generation of Korean, offering robust solutions for bilingual or multilingual applications targeting Korean-speaking audiences.
## πΌοΈ Key Features
- **Extended Context Length**: Utilizes the PoSE (Positional Encoding) technique to handle up to 256,000 tokens, making it ideal for analyzing large volumes of text such as books, comprehensive reports, and lengthy communications.
- **Multilingual Support**: While primarily focused on Korean language processing, this model also provides robust support for multiple languages, enhancing its utility in global applications.
- **Advanced Integration of Models**: Combines strengths from various models including NousResearch's Meta-Llama-3-8B, the instruction-following capabilities of Llama-3-Open-Ko-8B-Instruct-preview, and specialized capabilities from models like Llama-3-Smaug-8B for nuanced dialogues and Orca-1.0-8B for technical precision.
## π¨ Models Merged
The following models were included in the merge:
- **winglian/llama-3-8b-256k-PoSE**: [Extends the context handling capability](https://huggingface.co/winglian/llama-3-8b-256k-PoSE). This model uses Positional Skip-wise Training (PoSE) to enhance the handling of extended context lengths, up to 256k tokens.
- **Locutusque/Llama-3-Orca-1.0-8B**: [Enhances abilities in handling technical content](https://huggingface.co/Locutusque/Llama-3-Orca-1.0-8B). Specialized in computational, scientific, and technical tasks, improving the model's ability to process complex academic and technical language.
- **abacusai/Llama-3-Smaug-8B**: [Improves multi-turn conversational abilities](https://huggingface.co/abacusai/Llama-3-Smaug-8B). Boosts performance in engaging in lengthy, context-aware dialogues necessary for effective customer service and interactive learning.
- **beomi/Llama-3-Open-Ko-8B-Instruct-preview**: [Provides enhanced capabilities for Korean language processing](https://huggingface.co/beomi/Llama-3-Open-Ko-8B-Instruct-preview). This model is fine-tuned to understand and generate Korean, making it ideal for applications targeting Korean-speaking users.
- **NousResearch/Meta-Llama-3-8B-Instruct**: [Offers advanced instruction-following capabilities](https://huggingface.co/NousResearch/Meta-Llama-3-8B-Instruct). It is optimized to follow complex instructions, enhancing the model's utility in task-oriented dialogues and applications that require a high level of understanding and execution of user commands.
### ποΈ Merge Method
- **DARE TIES**: This method was employed to ensure that each component model contributes effectively to the merged model, maintaining a high level of performance across diverse applications. NousResearch/Meta-Llama-3-8B served as the base model for this integration, providing a stable and powerful framework for the other models to build upon.
## π» Ollama
```
ollama create smartllama-3-Ko-8b-256k-pose -f ./Modelfile_Q5_K_M
```
[Modelfile_Q5_K_M]
```
FROM smartllama-3-ko-8b-256k-pose-Q5_K_M.gguf
TEMPLATE """
{{- if .System }}
system
<s>{{ .System }}</s>
{{- end }}
user
<s>Human:
{{ .Prompt }}</s>
assistant
<s>Assistant:
"""
SYSTEM """
μΉμ ν μ±λ΄μΌλ‘μ μλλ°©μ μμ²μ μ΅λν μμΈνκ³ μΉμ νκ² λ΅νμ. κΈΈμ΄μ μκ΄μμ΄ λͺ¨λ λλ΅μ νκ΅μ΄(Korean)μΌλ‘ λλ΅ν΄μ€.
"""
PARAMETER temperature 0.7
PARAMETER num_predict 3000
PARAMETER num_ctx 256000
PARAMETER stop "<s>"
PARAMETER stop "</s>"
```
## π» Ollama Python Summarizing Normal Test Code
install all of these libraries
```
pip install requests beautifulsoup4 PyPDF2 langchain-community langchain
```
pose_test.py
```
import sys
import os
import requests
from bs4 import BeautifulSoup
import PyPDF2
from langchain_community.chat_models import ChatOllama
from langchain.schema import AIMessage, HumanMessage, SystemMessage
def clean_output(text):
text = text.replace("</s>", "").strip()
return text
def invoke_model(text):
messages = [
SystemMessage(content='You are an expert copywriter with expertise in summarizing documents.'),
HumanMessage(content=f'Please provide a short and concise summary of the following text:\nTEXT: {text}')
]
try:
llm = ChatOllama(model="pose:latest")
summary_output = llm.invoke(messages)
if isinstance(summary_output, AIMessage):
cleaned_content = clean_output(summary_output.content)
return cleaned_content
else:
return "Unexpected data type for model output."
except Exception as e:
print(f"An error occurred while processing the model output: {str(e)}")
return None
def fetch_text_from_url(url):
try:
response = requests.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
content = soup.find('div', {'id': 'bodyContent'})
paragraphs = content.find_all('p')
text_content = ' '.join(p.text for p in paragraphs)
return text_content
except requests.RequestException as e:
print(f"Failed to fetch data from URL: {str(e)}")
return None
def read_text_file(file_path):
with open(file_path, "r", encoding="utf-8") as file:
return file.read()
def read_pdf(file_path):
with open(file_path, "rb") as file:
reader = PyPDF2.PdfReader(file)
text_content = ""
for page in reader.pages:
extracted_text = page.extract_text()
if extracted_text:
text_content += extracted_text + "\n"
return text_content
def summarize_content(source):
if source.startswith(('http://', 'https://')):
text_content = fetch_text_from_url(source)
else:
_, file_extension = os.path.splitext(source)
if file_extension.lower() == '.pdf':
text_content = read_pdf(source)
elif file_extension.lower() in ['.txt', '.text']:
text_content = read_text_file(source)
else:
print("Unsupported file type")
return
if text_content:
summary = invoke_model(text_content)
print("Summary of the document:")
print(summary)
else:
print("No text found or unable to extract text from source.")
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: python script.py <file_path_or_url>")
else:
source = sys.argv[1]
summarize_content(source)
```
run txt file (assume txt is a.txt)
```
python pose_test.py a.txt
```
run url (assume txt is url)
```
python pose_test.py url
```
You can find both test results below on the section : Test Result1
## π» Ollama Python Summarizing Test Code for the target lang response
install all of these libraries
```
pip install requests beautifulsoup4 PyPDF2 googletrans==4.0.0-rc1 langchain-community langchain aiohttp asyncio aiofiles
```
pose_lang.py
```
import sys
import os
import aiohttp
import PyPDF2
from bs4 import BeautifulSoup
from langchain_community.chat_models import ChatOllama
from langchain.schema import AIMessage, HumanMessage, SystemMessage
from googletrans import Translator
import logging
import asyncio
import aiofiles
# Setup logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
def clean_output(text):
"""Cleans the model output text."""
text = text.replace("</s>", "").strip() # Specific cleaning operation
return text
def translate_text(text, src_lang, dest_lang):
"""Translates text from source language to destination language using Google Translate."""
if src_lang == dest_lang:
return text
translator = Translator()
try:
translation = translator.translate(text, src=src_lang, dest=dest_lang)
return translation.text
except Exception as e:
logging.error(f"Translation failed: {e}")
return text
def detect_language(text):
"""Detects the language of the given text."""
translator = Translator()
try:
detected = translator.detect(text)
return detected.lang
except Exception as e:
logging.error(f"Language detection failed: {e}")
return None
async def invoke_model(text, target_lang):
"""Asynchronously invokes the chat model and processes the response with language-specific instructions."""
llm = ChatOllama(model="pose:latest")
try:
# Define messages based on target language
if target_lang == 'ko':
messages = [
SystemMessage(content='λ¬Έμμ ν΅μ¬ μμ½μ μμΈνκ² μ κ³΅ν΄ μ£Όμ€ μ λ¬Έκ°λ‘μ, λ€μ λ¬Έμλ₯Ό μμ½ν΄ μ£ΌμΈμ.'),
HumanMessage(content=f'λ€μ ν
μ€νΈμ λν μ λ¬Έμ μμ½μ μ κ³΅ν΄ μ£ΌμΈμ. μμ½μ νκ΅μ΄μ μΈμ΄μ λμμ€μ λ§κ² μ΅κ³ μμ€μ λͺ
νμ±κ³Ό μΈλΆ μ¬νμ μ€μν΄μΌ ν©λλ€:\n\nTEXT: {text}')
]
else: # default to English if not Korean
messages = [
SystemMessage(content='As an adept summarizer, your expertise is required to condense the following document into its essential points in detail.'),
HumanMessage(content=f'Kindly provide an expert summary of the text below, adhering to the highest standards of clarity and detail. Ensure the response is tailored to the linguistic nuances of English:\n\nTEXT: {text}')
]
# Since invoke is not awaitable, run it in a thread if it's blocking
response = await asyncio.to_thread(llm.invoke, messages)
if isinstance(response, AIMessage):
cleaned_content = clean_output(response.content)
content_lang = detect_language(cleaned_content)
print(f"Current content language: {content_lang}, Target language to be translated to: {target_lang}")
if content_lang != target_lang:
return translate_text(cleaned_content, content_lang, target_lang)
return cleaned_content
else:
raise ValueError("Model did not return an AIMessage")
except Exception as e:
logging.error(f"Error during model invocation: {e}")
return "Model invocation failed."
async def fetch_text_from_url(url):
"""Asynchronously fetches and extracts text content from a given URL."""
async with aiohttp.ClientSession() as session:
try:
async with session.get(url) as response:
content = await response.text()
soup = BeautifulSoup(content, 'html.parser')
main_content = soup.select_one('#mw-content-text, #bodyContent, .content')
if not main_content:
logging.error("No content found in the expected sections.")
return None
text_content = ' '.join(p.get_text() for p in main_content.find_all(['p', 'li'], string=True))
return text_content
except Exception as e:
logging.error(f"Error fetching URL content: {e}")
return None
async def read_text_file(file_path):
"""Asynchronously reads text from a text file."""
async with aiofiles.open(file_path, mode='r', encoding='utf-8') as file:
text_content = await file.read()
return text_content
async def read_pdf(file_path):
"""Asynchronously reads text from a PDF file."""
def sync_read_pdf(path):
try:
with open(path, "rb") as file:
reader = PyPDF2.PdfReader(file)
return ' '.join(page.extract_text() for page in reader.pages if page.extract_text())
except Exception as e:
logging.error(f"Error reading PDF file: {e}")
return None
return await asyncio.to_thread(sync_read_pdf, file_path)
async def summarize_content(source, language):
"""Processes input source (URL, file, text) and outputs a summary in the specified language asynchronously."""
print("Processing input...")
text_content = None
if source.startswith(('http://', 'https://')):
print("Fetching content from URL...")
text_content = await fetch_text_from_url(source)
elif os.path.isfile(source):
_, file_extension = os.path.splitext(source)
if file_extension.lower() == '.pdf':
print("Reading PDF...")
text_content = await read_pdf(source)
elif file_extension.lower() in ['.txt', '.text']:
print("Reading text file...")
text_content = await read_text_file(source)
else:
print("Unsupported file type")
return
else:
print("Unsupported file type")
return
if text_content:
print("Summarizing content...")
summary = await invoke_model(text_content, language)
print("\n--- Summary of the document ---\n")
print(summary)
else:
print("No text found or unable to extract text from source.")
if __name__ == '__main__':
if len(sys.argv) < 3:
print("Usage: python script.py <file_path_or_url_or_text> <language>")
print("Language should be 'ko' for Korean or 'en' for English.")
else:
source = sys.argv[1]
language = sys.argv[2]
asyncio.run(summarize_content(source, language))
```
run txt file (assume txt is a.txt)
```
Korean response : python pose_lang a.txt ko
English response : python pose_lang a.txt en
```
run pdf file (assume pdf is a.pdf)
```
Korean response : python pose_lang a.pdf ko
English response : python pose_lang a.pdf en
```
run url (assume url is wikepedia)
```
Korean response : python pose_lang url ko
English response : python pose_lang url en
```
I added additional Google Translator here. If you request an answer in Korean and the answer is in English sometimes for the lang hallucination, this function detects it and answers you in Korean.
Conversely, if you request a response in English and the response is in Korean for the lang hallucination, this function detects it and responds in English.
You can find both test results below on the section : Test Result2 for target lang response
### ποΈ Configuration
The YAML configuration for this model:
```yaml
models:
- model: NousResearch/Meta-Llama-3-8B
# Base model providing a general foundation without specific parameters
- model: NousResearch/Meta-Llama-3-8B-Instruct
parameters:
density: 0.60
weight: 0.25
- model: winglian/llama-3-8b-256k-PoSE
parameters:
density: 0.60
weight: 0.20
- model: Locutusque/Llama-3-Orca-1.0-8B
parameters:
density: 0.55
weight: 0.15
- model: abacusai/Llama-3-Smaug-8B
parameters:
density: 0.55
weight: 0.15
- model: beomi/Llama-3-Open-Ko-8B-Instruct-preview
parameters:
density: 0.55
weight: 0.30
merge_method: dare_ties
base_model: NousResearch/Meta-Llama-3-8B
parameters:
int8_mask: true
dtype: bfloat16
```
Test OS Condition
```
Hardware Overview:
Model Name: MacBook Pro
Model Identifier: MacBookPro18,2
Chip: Apple M1 Max
Total Number of Cores: 10 (8 performance and 2 efficiency)
Memory: 64 GB
System Firmware Version: 10151.101.3
OS Loader Version: 10151.101.3
```
### π Test Result1 (Normal)
**SmartLlama-3-Ko-8B-256k-PoSE Summary Ability**
consideration
Long sentences seemed to summarize well, but I observed that answers came in English. And when I asked for it to be translated into Korean, I confirmed that it was translated well. The summary seems to work well, but you can take into account the fact that there are times when it cannot be summarized directly in Korean.
## Summary of Britney Spears on Wikipedia
[![Britney Spears Singer Wikipedia Summary](https://i.ibb.co/2600HbV/Screenshot-2024-05-02-at-11-52-58-AM.png)](https://ibb.co/7zxxL9M)
## Summary of Steve Jobs Text File
[![Steve Jobs Text File Summary](https://i.ibb.co/10tRCrj/Screenshot-2024-05-02-at-11-54-50-AM.png)](https://ibb.co/9pkyxbS)
## Summary of Jay Park on Wikipedia
[![Jay Park Wikipedia Summary](https://i.ibb.co/nmkpbCt/Screenshot-2024-05-02-at-1-33-30-PM.png)](https://ibb.co/g9gY3Vh)
### π Test Result2 (Target Language Summary Return)
**SmartLlama-3-Ko-8B-256k-PoSE Summary Ability**
consideration
I added additional Google Translator here. If you request an answer in Korean and the answer is in English, this function detects it and answers you in Korean.
Conversely, if you request a response in English and the response is in Korean, this function detects it and responds in English.
If you don't get a clear answer, try running it several times.
## Summary of economy pdf
```
python final2.py economy.pdf ko
# if you want english summary, en
```
[![Economy pdf Summary](https://i.ibb.co/QftXyWQ/Screenshot-2024-05-02-at-9-05-51-PM.png)](https://ibb.co/JKgCDYt)
## Summary of Steve Jobs Text File
```
python final2.py steve.txt ko
# if you want english summary, en
```
[![Steve Jobs Text File Summary](https://i.ibb.co/1nmqWxk/Screenshot-2024-05-02-at-8-57-20-PM.png)](https://ibb.co/PY6hH8d)
## Summary of Jay Park on Wikipedia
```
python final2.py https://en.wikipedia.org/wiki/Jay_Park ko
# if you want english summary, en
```
[![Jay Park Wikipedia Summary](https://i.ibb.co/Ssk4tdY/Screenshot-2024-05-02-at-8-54-19-PM.png)](https://ibb.co/j6CPyW0)
**Test Source From**
[λ°μ¬λ² - wikipedia - EN](https://en.wikipedia.org/wiki/Jay_Park)
[λ°μ¬λ² - wikipedia - KR](https://ko.wikipedia.org/wiki/%EB%B0%95%EC%9E%AC%EB%B2%94)
[Britney Spears - wikipedia - EN](https://en.wikipedia.org/wiki/Britney_Spears)
[νκ΅μν κ²½μ μ λ§ λ³΄κ³ μ - KR](https://www.bok.or.kr/viewer/skin/doc.html?fn=202402290251197820.pdf&rs=/webview/result/P0002359/202402)
[Community member : Mr Han' steve jobs txt file]
### βοΈ Test Issue
2024-05-02
```
If you use load_summarize_chain(), there will be repetition. -> community member Mr.Han issue
Is it a merge issue? He thinks the merge target may be the issue.
chain = load_summarize_chain(
llm,
chain_type='stuff',
prompt=prompt,
verbose=False
)
output_summary = chain.invoke(docs)
-> investigating for me how to solve.....
```
```
Mr.Han is investgating the symptoms
Your OS is using REDHAT. Even if I run the code using the LLAMA3 model provided by ollama, there is an error.
I wonder if I should wait a little longer for Red Hat...
<|eot_id|><|start_header_id|>assistant<|end_header_id|>, ... omitted
Ha ha, thanks for the chat! You too have a great day and happy summarizing if you need it again soon!<|eot_id|><|start_header_id|>assistant<|end_header_id|>
It's not a merge problem... I think it's a fundamental problem that doesn't fit the OS environment... so I'm sharing it with you. Is there anyone who has the same problem as me in redhat?
```
|