Compare commits
No commits in common. "refs/deployment/triton" and "main" have entirely different histories.
refs/deplo
...
main
35
.gitattributes
vendored
Normal file
35
.gitattributes
vendored
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
*.7z filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.arrow filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.bin filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.ftz filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.gz filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.h5 filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.joblib filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.model filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.npy filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.npz filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.onnx filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.ot filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.parquet filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.pb filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.pickle filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.pkl filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.pt filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.pth filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.rar filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
||||||
|
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.tar filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.tflite filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.tgz filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.wasm filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.xz filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.zip filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.zst filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
||||||
252
1/model.py
252
1/model.py
@ -1,252 +0,0 @@
|
|||||||
"""
|
|
||||||
[Transformer-LLM 백엔드 가이드]
|
|
||||||
|
|
||||||
본 파일은 NVIDIA Triton Server에서 Hugging Face `AutoModelForCausalLM` 기반 모델을 손쉽게 배포하기 위해 제공되는 커스텀 Python 백엔드 템플릿입니다.
|
|
||||||
|
|
||||||
1. 모델 호환성
|
|
||||||
- Hugging Face의 `AutoModelForCausalLM` 클래스와 호환되는 모든 Causal Language Model을 지원합니다.
|
|
||||||
- [확인] 배포할 모델 `config.json`의 `architectures` 항목이 `...ForCausalLM` 형식인지 확인.
|
|
||||||
2. 토크나이저 호환성
|
|
||||||
- `AutoTokenizer`와 호환되는 토크나이저를 지원하며, 모델과 동일한 경로에서 자동으로 로드됩니다.
|
|
||||||
|
|
||||||
3. 커스터마이징 안내
|
|
||||||
- 본 템플릿은 범용적인 사용을 위해 작성되었습니다.
|
|
||||||
- 특정 모델의 동작 방식이나 예외 처리가 필요한 경우, 이 파일(`model.py`)과 설정 파일(`config.pbtxt`)을 직접 수정하여 사용하시기 바랍니다.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import torch
|
|
||||||
import numpy as np
|
|
||||||
import triton_python_backend_utils as pb_utils
|
|
||||||
import uuid
|
|
||||||
from typing import List, Dict, Any, Union, Tuple
|
|
||||||
|
|
||||||
from transformers import (
|
|
||||||
AutoModelForCausalLM,
|
|
||||||
AutoTokenizer,
|
|
||||||
GenerationConfig,
|
|
||||||
BitsAndBytesConfig,
|
|
||||||
)
|
|
||||||
from peft import PeftModel, PeftConfig
|
|
||||||
|
|
||||||
class TritonPythonModel:
|
|
||||||
def initialize(self, args: Dict[str, str]):
|
|
||||||
"""
|
|
||||||
모델 초기화: 설정 로드, 로거 설정, 모델 및 토크나이저 로드
|
|
||||||
"""
|
|
||||||
self.logger = pb_utils.Logger
|
|
||||||
self.model_config = json.loads(args["model_config"])
|
|
||||||
self.model_name = args["model_name"]
|
|
||||||
|
|
||||||
# 설정 파라미터 로드
|
|
||||||
self.base_model_path = self._get_config_param("base_model_path")
|
|
||||||
self.is_adapter_model = self._get_config_param("is_adapter_model", "false").lower() == "true"
|
|
||||||
self.adapter_model_path = self._get_config_param("adapter_model_path")
|
|
||||||
self.quantization = self._get_config_param("quantization")
|
|
||||||
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
||||||
|
|
||||||
# 설정 로그 출력
|
|
||||||
self.logger.log_info(f"================ {self.model_name} Setup ================")
|
|
||||||
self.logger.log_info(f"Base Model: {self.base_model_path}")
|
|
||||||
self.logger.log_info(f"Adapter Mode: {self.is_adapter_model} ({self.adapter_model_path})")
|
|
||||||
self.logger.log_info(f"Quantization: {self.quantization}")
|
|
||||||
self.logger.log_info(f"Device: {self.device}")
|
|
||||||
|
|
||||||
self._load_model_and_tokenizer()
|
|
||||||
self.logger.log_info(f"Model initialized successfully.")
|
|
||||||
|
|
||||||
def _load_model_and_tokenizer(self):
|
|
||||||
"""모델과 토크나이저를 로드하고 설정합니다."""
|
|
||||||
# 1. Quantization 설정
|
|
||||||
bnb_config = self._get_bnb_config()
|
|
||||||
|
|
||||||
# 2. Base Model 로드
|
|
||||||
load_path = self.base_model_path
|
|
||||||
if self.is_adapter_model:
|
|
||||||
peft_config = PeftConfig.from_pretrained(self.adapter_model_path)
|
|
||||||
load_path = peft_config.base_model_name_or_path
|
|
||||||
|
|
||||||
try:
|
|
||||||
self.model = AutoModelForCausalLM.from_pretrained(
|
|
||||||
load_path,
|
|
||||||
torch_dtype=torch.float16,
|
|
||||||
quantization_config=bnb_config,
|
|
||||||
device_map="auto",
|
|
||||||
local_files_only=True,
|
|
||||||
trust_remote_code=True
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
self.logger.log_error(f"Failed to load base model: {e}")
|
|
||||||
raise e
|
|
||||||
|
|
||||||
# 3. Adapter 병합 (필요 시)
|
|
||||||
if self.is_adapter_model:
|
|
||||||
self.model = PeftModel.from_pretrained(self.model, self.adapter_model_path)
|
|
||||||
|
|
||||||
self.model.eval()
|
|
||||||
|
|
||||||
# 4. Tokenizer 로드
|
|
||||||
self.tokenizer = AutoTokenizer.from_pretrained(load_path, trust_remote_code=True)
|
|
||||||
|
|
||||||
if self.tokenizer.pad_token is None:
|
|
||||||
self.tokenizer.pad_token = self.tokenizer.eos_token
|
|
||||||
self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
|
|
||||||
self.logger.log_info("Pad token was None. Set to EOS token.")
|
|
||||||
|
|
||||||
self.supports_chat_template = (
|
|
||||||
hasattr(self.tokenizer, "chat_template") and
|
|
||||||
self.tokenizer.chat_template is not None
|
|
||||||
)
|
|
||||||
|
|
||||||
self.logger.log_info(f"Supports Chat Template: {self.supports_chat_template}")
|
|
||||||
if self.supports_chat_template:
|
|
||||||
self.logger.log_info(f"Chat Template Content:\n{self.tokenizer.chat_template}")
|
|
||||||
|
|
||||||
def _get_bnb_config(self) -> Union[BitsAndBytesConfig, None]:
|
|
||||||
if self.quantization == "int4":
|
|
||||||
return BitsAndBytesConfig(
|
|
||||||
load_in_4bit=True,
|
|
||||||
bnb_4bit_use_double_quant=True,
|
|
||||||
bnb_4bit_quant_type="nf4",
|
|
||||||
bnb_4bit_compute_dtype=torch.float16
|
|
||||||
)
|
|
||||||
elif self.quantization == "int8":
|
|
||||||
return BitsAndBytesConfig(
|
|
||||||
load_in_8bit=True,
|
|
||||||
llm_int8_threshold=6.0,
|
|
||||||
llm_int8_has_fp16_weight=True
|
|
||||||
)
|
|
||||||
return None
|
|
||||||
|
|
||||||
def execute(self, requests):
|
|
||||||
"""Triton Inference Request 처리 메인 루프"""
|
|
||||||
responses = []
|
|
||||||
|
|
||||||
for request in requests:
|
|
||||||
# [ID 생성 로직] - 로그 추적용으로 유지 (Response에는 포함 X)
|
|
||||||
request_id = request.request_id()
|
|
||||||
if not request_id:
|
|
||||||
request_id = str(uuid.uuid4())
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 1. 입력 데이터 파싱
|
|
||||||
input_data, is_chat = self._parse_input(request)
|
|
||||||
|
|
||||||
# [LOGGING] Request ID 포함하여 로그 출력
|
|
||||||
log_input_str = json.dumps(input_data, ensure_ascii=False) if isinstance(input_data, (list, dict)) else str(input_data)
|
|
||||||
self.logger.log_info(f"\n[RID: {request_id}] >>> [{'CHAT' if is_chat else 'TEXT'}][Input]: {log_input_str}")
|
|
||||||
|
|
||||||
# 2. Generation Config 생성
|
|
||||||
gen_config = self._create_generation_config(request)
|
|
||||||
|
|
||||||
# 3. 토크나이징
|
|
||||||
inputs = self._tokenize(input_data, is_chat)
|
|
||||||
|
|
||||||
# 4. 모델 추론 (Generate)
|
|
||||||
output_text = self._generate(inputs, gen_config)
|
|
||||||
|
|
||||||
# [LOGGING] Request ID 포함하여 결과 출력
|
|
||||||
self.logger.log_info(f"\n[RID: {request_id}] <<< [Output]: {output_text}")
|
|
||||||
|
|
||||||
# 5. 응답 생성
|
|
||||||
responses.append(self._create_response(output_text, request_id))
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
self.logger.log_error(f"[RID: {request_id}] Error during execution: {e}")
|
|
||||||
err_tensor = pb_utils.Tensor("text_output", np.array([str(e).encode('utf-8')], dtype=np.bytes_))
|
|
||||||
responses.append(pb_utils.InferenceResponse(output_tensors=[err_tensor]))
|
|
||||||
|
|
||||||
return responses
|
|
||||||
|
|
||||||
def _parse_input(self, request) -> Tuple[Union[str, List[Dict]], bool]:
|
|
||||||
input_text = self._get_input_scalar(request, "text_input")
|
|
||||||
try:
|
|
||||||
conversation = json.loads(input_text)
|
|
||||||
if isinstance(conversation, list):
|
|
||||||
return conversation, True
|
|
||||||
except (json.JSONDecodeError, TypeError):
|
|
||||||
pass
|
|
||||||
return input_text, False
|
|
||||||
|
|
||||||
def _tokenize(self, input_data, is_chat: bool):
|
|
||||||
if self.supports_chat_template and is_chat:
|
|
||||||
return self.tokenizer.apply_chat_template(
|
|
||||||
input_data,
|
|
||||||
tokenize=True,
|
|
||||||
add_generation_prompt=True,
|
|
||||||
return_tensors="pt",
|
|
||||||
return_dict=True
|
|
||||||
).to(self.device)
|
|
||||||
else:
|
|
||||||
if is_chat:
|
|
||||||
input_data = str(input_data)
|
|
||||||
return self.tokenizer(input_data, return_tensors="pt").to(self.device)
|
|
||||||
|
|
||||||
def _generate(self, inputs, gen_config: GenerationConfig) -> str:
|
|
||||||
input_ids = inputs["input_ids"]
|
|
||||||
input_len = input_ids.shape[-1]
|
|
||||||
|
|
||||||
with torch.no_grad():
|
|
||||||
outputs = self.model.generate(
|
|
||||||
**inputs,
|
|
||||||
generation_config=gen_config,
|
|
||||||
pad_token_id=self.tokenizer.pad_token_id,
|
|
||||||
eos_token_id=self.tokenizer.eos_token_id
|
|
||||||
)
|
|
||||||
|
|
||||||
generated_tokens = outputs[0][input_len:]
|
|
||||||
decoded_output = self.tokenizer.decode(generated_tokens, skip_special_tokens=True)
|
|
||||||
return decoded_output.strip()
|
|
||||||
|
|
||||||
def _create_generation_config(self, request) -> GenerationConfig:
|
|
||||||
def get_param(name, default=None, cast_type=None):
|
|
||||||
val = self._get_input_scalar(request, name, default)
|
|
||||||
if val is not None and cast_type:
|
|
||||||
return cast_type(val)
|
|
||||||
return val
|
|
||||||
|
|
||||||
return GenerationConfig(
|
|
||||||
max_length=get_param("max_length", 1024, int),
|
|
||||||
max_new_tokens=get_param("max_new_tokens", 256, int),
|
|
||||||
temperature=get_param("temperature", 1.0, float),
|
|
||||||
do_sample=get_param("do_sample", False, bool),
|
|
||||||
top_k=get_param("top_k", 50, int),
|
|
||||||
top_p=get_param("top_p", 1.0, float),
|
|
||||||
repetition_penalty=get_param("repetition_penalty", 1.0, float),
|
|
||||||
)
|
|
||||||
|
|
||||||
def _create_response(self, output_text: str, request_id: str):
|
|
||||||
"""생성된 텍스트를 Triton Response 객체로 변환"""
|
|
||||||
output_tensor = pb_utils.Tensor(
|
|
||||||
"text_output",
|
|
||||||
np.array([output_text.encode('utf-8')], dtype=np.bytes_)
|
|
||||||
)
|
|
||||||
return pb_utils.InferenceResponse(output_tensors=[output_tensor])
|
|
||||||
|
|
||||||
def _get_config_param(self, key: str, default: str = None) -> str:
|
|
||||||
params = self.model_config.get('parameters', {})
|
|
||||||
if key in params:
|
|
||||||
return params[key].get('string_value', default)
|
|
||||||
return default
|
|
||||||
|
|
||||||
def _get_input_scalar(self, request, name: str, default=None):
|
|
||||||
tensor = pb_utils.get_input_tensor_by_name(request, name)
|
|
||||||
if tensor is None:
|
|
||||||
return default
|
|
||||||
return self._np_decoder(tensor.as_numpy()[0])
|
|
||||||
|
|
||||||
def _np_decoder(self, obj):
|
|
||||||
if isinstance(obj, bytes):
|
|
||||||
return obj.decode('utf-8')
|
|
||||||
if np.issubdtype(obj, np.integer):
|
|
||||||
return int(obj)
|
|
||||||
if np.issubdtype(obj, np.floating):
|
|
||||||
return round(float(obj), 3)
|
|
||||||
if isinstance(obj, np.bool_):
|
|
||||||
return bool(obj)
|
|
||||||
|
|
||||||
def finalize(self):
|
|
||||||
self.logger.log_info(f"Finalizing model {self.model_name}")
|
|
||||||
self.model = None
|
|
||||||
self.tokenizer = None
|
|
||||||
torch.cuda.empty_cache()
|
|
||||||
58
LICENSE.md
Normal file
58
LICENSE.md
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
STABILITY AI COMMUNITY LICENSE AGREEMENT
|
||||||
|
|
||||||
|
Last Updated: July 5, 2024
|
||||||
|
|
||||||
|
1. INTRODUCTION
|
||||||
|
|
||||||
|
This Agreement applies to any individual person or entity (“You”, “Your” or “Licensee”) that uses or distributes any portion or element of the Stability AI Materials or Derivative Works thereof for any Research & Non-Commercial or Commercial purpose. Capitalized terms not otherwise defined herein are defined in Section V below.
|
||||||
|
|
||||||
|
This Agreement is intended to allow research, non-commercial, and limited commercial uses of the Models free of charge. In order to ensure that certain limited commercial uses of the Models continue to be allowed, this Agreement preserves free access to the Models for people or organizations generating annual revenue of less than US $1,000,000 (or local currency equivalent).
|
||||||
|
|
||||||
|
By clicking “I Accept” or by using or distributing or using any portion or element of the Stability Materials or Derivative Works, You agree that You have read, understood and are bound by the terms of this Agreement. If You are acting on behalf of a company, organization or other entity, then “You” includes you and that entity, and You agree that You: (i) are an authorized representative of such entity with the authority to bind such entity to this Agreement, and (ii) You agree to the terms of this Agreement on that entity’s behalf.
|
||||||
|
|
||||||
|
2. RESEARCH & NON-COMMERCIAL USE LICENSE
|
||||||
|
|
||||||
|
Subject to the terms of this Agreement, Stability AI grants You a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable and royalty-free limited license under Stability AI’s intellectual property or other rights owned by Stability AI embodied in the Stability AI Materials to use, reproduce, distribute, and create Derivative Works of, and make modifications to, the Stability AI Materials for any Research or Non-Commercial Purpose. “Research Purpose” means academic or scientific advancement, and in each case, is not primarily intended for commercial advantage or monetary compensation to You or others. “Non-Commercial Purpose” means any purpose other than a Research Purpose that is not primarily intended for commercial advantage or monetary compensation to You or others, such as personal use (i.e., hobbyist) or evaluation and testing.
|
||||||
|
|
||||||
|
3. COMMERCIAL USE LICENSE
|
||||||
|
|
||||||
|
Subject to the terms of this Agreement (including the remainder of this Section III), Stability AI grants You a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable and royalty-free limited license under Stability AI’s intellectual property or other rights owned by Stability AI embodied in the Stability AI Materials to use, reproduce, distribute, and create Derivative Works of, and make modifications to, the Stability AI Materials for any Commercial Purpose. “Commercial Purpose” means any purpose other than a Research Purpose or Non-Commercial Purpose that is primarily intended for commercial advantage or monetary compensation to You or others, including but not limited to, (i) creating, modifying, or distributing Your product or service, including via a hosted service or application programming interface, and (ii) for Your business’s or organization’s internal operations.
|
||||||
|
If You are using or distributing the Stability AI Materials for a Commercial Purpose, You must register with Stability AI at (https://stability.ai/community-license). If at any time You or Your Affiliate(s), either individually or in aggregate, generate more than USD $1,000,000 in annual revenue (or the equivalent thereof in Your local currency), regardless of whether that revenue is generated directly or indirectly from the Stability AI Materials or Derivative Works, any licenses granted to You under this Agreement shall terminate as of such date. You must request a license from Stability AI at (https://stability.ai/enterprise) , which Stability AI may grant to You in its sole discretion. If you receive Stability AI Materials, or any Derivative Works thereof, from a Licensee as part of an integrated end user product, then Section III of this Agreement will not apply to you.
|
||||||
|
|
||||||
|
4. GENERAL TERMS
|
||||||
|
|
||||||
|
Your Research, Non-Commercial, and Commercial License(s) under this Agreement are subject to the following terms.
|
||||||
|
a. Distribution & Attribution. If You distribute or make available the Stability AI Materials or a Derivative Work to a third party, or a product or service that uses any portion of them, You shall: (i) provide a copy of this Agreement to that third party, (ii) retain the following attribution notice within a "Notice" text file distributed as a part of such copies: "This Stability AI Model is licensed under the Stability AI Community License, Copyright © Stability AI Ltd. All Rights Reserved”, and (iii) prominently display “Powered by Stability AI” on a related website, user interface, blogpost, about page, or product documentation. If You create a Derivative Work, You may add your own attribution notice(s) to the “Notice” text file included with that Derivative Work, provided that You clearly indicate which attributions apply to the Stability AI Materials and state in the “Notice” text file that You changed the Stability AI Materials and how it was modified.
|
||||||
|
b. Use Restrictions. Your use of the Stability AI Materials and Derivative Works, including any output or results of the Stability AI Materials or Derivative Works, must comply with applicable laws and regulations (including Trade Control Laws and equivalent regulations) and adhere to the Documentation and Stability AI’s AUP, which is hereby incorporated by reference. Furthermore, You will not use the Stability AI Materials or Derivative Works, or any output or results of the Stability AI Materials or Derivative Works, to create or improve any foundational generative AI model (excluding the Models or Derivative Works).
|
||||||
|
c. Intellectual Property.
|
||||||
|
(i) Trademark License. No trademark licenses are granted under this Agreement, and in connection with the Stability AI Materials or Derivative Works, You may not use any name or mark owned by or associated with Stability AI or any of its Affiliates, except as required under Section IV(a) herein.
|
||||||
|
(ii) Ownership of Derivative Works. As between You and Stability AI, You are the owner of Derivative Works You create, subject to Stability AI’s ownership of the Stability AI Materials and any Derivative Works made by or for Stability AI.
|
||||||
|
(iii) Ownership of Outputs. As between You and Stability AI, You own any outputs generated from the Models or Derivative Works to the extent permitted by applicable law.
|
||||||
|
(iv) Disputes. If You or Your Affiliate(s) institute litigation or other proceedings against Stability AI (including a cross-claim or counterclaim in a lawsuit) alleging that the Stability AI Materials, Derivative Works or associated outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by You, then any licenses granted to You under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Stability AI from and against any claim by any third party arising out of or related to Your use or distribution of the Stability AI Materials or Derivative Works in violation of this Agreement.
|
||||||
|
(v) Feedback. From time to time, You may provide Stability AI with verbal and/or written suggestions, comments or other feedback related to Stability AI’s existing or prospective technology, products or services (collectively, “Feedback”). You are not obligated to provide Stability AI with Feedback, but to the extent that You do, You hereby grant Stability AI a perpetual, irrevocable, royalty-free, fully-paid, sub-licensable, transferable, non-exclusive, worldwide right and license to exploit the Feedback in any manner without restriction. Your Feedback is provided “AS IS” and You make no warranties whatsoever about any Feedback.
|
||||||
|
d. Disclaimer Of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE STABILITY AI MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OR LAWFULNESS OF USING OR REDISTRIBUTING THE STABILITY AI MATERIALS, DERIVATIVE WORKS OR ANY OUTPUT OR RESULTS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE STABILITY AI MATERIALS, DERIVATIVE WORKS AND ANY OUTPUT AND RESULTS.
|
||||||
|
e. Limitation Of Liability. IN NO EVENT WILL STABILITY AI OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF STABILITY AI OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
|
||||||
|
f. Term And Termination. The term of this Agreement will commence upon Your acceptance of this Agreement or access to the Stability AI Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Stability AI may terminate this Agreement if You are in breach of any term or condition of this Agreement. Upon termination of this Agreement, You shall delete and cease use of any Stability AI Materials or Derivative Works. Section IV(d), (e), and (g) shall survive the termination of this Agreement.
|
||||||
|
g. Governing Law. This Agreement will be governed by and constructed in accordance with the laws of the United States and the State of California without regard to choice of law principles, and the UN Convention on Contracts for International Sale of Goods does not apply to this Agreement.
|
||||||
|
|
||||||
|
5. DEFINITIONS
|
||||||
|
|
||||||
|
“Affiliate(s)” means any entity that directly or indirectly controls, is controlled by, or is under common control with the subject entity; for purposes of this definition, “control” means direct or indirect ownership or control of more than 50% of the voting interests of the subject entity.
|
||||||
|
|
||||||
|
"Agreement" means this Stability AI Community License Agreement.
|
||||||
|
|
||||||
|
“AUP” means the Stability AI Acceptable Use Policy available at (https://stability.ai/use-policy), as may be updated from time to time.
|
||||||
|
|
||||||
|
"Derivative Work(s)” means (a) any derivative work of the Stability AI Materials as recognized by U.S. copyright laws and (b) any modifications to a Model, and any other model created which is based on or derived from the Model or the Model’s output, including “fine tune” and “low-rank adaptation” models derived from a Model or a Model’s output, but do not include the output of any Model.
|
||||||
|
|
||||||
|
“Documentation” means any specifications, manuals, documentation, and other written information provided by Stability AI related to the Software or Models.
|
||||||
|
|
||||||
|
“Model(s)" means, collectively, Stability AI’s proprietary models and algorithms, including machine-learning models, trained model weights and other elements of the foregoing listed on Stability’s Core Models Webpage available at (https://stability.ai/core-models), as may be updated from time to time.
|
||||||
|
|
||||||
|
"Stability AI" or "we" means Stability AI Ltd. and its Affiliates.
|
||||||
|
|
||||||
|
"Software" means Stability AI’s proprietary software made available under this Agreement now or in the future.
|
||||||
|
|
||||||
|
“Stability AI Materials” means, collectively, Stability’s proprietary Models, Software and Documentation (and any portion or combination thereof) made available under this Agreement.
|
||||||
|
|
||||||
|
“Trade Control Laws” means any applicable U.S. and non-U.S. export control and trade sanctions laws and regulations.
|
||||||
143
README.md
Normal file
143
README.md
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
---
|
||||||
|
license: other
|
||||||
|
datasets:
|
||||||
|
- tiiuae/falcon-refinedweb
|
||||||
|
- togethercomputer/RedPajama-Data-1T
|
||||||
|
- uonlp/CulturaX
|
||||||
|
- CarperAI/pilev2-dev
|
||||||
|
- bigcode/starcoderdata
|
||||||
|
- DataProvenanceInitiative/Commercially-Verified-Licenses
|
||||||
|
language:
|
||||||
|
- en
|
||||||
|
- de
|
||||||
|
- es
|
||||||
|
- fr
|
||||||
|
- it
|
||||||
|
- nl
|
||||||
|
- pt
|
||||||
|
- kr
|
||||||
|
tags:
|
||||||
|
- causal-lm
|
||||||
|
---
|
||||||
|
|
||||||
|
# `Stable LM 2 1.6B`
|
||||||
|
|
||||||
|
Please note: For commercial use, please refer to https://stability.ai/license
|
||||||
|
|
||||||
|
## Model Description
|
||||||
|
|
||||||
|
`Stable LM 2 1.6B` is a 1.6 billion parameter decoder-only language model pre-trained on 2 trillion tokens of diverse multilingual and code datasets for two epochs.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
Get started generating text with `Stable LM 2 1.6B` by using the following code snippet:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||||
|
tokenizer = AutoTokenizer.from_pretrained("stabilityai/stablelm-2-1_6b")
|
||||||
|
model = AutoModelForCausalLM.from_pretrained(
|
||||||
|
"stabilityai/stablelm-2-1_6b",
|
||||||
|
torch_dtype="auto",
|
||||||
|
)
|
||||||
|
model.cuda()
|
||||||
|
inputs = tokenizer("The weather is always wonderful", return_tensors="pt").to(model.device)
|
||||||
|
tokens = model.generate(
|
||||||
|
**inputs,
|
||||||
|
max_new_tokens=64,
|
||||||
|
temperature=0.70,
|
||||||
|
top_p=0.95,
|
||||||
|
do_sample=True,
|
||||||
|
)
|
||||||
|
print(tokenizer.decode(tokens[0], skip_special_tokens=True))
|
||||||
|
```
|
||||||
|
|
||||||
|
### Run with Flash Attention 2 ⚡️
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary> Click to expand </summary>
|
||||||
|
|
||||||
|
```python
|
||||||
|
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||||
|
tokenizer = AutoTokenizer.from_pretrained("stabilityai/stablelm-2-1_6b")
|
||||||
|
model = AutoModelForCausalLM.from_pretrained(
|
||||||
|
"stabilityai/stablelm-2-1_6b",
|
||||||
|
torch_dtype="auto",
|
||||||
|
attn_implementation="flash_attention_2",
|
||||||
|
)
|
||||||
|
model.cuda()
|
||||||
|
inputs = tokenizer("The weather is always wonderful", return_tensors="pt").to(model.device)
|
||||||
|
tokens = model.generate(
|
||||||
|
**inputs,
|
||||||
|
max_new_tokens=64,
|
||||||
|
temperature=0.70,
|
||||||
|
top_p=0.95,
|
||||||
|
do_sample=True,
|
||||||
|
)
|
||||||
|
print(tokenizer.decode(tokens[0], skip_special_tokens=True))
|
||||||
|
```
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
|
||||||
|
## Model Details
|
||||||
|
|
||||||
|
* **Developed by**: [Stability AI](https://stability.ai/)
|
||||||
|
* **Model type**: `Stable LM 2 1.6B` models are auto-regressive language models based on the transformer decoder architecture.
|
||||||
|
* **Language(s)**: English
|
||||||
|
* **Paper**: [Stable LM 2 1.6B Technical Report](https://drive.google.com/file/d/1JYJHszhS8EFChTbNAf8xmqhKjogWRrQF/view?usp=sharing)
|
||||||
|
* **Library**: [GPT-NeoX](https://github.com/EleutherAI/gpt-neox)
|
||||||
|
* **License**: [Stability AI Community License](https://huggingface.co/stabilityai/stablelm-2-1_6b/blob/main/LICENSE.md).
|
||||||
|
* **Commercial License**: to use this model commercially, please refer to https://stability.ai/license
|
||||||
|
* **Contact**: For questions and comments about the model, please email `lm@stability.ai`
|
||||||
|
|
||||||
|
### Model Architecture
|
||||||
|
|
||||||
|
The model is a decoder-only transformer similar to the LLaMA ([Touvron et al., 2023](https://arxiv.org/abs/2307.09288)) architecture with the following modifications:
|
||||||
|
|
||||||
|
| Parameters | Hidden Size | Layers | Heads | Sequence Length |
|
||||||
|
|----------------|-------------|--------|-------|-----------------|
|
||||||
|
| 1,644,417,024 | 2048 | 24 | 32 | 4096 |
|
||||||
|
|
||||||
|
* **Position Embeddings**: Rotary Position Embeddings ([Su et al., 2021](https://arxiv.org/abs/2104.09864)) applied to the first 25% of head embedding dimensions for improved throughput following [Black et al. (2022)](https://arxiv.org/pdf/2204.06745.pdf).
|
||||||
|
* **Normalization**: LayerNorm ([Ba et al., 2016](https://arxiv.org/abs/1607.06450)) with learned bias terms as opposed to RMSNorm ([Zhang & Sennrich, 2019](https://arxiv.org/abs/1910.07467)).
|
||||||
|
* **Biases**: We remove all bias terms from the feed-forward networks and multi-head self-attention layers, except for the biases of the query, key, and value projections ([Bai et al., 2023](https://arxiv.org/abs/2309.16609)).
|
||||||
|
* **Tokenizer**: We use Arcade100k, a BPE tokenizer extended from OpenAI's [`tiktoken.cl100k_base`](https://github.com/openai/tiktoken). We split digits into individual tokens following findings by [Liu & Low (2023)](https://arxiv.org/abs/2305.14201).
|
||||||
|
|
||||||
|
## Training
|
||||||
|
|
||||||
|
### Training Dataset
|
||||||
|
|
||||||
|
The dataset is comprised of a filtered mixture of open-source large-scale datasets available on the [HuggingFace Hub](https://huggingface.co/datasets): Falcon RefinedWeb extract ([Penedo et al., 2023](https://huggingface.co/datasets/tiiuae/falcon-refinedweb)), RedPajama-Data ([Together Computer., 2023](https://github.com/togethercomputer/RedPajama-Data)) and The Pile ([Gao et al., 2020](https://arxiv.org/abs/2101.00027)) both without the *Books3* subset, and StarCoder ([Li et al., 2023](https://arxiv.org/abs/2305.06161)). We further supplement our training with multi-lingual data from CulturaX ([Nguyen et al., 2023](https://arxiv.org/abs/2309.09400)) and, in particular, from its OSCAR corpora, as well as restructured data in the style of [Yuan & Liu (2022)](https://arxiv.org/abs/2206.11147).
|
||||||
|
|
||||||
|
* Given the large amount of web data, we recommend fine-tuning the base `Stable LM 2 1.6B` for your downstream tasks.
|
||||||
|
|
||||||
|
### Training Procedure
|
||||||
|
|
||||||
|
The model is pre-trained on the aforementioned datasets in `bfloat16` precision, optimized with AdamW, and trained using the Arcade100k tokenizer with a vocabulary size of 100,352. We outline the complete hyperparameters choices in the project's [GitHub repository - config*](https://github.com/Stability-AI/StableLM/blob/main/configs/stablelm-2-1_6b.yml). The final checkpoint of pre-training, before cooldown, is provided in the `global_step420000` [branch](https://huggingface.co/stabilityai/stablelm-2-1_6b/blob/global_step420000/README.md).
|
||||||
|
|
||||||
|
### Training Infrastructure
|
||||||
|
|
||||||
|
* **Hardware**: `Stable LM 2 1.6B` was trained on the Stability AI cluster across 512 NVIDIA A100 40GB GPUs (AWS P4d instances).
|
||||||
|
|
||||||
|
* **Software**: We use a fork of `gpt-neox` ([EleutherAI, 2021](https://github.com/EleutherAI/gpt-neox)), train under 2D parallelism (Data and Tensor Parallel) with ZeRO-1 ([Rajbhandari et al., 2019](https://arxiv.org/abs/1910.02054v3)), and rely on flash-attention as well as SwiGLU and Rotary Embedding kernels from FlashAttention-2 ([Dao et al., 2023](https://tridao.me/publications/flash2/flash2.pdf))
|
||||||
|
|
||||||
|
## Use and Limitations
|
||||||
|
|
||||||
|
### Intended Use
|
||||||
|
|
||||||
|
The model is intended to be used as a foundational base model for application-specific fine-tuning. Developers must evaluate and fine-tune the model for safe performance in downstream applications. For commercial use, please refer to https://stability.ai/membership.
|
||||||
|
|
||||||
|
### Limitations and Bias
|
||||||
|
|
||||||
|
As a base model, this model may exhibit unreliable, unsafe, or other undesirable behaviors that must be corrected through evaluation and fine-tuning prior to deployment. The pre-training dataset may have contained offensive or inappropriate content, even after applying data cleansing filters, which can be reflected in the model-generated text. We recommend that users exercise caution when using these models in production systems. Do not use the models if they are unsuitable for your application, or for any applications that may cause deliberate or unintentional harm to others.
|
||||||
|
|
||||||
|
## How to Cite
|
||||||
|
|
||||||
|
```bibtex
|
||||||
|
@article{bellagente2024stable,
|
||||||
|
title={Stable LM 2 1.6 B Technical Report},
|
||||||
|
author={Bellagente, Marco and Tow, Jonathan and Mahan, Dakota and Phung, Duy and Zhuravinskyi, Maksym and Adithyan, Reshinth and Baicoianu, James and Brooks, Ben and Cooper, Nathan and Datta, Ashish and others},
|
||||||
|
journal={arXiv preprint arXiv:2402.17834},
|
||||||
|
year={2024}
|
||||||
|
}
|
||||||
|
```
|
||||||
25
config.json
Normal file
25
config.json
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"architectures": [
|
||||||
|
"StableLmForCausalLM"
|
||||||
|
],
|
||||||
|
"bos_token_id": 100257,
|
||||||
|
"eos_token_id": 100257,
|
||||||
|
"hidden_act": "silu",
|
||||||
|
"hidden_size": 2048,
|
||||||
|
"initializer_range": 0.02,
|
||||||
|
"intermediate_size": 5632,
|
||||||
|
"max_position_embeddings": 4096,
|
||||||
|
"model_type": "stablelm",
|
||||||
|
"layer_norm_eps": 1e-05,
|
||||||
|
"num_attention_heads": 32,
|
||||||
|
"num_hidden_layers": 24,
|
||||||
|
"num_key_value_heads": 32,
|
||||||
|
"partial_rotary_factor": 0.25,
|
||||||
|
"rope_theta": 10000,
|
||||||
|
"tie_word_embeddings": false,
|
||||||
|
"torch_dtype": "float16",
|
||||||
|
"transformers_version": "4.38.0",
|
||||||
|
"use_cache": true,
|
||||||
|
"use_qkv_bias": true,
|
||||||
|
"vocab_size": 100352
|
||||||
|
}
|
||||||
132
config.pbtxt
132
config.pbtxt
@ -1,132 +0,0 @@
|
|||||||
# Triton Backend for TransformerLLM.
|
|
||||||
backend: "python"
|
|
||||||
max_batch_size: 0
|
|
||||||
|
|
||||||
# Triton should expect as input a single string
|
|
||||||
# input of variable length named 'text_input'
|
|
||||||
input [
|
|
||||||
|
|
||||||
{
|
|
||||||
name: "text_input"
|
|
||||||
data_type: TYPE_STRING
|
|
||||||
dims: [ 1 ]
|
|
||||||
|
|
||||||
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "max_length"
|
|
||||||
data_type: TYPE_INT32
|
|
||||||
dims: [ 1 ]
|
|
||||||
|
|
||||||
optional: true
|
|
||||||
|
|
||||||
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "max_new_tokens"
|
|
||||||
data_type: TYPE_INT32
|
|
||||||
dims: [ 1 ]
|
|
||||||
|
|
||||||
optional: true
|
|
||||||
|
|
||||||
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "do_sample"
|
|
||||||
data_type: TYPE_BOOL
|
|
||||||
dims: [ 1 ]
|
|
||||||
|
|
||||||
optional: true
|
|
||||||
|
|
||||||
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "top_k"
|
|
||||||
data_type: TYPE_INT32
|
|
||||||
dims: [ 1 ]
|
|
||||||
|
|
||||||
optional: true
|
|
||||||
|
|
||||||
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "top_p"
|
|
||||||
data_type: TYPE_FP32
|
|
||||||
dims: [ 1 ]
|
|
||||||
|
|
||||||
optional: true
|
|
||||||
|
|
||||||
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "temperature"
|
|
||||||
data_type: TYPE_FP32
|
|
||||||
dims: [ 1 ]
|
|
||||||
|
|
||||||
optional: true
|
|
||||||
|
|
||||||
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "repetition_penalty"
|
|
||||||
data_type: TYPE_FP32
|
|
||||||
dims: [ 1 ]
|
|
||||||
|
|
||||||
optional: true
|
|
||||||
|
|
||||||
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "stream"
|
|
||||||
data_type: TYPE_BOOL
|
|
||||||
dims: [ 1 ]
|
|
||||||
|
|
||||||
optional: true
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
# Triton should expect to respond with a single string
|
|
||||||
# output of variable length named 'text_output'
|
|
||||||
output [
|
|
||||||
|
|
||||||
{
|
|
||||||
name: "text_output"
|
|
||||||
data_type: TYPE_STRING
|
|
||||||
dims: [ 1 ]
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
]
|
|
||||||
|
|
||||||
parameters: [
|
|
||||||
{
|
|
||||||
key: "model_path",
|
|
||||||
value: {string_value: "/cheetah/input/model/groupuser/stablelm-2-1_6b"}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "is_adapter_model",
|
|
||||||
value: {string_value: "false"}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "adapter_model_path",
|
|
||||||
value: {string_value: ""}
|
|
||||||
},
|
|
||||||
|
|
||||||
{
|
|
||||||
key: "quantization",
|
|
||||||
value: {string_value: "none"}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
instance_group [
|
|
||||||
{
|
|
||||||
kind: KIND_AUTO,
|
|
||||||
count: 1
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
183
configuration_stablelm.py
Normal file
183
configuration_stablelm.py
Normal file
@ -0,0 +1,183 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# Copyright 2024 Stability AI and The HuggingFace Inc. team. All rights reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
""" StableLM model configuration """
|
||||||
|
|
||||||
|
from transformers.configuration_utils import PretrainedConfig
|
||||||
|
from transformers.utils import logging
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.get_logger(__name__)
|
||||||
|
|
||||||
|
STABLELM_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
||||||
|
"stabilityai/stablelm-3b-4e1t": "https://huggingface.co/stabilityai/stablelm-3b-4e1t/resolve/main/config.json",
|
||||||
|
# See all StableLM models at https://huggingface.co/models?filter=stablelm
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class StableLmConfig(PretrainedConfig):
|
||||||
|
r"""
|
||||||
|
This is the configuration class to store the configuration of a [`~StableLmModel`].
|
||||||
|
It is used to instantiate an StableLM model according to the specified arguments, defining the model
|
||||||
|
architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
|
||||||
|
the StableLM [stabilityai/stablelm-3b-4e1t](https://huggingface.co/stabilityai/stablelm-3b-4e1t) architecture.
|
||||||
|
|
||||||
|
Configuration objects inherit from [`PretrainedConfig`] and can be used
|
||||||
|
to control the model outputs. Read the documentation from [`PretrainedConfig`]
|
||||||
|
for more information.
|
||||||
|
|
||||||
|
|
||||||
|
Args:
|
||||||
|
vocab_size (`int`, *optional*, defaults to 50304):
|
||||||
|
Vocabulary size of the StableLM model. Defines the number of different tokens that
|
||||||
|
can be represented by the `inputs_ids` passed when calling [`StableLmModel`].
|
||||||
|
intermediate_size (`int`, *optional*, defaults to 6912):
|
||||||
|
Dimension of the MLP representations.
|
||||||
|
hidden_size (`int`, *optional*, defaults to 2560):
|
||||||
|
Number of hidden layers in the Transformer decoder.
|
||||||
|
num_hidden_layers (`int`, *optional*, defaults to 32):
|
||||||
|
Number of hidden layers in the Transformer decoder.
|
||||||
|
num_attention_heads (`int`, *optional*, defaults to 32):
|
||||||
|
Number of attention heads for each attention layer in the Transformer encoder.
|
||||||
|
num_key_value_heads (`int`, *optional*, defaults to 32):
|
||||||
|
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
||||||
|
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
||||||
|
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
||||||
|
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
||||||
|
by meanpooling all the original heads within that group. For more details checkout [this
|
||||||
|
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
||||||
|
`num_attention_heads`.
|
||||||
|
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
||||||
|
The non-linear activation function (function or string).
|
||||||
|
max_position_embeddings (`int`, *optional*, defaults to 4096):
|
||||||
|
The maximum sequence length that this model might ever be used with.
|
||||||
|
Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
|
||||||
|
initializer_range (`float`, *optional*, defaults to 0.02):
|
||||||
|
The standard deviation of the truncated_normal_initializer for initializing
|
||||||
|
all weight matrices.
|
||||||
|
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
||||||
|
The epsilon used by the normalization layers.
|
||||||
|
use_cache (`bool`, *optional*, defaults to `True`):
|
||||||
|
Whether or not the model should return the last key/values attentions
|
||||||
|
(not used by all models). Only relevant if `config.is_decoder=True`.
|
||||||
|
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
||||||
|
Whether the model's input and output word embeddings should be tied.
|
||||||
|
rope_theta (`float`, *optional*, defaults to `10000.0`):
|
||||||
|
The base period of the RoPE embeddings.
|
||||||
|
rope_scaling (`Dict`, *optional*):
|
||||||
|
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
||||||
|
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
||||||
|
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
||||||
|
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
||||||
|
these scaling strategies behave:
|
||||||
|
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This
|
||||||
|
is an experimental feature, subject to breaking API changes in future versions.
|
||||||
|
use_qkv_bias (`bool`, *optional*, defaults to `False`):
|
||||||
|
Whether or not the model should use bias for qkv layers.
|
||||||
|
hidden_dropout (`float`, *optional*, defaults to 0.0):
|
||||||
|
The dropout ratio after applying the MLP to the hidden states.
|
||||||
|
attention_dropout (`float`, *optional*, defaults to 0.0):
|
||||||
|
The dropout ratio for the attention probabilities.
|
||||||
|
partial_rotary_factor (`float`, *optional*, defaults to 0.25):
|
||||||
|
Percentage of the query and keys which will have rotary embedding.
|
||||||
|
bos_token_id (int, *optional*, defaults to 0):
|
||||||
|
The id of the `BOS` token in the vocabulary.
|
||||||
|
eos_token_id (int, *optional*, defaults to 0):
|
||||||
|
The id of the `EOS` token in the vocabulary.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```python
|
||||||
|
>>> from transformers import StableLmModel, StableLmConfig
|
||||||
|
|
||||||
|
>>> # Initializing a StableLM stablelm-3b style configuration
|
||||||
|
>>> configuration = StableLmConfig()
|
||||||
|
```"""
|
||||||
|
|
||||||
|
model_type = "stablelm"
|
||||||
|
keys_to_ignore_at_inference = ["past_key_values"]
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
vocab_size=50304,
|
||||||
|
intermediate_size=6912,
|
||||||
|
hidden_size=2560,
|
||||||
|
num_hidden_layers=32,
|
||||||
|
num_attention_heads=32,
|
||||||
|
num_key_value_heads=32,
|
||||||
|
hidden_act="silu",
|
||||||
|
max_position_embeddings=4096,
|
||||||
|
initializer_range=0.02,
|
||||||
|
layer_norm_eps=1.0e-5,
|
||||||
|
use_cache=True,
|
||||||
|
tie_word_embeddings=False,
|
||||||
|
rope_theta=10_000,
|
||||||
|
rope_scaling=None,
|
||||||
|
use_qkv_bias=False,
|
||||||
|
hidden_dropout=0.0,
|
||||||
|
attention_dropout=0.0,
|
||||||
|
partial_rotary_factor=0.25,
|
||||||
|
bos_token_id=0,
|
||||||
|
eos_token_id=0,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
self.vocab_size = vocab_size
|
||||||
|
self.max_position_embeddings = max_position_embeddings
|
||||||
|
|
||||||
|
self.hidden_size = hidden_size
|
||||||
|
self.intermediate_size = intermediate_size
|
||||||
|
self.num_hidden_layers = num_hidden_layers
|
||||||
|
self.num_attention_heads = num_attention_heads
|
||||||
|
self.num_key_value_heads = num_key_value_heads
|
||||||
|
self.hidden_act = hidden_act
|
||||||
|
|
||||||
|
self.initializer_range = initializer_range
|
||||||
|
self.layer_norm_eps = layer_norm_eps
|
||||||
|
self.use_cache = use_cache
|
||||||
|
self.rope_theta = rope_theta
|
||||||
|
self.rope_scaling = rope_scaling
|
||||||
|
self.use_qkv_bias = use_qkv_bias
|
||||||
|
self.hidden_dropout = hidden_dropout
|
||||||
|
self.attention_dropout = attention_dropout
|
||||||
|
self.partial_rotary_factor = partial_rotary_factor
|
||||||
|
self._rope_scaling_validation()
|
||||||
|
|
||||||
|
super().__init__(
|
||||||
|
bos_token_id=bos_token_id,
|
||||||
|
eos_token_id=eos_token_id,
|
||||||
|
tie_word_embeddings=tie_word_embeddings,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
|
||||||
|
def _rope_scaling_validation(self):
|
||||||
|
"""
|
||||||
|
Validate the `rope_scaling` configuration.
|
||||||
|
"""
|
||||||
|
if self.rope_scaling is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
||||||
|
raise ValueError(
|
||||||
|
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
||||||
|
f"got {self.rope_scaling}"
|
||||||
|
)
|
||||||
|
rope_scaling_type = self.rope_scaling.get("type", None)
|
||||||
|
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
||||||
|
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
||||||
|
raise ValueError(
|
||||||
|
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
||||||
|
)
|
||||||
|
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
||||||
|
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
||||||
6
generation_config.json
Normal file
6
generation_config.json
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"_from_model_config": true,
|
||||||
|
"bos_token_id": 100257,
|
||||||
|
"eos_token_id": 100257,
|
||||||
|
"transformers_version": "4.38.0"
|
||||||
|
}
|
||||||
100001
merges.txt
Normal file
100001
merges.txt
Normal file
File diff suppressed because it is too large
Load Diff
BIN
model.safetensors
(Stored with Git LFS)
Normal file
BIN
model.safetensors
(Stored with Git LFS)
Normal file
Binary file not shown.
1341
modeling_stablelm.py
Normal file
1341
modeling_stablelm.py
Normal file
File diff suppressed because it is too large
Load Diff
40
special_tokens_map.json
Normal file
40
special_tokens_map.json
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"additional_special_tokens": [
|
||||||
|
"<|reg_extra|>",
|
||||||
|
"<|endoftext|>",
|
||||||
|
"<|fim_prefix|>",
|
||||||
|
"<|fim_middle|>",
|
||||||
|
"<|fim_suffix|>",
|
||||||
|
"<|fim_pad|>",
|
||||||
|
"<gh_stars>",
|
||||||
|
"<filename>",
|
||||||
|
"<issue_start>",
|
||||||
|
"<issue_comment>",
|
||||||
|
"<issue_closed>",
|
||||||
|
"<jupyter_start>",
|
||||||
|
"<jupyter_text>",
|
||||||
|
"<jupyter_code>",
|
||||||
|
"<jupyter_output>",
|
||||||
|
"<empty_output>",
|
||||||
|
"<commit_before>",
|
||||||
|
"<commit_msg>",
|
||||||
|
"<commit_after>",
|
||||||
|
"<reponame>",
|
||||||
|
"<|endofprompt|>",
|
||||||
|
"<|im_start|>",
|
||||||
|
"<|im_end|>",
|
||||||
|
"<|pause|>",
|
||||||
|
"<|reg0|>",
|
||||||
|
"<|reg1|>",
|
||||||
|
"<|reg2|>",
|
||||||
|
"<|reg3|>",
|
||||||
|
"<|reg4|>",
|
||||||
|
"<|reg5|>",
|
||||||
|
"<|reg6|>",
|
||||||
|
"<|reg7|>",
|
||||||
|
"<|extra0|>"
|
||||||
|
],
|
||||||
|
"bos_token": "<|endoftext|>",
|
||||||
|
"eos_token": "<|endoftext|>",
|
||||||
|
"unk_token": "<|endoftext|>"
|
||||||
|
}
|
||||||
200632
tokenizer.json
Normal file
200632
tokenizer.json
Normal file
File diff suppressed because it is too large
Load Diff
43
tokenizer_config.json
Normal file
43
tokenizer_config.json
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
{
|
||||||
|
"add_prefix_space": false,
|
||||||
|
"additional_special_tokens": [
|
||||||
|
"<|reg_extra|>",
|
||||||
|
"<|endoftext|>",
|
||||||
|
"<|fim_prefix|>",
|
||||||
|
"<|fim_middle|>",
|
||||||
|
"<|fim_suffix|>",
|
||||||
|
"<|fim_pad|>",
|
||||||
|
"<gh_stars>",
|
||||||
|
"<filename>",
|
||||||
|
"<issue_start>",
|
||||||
|
"<issue_comment>",
|
||||||
|
"<issue_closed>",
|
||||||
|
"<jupyter_start>",
|
||||||
|
"<jupyter_text>",
|
||||||
|
"<jupyter_code>",
|
||||||
|
"<jupyter_output>",
|
||||||
|
"<empty_output>",
|
||||||
|
"<commit_before>",
|
||||||
|
"<commit_msg>",
|
||||||
|
"<commit_after>",
|
||||||
|
"<reponame>",
|
||||||
|
"<|endofprompt|>",
|
||||||
|
"<|im_start|>",
|
||||||
|
"<|im_end|>",
|
||||||
|
"<|pause|>",
|
||||||
|
"<|reg0|>",
|
||||||
|
"<|reg1|>",
|
||||||
|
"<|reg2|>",
|
||||||
|
"<|reg3|>",
|
||||||
|
"<|reg4|>",
|
||||||
|
"<|reg5|>",
|
||||||
|
"<|reg6|>",
|
||||||
|
"<|reg7|>",
|
||||||
|
"<|extra0|>"
|
||||||
|
],
|
||||||
|
"bos_token": "<|endoftext|>",
|
||||||
|
"clean_up_tokenization_spaces": true,
|
||||||
|
"eos_token": "<|endoftext|>",
|
||||||
|
"tokenizer_class": "GPT2TokenizerFast",
|
||||||
|
"unk_token": "<|endoftext|>"
|
||||||
|
}
|
||||||
100291
vocab.json
Normal file
100291
vocab.json
Normal file
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user