* Fix pad token * Update llama.py * Typo * ignored labels * Revert "ignored labels" This reverts commit4b25138ac7. * More patching * Update _utils.py * Update _utils.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Feat/all tmp (#1219) * Update save.py Check whether path is in /tmp dir for Kaggle environment * Update save.py Move temporary_location to /tmp in Kaggle * Enhance Kaggle environment support in save and tokenizer utilities --------- Co-authored-by: dendarrion <37800703+dendarrion@users.noreply.github.com> Co-authored-by: Erland366 <erland.pg366@gmail.com> * Bug fixes * Update pyproject.toml * Update _utils.py * Update __init__.py * Update __init__.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Tied weights * Revert "Tied weights" This reverts commit820cd4efef. * Tied weights * Utils * CE Loss patching * Update __init__.py * Update __init__.py * Patching * Update cross_entropy_loss.py * CE Loss * Update _utils.py * Update _utils.py * CE Loss * Update _utils.py * Update _utils.py * Layernorm * Update _utils.py * Update _utils.py * Post patch * Update _utils.py * Update llama.py * Update _utils.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * typing * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * int64 * Update _utils.py * Update cross_entropy_loss.py * constexpr * constexpr * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update _utils.py * Update _utils.py * Update _utils.py * CE * Update cross_entropy_loss.py * Update _utils.py * Update llama.py * Update _utils.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update utils.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * Update rms_layernorm.py * typing * Update rope_embedding.py * types * Disable compiling * Update _utils.py * Update _utils.py * Forward hook * Update _utils.py * Update llama.py * Update _utils.py * Update llama.py * Update llama.py * Update _utils.py * Update pyproject.toml * Update _utils.py * Update llama.py * CE Loss * Update cross_entropy_loss.py * Update _utils.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update cross_entropy_loss.py * Update llama.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Fix: cast logits to float32 in cross_entropy_forward to prevent errors (#1254) * Fix: cast logits to float32 in cross_entropy_forward to prevent errors * Update cross_entropy_loss.py --------- Co-authored-by: Daniel Han <danielhanchen@gmail.com> * Throw error when inferencing longer than max_popsition_embeddings (#1236) * Throw error when inferencing longer than max_popsition_embeddings without rope scaling * Update llama.py --------- Co-authored-by: Daniel Han <danielhanchen@gmail.com> * CLI now handles user input strings for dtype correctly (#1235) Co-authored-by: root <root@ieeres.chu.cam.ac.uk> * Update flex_attention.py * Update _utils.py * Update _utils.py * Update flex_attention.py * Update flex_attention.py * Update loader.py * Update loader.py * Update flex_attention.py * Update flex_attention.py * Update flex_attention.py * Update flex_attention.py * Update _utils.py * Update cross_entropy_loss.py * Update _utils.py * Update tokenizer_utils.py * Update tokenizer_utils.py * Update tokenizer_utils.py * Update tokenizer_utils.py * Update tokenizer_utils.py * triton_cast * Update utils.py * Qwen 2.5 Coder * Fix/export mistral (#1281) * Enhance install_python_non_blocking to handle protobuf installation and process management * Revert "Enhance install_python_non_blocking to handle protobuf installation and process management" This reverts commit a3b796a05841fb8d93c652c845591e12cf81ea93. * Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION to 'python' to address issue #1266 * Revert "Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION to 'python' to address issue #1266" This reverts commit f00fbf5eac7ad4f5d48c70b98d770255d1a9ef58. * Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION to 'python' to address issue #1266 * Update __init__.py --------- Co-authored-by: Daniel Han <danielhanchen@gmail.com> * DOC Update - Update README.md with os.environ in example (#1269) * Update README.md with os.environ in example Added OS Environ in example to avoid device conflicts , for a user at least in jupyter notebook this allows to select GPU in a multi GPU setup. As currently the unsloth init checks all GPU's and takes the first in the order which can be a issue when some GPU's are in use and the list still shows them. So to manually avoid this, this os config is required. Small change but a bit time saver for those who straight away copies the tutorials * Update README.md --------- Co-authored-by: Daniel Han <danielhanchen@gmail.com> * fix/get_chat_template (#1246) * Refactor `get_chat_template` to now support system message instead. It supposed to fix ollama tokenizer chattemplate to * Remove type hinting * Update chat_templates.py --------- Co-authored-by: Daniel Han <danielhanchen@gmail.com> * fix/sft-trainer (#1276) * Add patch for SFTTrainer to maintain backward compatibility with TRL changes * Update trainer.py * Update trainer.py * Refactor trainer patch to maintain backward compatibility with TRL changes * Update trainer.py * Refactor trainer.py to exclude non-convertible trainers from backward compatibility patch --------- Co-authored-by: Daniel Han <danielhanchen@gmail.com> * Update __init__.py * Update trainer.py * Update trainer.py * Update trainer.py * Update tokenizer_utils.py * Update llama.py * Fix #853 * fix/sfttrainer-compatibility (#1293) * Refactor trainer.py to import SFTConfig directly and update UnslothTrainingArguments class inheritance * Update trainer.py * Update trainer.py --------- Co-authored-by: Daniel Han <danielhanchen@gmail.com> * Update rms_layernorm.py * Update rms_layernorm.py * Gemma * Update rms_layernorm.py * Update gemma2.py * Cut Cross Entropy * Update llama.py * Cut Cross Entropy * Update llama.py * Update llama.py * Update llama.py * Update __init__.py * Update __init__.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update mapper.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * patch_fast_lora * vision * Update fast_lora.py * Update _utils.py * Update _utils.py * Vision * Update trainer.py * Update save.py * FastBaseVisionModel * Update loader_utils.py * Update vision.py * Update loader.py * Update vision.py * Update loader.py * Update vision.py * Update _utils.py * tokenizer_name * Update loader.py * Update vision.py * Update save.py * Update save.py * Update vision.py * Update vision.py * Update vision.py * Update vision.py * Update vision.py * Update vision.py * Update _utils.py --------- Co-authored-by: dendarrion <37800703+dendarrion@users.noreply.github.com> Co-authored-by: Erland366 <erland.pg366@gmail.com> Co-authored-by: Edd <68678137+Erland366@users.noreply.github.com> Co-authored-by: Datta Nimmaturi <datta.nimmaturi@nutanix.com> Co-authored-by: Edwin Fennell <edwinfennell1@gmail.com> Co-authored-by: root <root@ieeres.chu.cam.ac.uk> Co-authored-by: Uday Girish Maradana <einsteingirish@gmail.com>
181 lines
7.1 KiB
Python
181 lines
7.1 KiB
Python
# Copyright 2023-present Daniel Han-Chen & the Unsloth 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.
|
|
|
|
import warnings, importlib, sys
|
|
from packaging.version import Version
|
|
import os, re, subprocess, inspect
|
|
import numpy as np
|
|
|
|
# # Define a list of modules to check
|
|
# MODULES_TO_CHECK = ["bitsandbytes"]
|
|
|
|
# # Check if any of the modules in the list have been imported
|
|
# for module in MODULES_TO_CHECK:
|
|
# if module in sys.modules:
|
|
# raise ImportError(f"Unsloth: Please import Unsloth before {module}.")
|
|
# pass
|
|
# pass
|
|
|
|
# Unsloth currently does not work on multi GPU setups - sadly we are a 2 brother team so
|
|
# enabling it will require much more work, so we have to prioritize. Please understand!
|
|
# We do have a beta version, which you can contact us about!
|
|
# Thank you for your understanding and we appreciate it immensely!
|
|
|
|
# Fixes https://github.com/unslothai/unsloth/issues/1266
|
|
os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
|
|
|
|
if "CUDA_VISIBLE_DEVICES" in os.environ:
|
|
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
|
|
devices = os.environ["CUDA_VISIBLE_DEVICES"]
|
|
# Check if there are multiple cuda devices set in env
|
|
if not devices.isdigit():
|
|
first_id = devices.split(",")[0]
|
|
warnings.warn(
|
|
f"Unsloth: 'CUDA_VISIBLE_DEVICES' is currently {devices} \n"\
|
|
"Unsloth currently does not support multi GPU setups - but we are working on it!\n"\
|
|
"Multiple CUDA devices detected but we require a single device.\n"\
|
|
f"We will override CUDA_VISIBLE_DEVICES to first device: {first_id}."
|
|
)
|
|
os.environ["CUDA_VISIBLE_DEVICES"] = str(first_id)
|
|
else:
|
|
# warnings.warn("Unsloth: 'CUDA_VISIBLE_DEVICES' is not set. We shall set it ourselves.")
|
|
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
|
|
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
|
|
pass
|
|
|
|
# Reduce VRAM usage by reducing fragmentation
|
|
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True,roundup_power2_divisions:[64:128,256:64,>:32]"
|
|
|
|
# Hugging Face Hub faster downloads
|
|
if "HF_HUB_ENABLE_HF_TRANSFER" not in os.environ:
|
|
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
|
pass
|
|
|
|
# Log Unsloth is being used
|
|
os.environ["UNSLOTH_IS_PRESENT"] = "1"
|
|
|
|
try:
|
|
import torch
|
|
except ModuleNotFoundError:
|
|
raise ImportError(
|
|
"Unsloth: Pytorch is not installed. Go to https://pytorch.org/.\n"\
|
|
"We have some installation instructions on our Github page."
|
|
)
|
|
except Exception as exception:
|
|
raise exception
|
|
pass
|
|
|
|
# We support Pytorch 2
|
|
# Fixes https://github.com/unslothai/unsloth/issues/38
|
|
torch_version = torch.__version__.split(".")
|
|
major_torch, minor_torch = torch_version[0], torch_version[1]
|
|
major_torch, minor_torch = int(major_torch), int(minor_torch)
|
|
if (major_torch < 2):
|
|
raise ImportError("Unsloth only supports Pytorch 2 for now. Please update your Pytorch to 2.1.\n"\
|
|
"We have some installation instructions on our Github page.")
|
|
elif (major_torch == 2) and (minor_torch < 2):
|
|
# Disable expandable_segments
|
|
del os.environ["PYTORCH_CUDA_ALLOC_CONF"]
|
|
pass
|
|
|
|
# Torch 2.4 has including_emulation
|
|
major_version, minor_version = torch.cuda.get_device_capability()
|
|
SUPPORTS_BFLOAT16 = (major_version >= 8)
|
|
|
|
old_is_bf16_supported = torch.cuda.is_bf16_supported
|
|
if "including_emulation" in str(inspect.signature(old_is_bf16_supported)):
|
|
def is_bf16_supported(including_emulation = False):
|
|
return old_is_bf16_supported(including_emulation)
|
|
torch.cuda.is_bf16_supported = is_bf16_supported
|
|
else:
|
|
def is_bf16_supported(): return SUPPORTS_BFLOAT16
|
|
torch.cuda.is_bf16_supported = is_bf16_supported
|
|
pass
|
|
|
|
# Try loading bitsandbytes and triton
|
|
import bitsandbytes as bnb
|
|
|
|
if "SPACE_AUTHOR_NAME" not in os.environ and "SPACE_REPO_NAME" not in os.environ:
|
|
|
|
import triton
|
|
libcuda_dirs = lambda: None
|
|
if Version(triton.__version__) >= Version("3.0.0"):
|
|
try: from triton.backends.nvidia.driver import libcuda_dirs
|
|
except: pass
|
|
else: from triton.common.build import libcuda_dirs
|
|
|
|
try:
|
|
cdequantize_blockwise_fp32 = bnb.functional.lib.cdequantize_blockwise_fp32
|
|
libcuda_dirs()
|
|
except:
|
|
warnings.warn(
|
|
"Unsloth: Running `ldconfig /usr/lib64-nvidia` to link CUDA."\
|
|
)
|
|
|
|
if os.path.exists("/usr/lib64-nvidia"):
|
|
os.system("ldconfig /usr/lib64-nvidia")
|
|
elif os.path.exists("/usr/local"):
|
|
# Sometimes bitsandbytes cannot be linked properly in Runpod for example
|
|
possible_cudas = subprocess.check_output(["ls", "-al", "/usr/local"]).decode("utf-8").split("\n")
|
|
find_cuda = re.compile(r"[\s](cuda\-[\d\.]{2,})$")
|
|
possible_cudas = [find_cuda.search(x) for x in possible_cudas]
|
|
possible_cudas = [x.group(1) for x in possible_cudas if x is not None]
|
|
|
|
# Try linking cuda folder, or everything in local
|
|
if len(possible_cudas) == 0:
|
|
os.system("ldconfig /usr/local/")
|
|
else:
|
|
find_number = re.compile(r"([\d\.]{2,})")
|
|
latest_cuda = np.argsort([float(find_number.search(x).group(1)) for x in possible_cudas])[::-1][0]
|
|
latest_cuda = possible_cudas[latest_cuda]
|
|
os.system(f"ldconfig /usr/local/{latest_cuda}")
|
|
pass
|
|
|
|
importlib.reload(bnb)
|
|
importlib.reload(triton)
|
|
try:
|
|
libcuda_dirs = lambda: None
|
|
if Version(triton.__version__) >= Version("3.0.0"):
|
|
try: from triton.backends.nvidia.driver import libcuda_dirs
|
|
except: pass
|
|
else: from triton.common.build import libcuda_dirs
|
|
cdequantize_blockwise_fp32 = bnb.functional.lib.cdequantize_blockwise_fp32
|
|
libcuda_dirs()
|
|
except:
|
|
warnings.warn(
|
|
"Unsloth: CUDA is not linked properly.\n"\
|
|
"Try running `python -m bitsandbytes` then `python -m xformers.info`\n"\
|
|
"We tried running `ldconfig /usr/lib64-nvidia` ourselves, but it didn't work.\n"\
|
|
"You need to run in your terminal `sudo ldconfig /usr/lib64-nvidia` yourself, then import Unsloth.\n"\
|
|
"Also try `sudo ldconfig /usr/local/cuda-xx.x` - find the latest cuda version.\n"\
|
|
"Unsloth will still run for now, but maybe it might crash - let's hope it works!"
|
|
)
|
|
pass
|
|
pass
|
|
|
|
# Check for unsloth_zoo
|
|
try:
|
|
import unsloth_zoo
|
|
except:
|
|
raise ImportError("Unsloth: Please install unsloth_zoo via `pip install unsloth-zoo`")
|
|
pass
|
|
|
|
from .models import *
|
|
from .save import *
|
|
from .chat_templates import *
|
|
from .tokenizer_utils import *
|
|
from .trainer import *
|
|
|
|
# Patch TRL trainers for backwards compatibility
|
|
_patch_trl_trainer()
|