repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/registry/_phi.py
unsloth/registry/_phi.py
from unsloth.registry.registry import ModelInfo, ModelMeta, QuantType, _register_models _IS_PHI_4_REGISTERED = False _IS_PHI_4_INSTRUCT_REGISTERED = False class PhiModelInfo(ModelInfo): @classmethod def construct_model_name(cls, base_name, version, size, quant_type, instruct_tag): key = f"{base_name}-{version}" return super().construct_model_name( base_name, version, size, quant_type, instruct_tag, key ) # Phi Model Meta PhiMeta4 = ModelMeta( org = "microsoft", base_name = "phi", instruct_tags = [None], model_version = "4", model_sizes = ["1"], # Assuming only one size model_info_cls = PhiModelInfo, is_multimodal = False, quant_types = [QuantType.NONE, QuantType.BNB, QuantType.UNSLOTH], ) # Phi Instruct Model Meta PhiInstructMeta4 = ModelMeta( org = "microsoft", base_name = "phi", instruct_tags = ["mini-instruct"], model_version = "4", model_sizes = ["1"], # Assuming only one size model_info_cls = PhiModelInfo, is_multimodal = False, quant_types = [QuantType.NONE, QuantType.BNB, QuantType.UNSLOTH, QuantType.GGUF], ) def register_phi_4_models(include_original_model: bool = False): global _IS_PHI_4_REGISTERED if _IS_PHI_4_REGISTERED: return _register_models(PhiMeta4, include_original_model = include_original_model) _IS_PHI_4_REGISTERED = True def register_phi_4_instruct_models(include_original_model: bool = False): global _IS_PHI_4_INSTRUCT_REGISTERED if _IS_PHI_4_INSTRUCT_REGISTERED: return _register_models(PhiInstructMeta4, include_original_model = include_original_model) _IS_PHI_4_INSTRUCT_REGISTERED = True def register_phi_models(include_original_model: bool = False): register_phi_4_models(include_original_model = include_original_model) register_phi_4_instruct_models(include_original_model = include_original_model) if __name__ == "__main__": from unsloth.registry.registry import MODEL_REGISTRY, _check_model_info MODEL_REGISTRY.clear() register_phi_models(include_original_model = True) for model_id, model_info in MODEL_REGISTRY.items(): model_info = _check_model_info(model_id) if model_info is None: print(f"\u2718 {model_id}") else: print(f"\u2713 {model_id}")
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/registry/registry.py
unsloth/registry/registry.py
import warnings from dataclasses import dataclass, field from enum import Enum class QuantType(Enum): BNB = "bnb" UNSLOTH = "unsloth" # dynamic 4-bit quantization GGUF = "GGUF" NONE = "none" BF16 = "bf16" # only for Deepseek V3 # Tags for Hugging Face model paths BNB_QUANTIZED_TAG = "bnb-4bit" UNSLOTH_DYNAMIC_QUANT_TAG = "unsloth" + "-" + BNB_QUANTIZED_TAG GGUF_TAG = "GGUF" BF16_TAG = "bf16" QUANT_TAG_MAP = { QuantType.BNB: BNB_QUANTIZED_TAG, QuantType.UNSLOTH: UNSLOTH_DYNAMIC_QUANT_TAG, QuantType.GGUF: GGUF_TAG, QuantType.NONE: None, QuantType.BF16: BF16_TAG, } # NOTE: models registered with org="unsloth" and QUANT_TYPE.NONE are aliases of QUANT_TYPE.UNSLOTH @dataclass class ModelInfo: org: str base_name: str version: str size: int name: str = None # full model name, constructed from base_name, version, and size unless provided is_multimodal: bool = False instruct_tag: str = None quant_type: QuantType = None description: str = None def __post_init__(self): self.name = self.name or self.construct_model_name( self.base_name, self.version, self.size, self.quant_type, self.instruct_tag, ) @staticmethod def append_instruct_tag(key: str, instruct_tag: str = None): if instruct_tag: key = "-".join([key, instruct_tag]) return key @staticmethod def append_quant_type(key: str, quant_type: QuantType = None): if quant_type != QuantType.NONE: key = "-".join([key, QUANT_TAG_MAP[quant_type]]) return key @classmethod def construct_model_name( cls, base_name, version, size, quant_type, instruct_tag, key = "" ): key = cls.append_instruct_tag(key, instruct_tag) key = cls.append_quant_type(key, quant_type) return key @property def model_path( self, ) -> str: return f"{self.org}/{self.name}" @dataclass class ModelMeta: org: str base_name: str model_version: str model_info_cls: type[ModelInfo] model_sizes: list[str] = field(default_factory = list) instruct_tags: list[str] = field(default_factory = list) quant_types: list[QuantType] | dict[str, list[QuantType]] = field( default_factory = list ) is_multimodal: bool = False MODEL_REGISTRY: dict[str, ModelInfo] = {} def register_model( model_info_cls: ModelInfo, org: str, base_name: str, version: str, size: int, instruct_tag: str = None, quant_type: QuantType = None, is_multimodal: bool = False, name: str = None, ): name = name or model_info_cls.construct_model_name( base_name = base_name, version = version, size = size, quant_type = quant_type, instruct_tag = instruct_tag, ) key = f"{org}/{name}" if key in MODEL_REGISTRY: raise ValueError( f"Model {key} already registered, current keys: {MODEL_REGISTRY.keys()}" ) MODEL_REGISTRY[key] = model_info_cls( org = org, base_name = base_name, version = version, size = size, is_multimodal = is_multimodal, instruct_tag = instruct_tag, quant_type = quant_type, name = name, ) def _check_model_info(model_id: str, properties: list[str] = ["lastModified"]): from huggingface_hub import HfApi from huggingface_hub import ModelInfo as HfModelInfo from huggingface_hub.utils import RepositoryNotFoundError api = HfApi() try: model_info: HfModelInfo = api.model_info(model_id, expand = properties) except Exception as e: if isinstance(e, RepositoryNotFoundError): warnings.warn(f"{model_id} not found on Hugging Face") model_info = None else: raise e return model_info def _register_models(model_meta: ModelMeta, include_original_model: bool = False): org = model_meta.org base_name = model_meta.base_name instruct_tags = model_meta.instruct_tags model_version = model_meta.model_version model_sizes = model_meta.model_sizes is_multimodal = model_meta.is_multimodal quant_types = model_meta.quant_types model_info_cls = model_meta.model_info_cls for size in model_sizes: for instruct_tag in instruct_tags: # Handle quant types per model size if isinstance(quant_types, dict): _quant_types = quant_types[size] else: _quant_types = quant_types for quant_type in _quant_types: # NOTE: models registered with org="unsloth" and QUANT_TYPE.NONE are aliases of QUANT_TYPE.UNSLOTH _org = "unsloth" # unsloth models -- these are all quantized versions of the original model register_model( model_info_cls = model_info_cls, org = _org, base_name = base_name, version = model_version, size = size, instruct_tag = instruct_tag, quant_type = quant_type, is_multimodal = is_multimodal, ) # include original model from releasing organization if include_original_model: register_model( model_info_cls = model_info_cls, org = org, base_name = base_name, version = model_version, size = size, instruct_tag = instruct_tag, quant_type = QuantType.NONE, is_multimodal = is_multimodal, )
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/registry/_mistral.py
unsloth/registry/_mistral.py
import copy from unsloth.registry.registry import ModelInfo, ModelMeta, QuantType, _register_models _IS_MISTRAL_SMALL_REGISTERED = False _MISTRAL_SMALL_03_25_VERSION = "2503" _MISTRAL_SMALL_01_25_VERSION = "2501" _MISTRAL_SMALL_09_24_VERSION = "2409" # Not uploaded to unsloth class MistralSmallModelInfo(ModelInfo): @classmethod def construct_model_name(cls, base_name, version, size, quant_type, instruct_tag): if version == _MISTRAL_SMALL_03_25_VERSION: key = f"{base_name}-3.1-{size}B-{instruct_tag}" else: key = f"{base_name}-{size}B-{instruct_tag}" key += f"-{version}" key = cls.append_quant_type(key, quant_type) return key MistralSmall_2503_Base_Meta = ModelMeta( org = "mistralai", base_name = "Mistral-Small", instruct_tags = ["Base"], model_version = _MISTRAL_SMALL_03_25_VERSION, model_sizes = ["24"], model_info_cls = MistralSmallModelInfo, is_multimodal = False, quant_types = [QuantType.NONE, QuantType.UNSLOTH, QuantType.BNB], ) MistralSmall_2503_Instruct_Meta = copy.deepcopy(MistralSmall_2503_Base_Meta) MistralSmall_2503_Instruct_Meta.instruct_tags = ["Instruct"] MistralSmall_2503_Instruct_Meta.quant_types = [ QuantType.NONE, QuantType.UNSLOTH, QuantType.BNB, QuantType.GGUF, ] MistralSmall_2501_Base_Meta = copy.deepcopy(MistralSmall_2503_Base_Meta) MistralSmall_2501_Base_Meta.model_version = _MISTRAL_SMALL_01_25_VERSION MistralSmall_2501_Instruct_Meta = copy.deepcopy(MistralSmall_2503_Instruct_Meta) MistralSmall_2501_Instruct_Meta.model_version = _MISTRAL_SMALL_01_25_VERSION def register_mistral_small_models(include_original_model: bool = False): global _IS_MISTRAL_SMALL_REGISTERED if _IS_MISTRAL_SMALL_REGISTERED: return _register_models( MistralSmall_2503_Base_Meta, include_original_model = include_original_model ) _register_models( MistralSmall_2503_Instruct_Meta, include_original_model = include_original_model ) _register_models( MistralSmall_2501_Base_Meta, include_original_model = include_original_model ) _register_models( MistralSmall_2501_Instruct_Meta, include_original_model = include_original_model ) _IS_MISTRAL_SMALL_REGISTERED = True def register_mistral_models(include_original_model: bool = False): register_mistral_small_models(include_original_model = include_original_model) if __name__ == "__main__": from unsloth.registry.registry import MODEL_REGISTRY, _check_model_info MODEL_REGISTRY.clear() register_mistral_models(include_original_model = True) for model_id, model_info in MODEL_REGISTRY.items(): model_info = _check_model_info(model_id) if model_info is None: print(f"\u2718 {model_id}") else: print(f"\u2713 {model_id}")
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/registry/_llama.py
unsloth/registry/_llama.py
from unsloth.registry.registry import ModelInfo, ModelMeta, QuantType, _register_models _IS_LLAMA_3_1_REGISTERED = False _IS_LLAMA_3_2_REGISTERED = False _IS_LLAMA_3_2_VISION_REGISTERED = False class LlamaModelInfo(ModelInfo): @classmethod def construct_model_name(cls, base_name, version, size, quant_type, instruct_tag): key = f"{base_name}-{version}-{size}B" return super().construct_model_name( base_name, version, size, quant_type, instruct_tag, key ) class LlamaVisionModelInfo(ModelInfo): @classmethod def construct_model_name(cls, base_name, version, size, quant_type, instruct_tag): key = f"{base_name}-{version}-{size}B-Vision" return super().construct_model_name( base_name, version, size, quant_type, instruct_tag, key ) # Llama 3.1 LlamaMeta_3_1 = ModelMeta( org = "meta-llama", base_name = "Llama", instruct_tags = [None, "Instruct"], model_version = "3.1", model_sizes = ["8"], model_info_cls = LlamaModelInfo, is_multimodal = False, quant_types = [QuantType.NONE, QuantType.BNB, QuantType.UNSLOTH], ) # Llama 3.2 Base Models LlamaMeta_3_2_Base = ModelMeta( org = "meta-llama", base_name = "Llama", instruct_tags = [None], model_version = "3.2", model_sizes = ["1", "3"], model_info_cls = LlamaModelInfo, is_multimodal = False, quant_types = [QuantType.NONE, QuantType.BNB, QuantType.UNSLOTH], ) # Llama 3.2 Instruction Tuned Models LlamaMeta_3_2_Instruct = ModelMeta( org = "meta-llama", base_name = "Llama", instruct_tags = ["Instruct"], model_version = "3.2", model_sizes = ["1", "3"], model_info_cls = LlamaModelInfo, is_multimodal = False, quant_types = [QuantType.NONE, QuantType.BNB, QuantType.UNSLOTH, QuantType.GGUF], ) # Llama 3.2 Vision LlamaMeta_3_2_Vision = ModelMeta( org = "meta-llama", base_name = "Llama", instruct_tags = [None, "Instruct"], model_version = "3.2", model_sizes = ["11", "90"], model_info_cls = LlamaVisionModelInfo, is_multimodal = True, quant_types = { "11": [QuantType.NONE, QuantType.BNB, QuantType.UNSLOTH], "90": [QuantType.NONE], }, ) def register_llama_3_1_models(include_original_model: bool = False): global _IS_LLAMA_3_1_REGISTERED if _IS_LLAMA_3_1_REGISTERED: return _register_models(LlamaMeta_3_1, include_original_model = include_original_model) _IS_LLAMA_3_1_REGISTERED = True def register_llama_3_2_models(include_original_model: bool = False): global _IS_LLAMA_3_2_REGISTERED if _IS_LLAMA_3_2_REGISTERED: return _register_models(LlamaMeta_3_2_Base, include_original_model = include_original_model) _register_models( LlamaMeta_3_2_Instruct, include_original_model = include_original_model ) _IS_LLAMA_3_2_REGISTERED = True def register_llama_3_2_vision_models(include_original_model: bool = False): global _IS_LLAMA_3_2_VISION_REGISTERED if _IS_LLAMA_3_2_VISION_REGISTERED: return _register_models( LlamaMeta_3_2_Vision, include_original_model = include_original_model ) _IS_LLAMA_3_2_VISION_REGISTERED = True def register_llama_models(include_original_model: bool = False): register_llama_3_1_models(include_original_model = include_original_model) register_llama_3_2_models(include_original_model = include_original_model) register_llama_3_2_vision_models(include_original_model = include_original_model) if __name__ == "__main__": from unsloth.registry.registry import MODEL_REGISTRY, _check_model_info MODEL_REGISTRY.clear() register_llama_models(include_original_model = True) for model_id, model_info in MODEL_REGISTRY.items(): model_info = _check_model_info(model_id) if model_info is None: print(f"\u2718 {model_id}") else: print(f"\u2713 {model_id}")
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/registry/_gemma.py
unsloth/registry/_gemma.py
from unsloth.registry.registry import ModelInfo, ModelMeta, QuantType, _register_models _IS_GEMMA_3_BASE_REGISTERED = False _IS_GEMMA_3_INSTRUCT_REGISTERED = False class GemmaModelInfo(ModelInfo): @classmethod def construct_model_name(cls, base_name, version, size, quant_type, instruct_tag): key = f"{base_name}-{version}-{size}B" return super().construct_model_name( base_name, version, size, quant_type, instruct_tag, key ) # Gemma3 Base Model Meta GemmaMeta3Base = ModelMeta( org = "google", base_name = "gemma", instruct_tags = ["pt"], # pt = base model_version = "3", model_sizes = ["1", "4", "12", "27"], model_info_cls = GemmaModelInfo, is_multimodal = True, quant_types = [QuantType.NONE, QuantType.BNB, QuantType.UNSLOTH], ) # Gemma3 Instruct Model Meta GemmaMeta3Instruct = ModelMeta( org = "google", base_name = "gemma", instruct_tags = ["it"], # it = instruction tuned model_version = "3", model_sizes = ["1", "4", "12", "27"], model_info_cls = GemmaModelInfo, is_multimodal = True, quant_types = [QuantType.NONE, QuantType.BNB, QuantType.UNSLOTH, QuantType.GGUF], ) def register_gemma_3_base_models(include_original_model: bool = False): global _IS_GEMMA_3_BASE_REGISTERED if _IS_GEMMA_3_BASE_REGISTERED: return _register_models(GemmaMeta3Base, include_original_model = include_original_model) _IS_GEMMA_3_BASE_REGISTERED = True def register_gemma_3_instruct_models(include_original_model: bool = False): global _IS_GEMMA_3_INSTRUCT_REGISTERED if _IS_GEMMA_3_INSTRUCT_REGISTERED: return _register_models(GemmaMeta3Instruct, include_original_model = include_original_model) _IS_GEMMA_3_INSTRUCT_REGISTERED = True def register_gemma_models(include_original_model: bool = False): register_gemma_3_base_models(include_original_model = include_original_model) register_gemma_3_instruct_models(include_original_model = include_original_model) if __name__ == "__main__": from unsloth.registry.registry import MODEL_REGISTRY, _check_model_info MODEL_REGISTRY.clear() register_gemma_models(include_original_model = True) for model_id, model_info in MODEL_REGISTRY.items(): model_info = _check_model_info(model_id) if model_info is None: print(f"\u2718 {model_id}") else: print(f"\u2713 {model_id}")
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/registry/_deepseek.py
unsloth/registry/_deepseek.py
from unsloth.registry.registry import ModelInfo, ModelMeta, QuantType, _register_models _IS_DEEPSEEK_V3_REGISTERED = False _IS_DEEPSEEK_V3_0324_REGISTERED = False _IS_DEEPSEEK_R1_REGISTERED = False _IS_DEEPSEEK_R1_ZERO_REGISTERED = False _IS_DEEPSEEK_R1_DISTILL_LLAMA_REGISTERED = False _IS_DEEPSEEK_R1_DISTILL_QWEN_REGISTERED = False class DeepseekV3ModelInfo(ModelInfo): @classmethod def construct_model_name(cls, base_name, version, size, quant_type, instruct_tag): key = f"{base_name}-V{version}" return super().construct_model_name( base_name, version, size, quant_type, instruct_tag, key ) class DeepseekR1ModelInfo(ModelInfo): @classmethod def construct_model_name(cls, base_name, version, size, quant_type, instruct_tag): key = f"{base_name}-{version}" if version else base_name if size: key = f"{key}-{size}B" return super().construct_model_name( base_name, version, size, quant_type, instruct_tag, key ) # Deepseek V3 Model Meta DeepseekV3Meta = ModelMeta( org = "deepseek-ai", base_name = "DeepSeek", instruct_tags = [None], model_version = "3", model_sizes = [""], model_info_cls = DeepseekV3ModelInfo, is_multimodal = False, quant_types = [QuantType.NONE, QuantType.BF16], ) DeepseekV3_0324Meta = ModelMeta( org = "deepseek-ai", base_name = "DeepSeek", instruct_tags = [None], model_version = "3-0324", model_sizes = [""], model_info_cls = DeepseekV3ModelInfo, is_multimodal = False, quant_types = [QuantType.NONE, QuantType.GGUF], ) DeepseekR1Meta = ModelMeta( org = "deepseek-ai", base_name = "DeepSeek-R1", instruct_tags = [None], model_version = "", model_sizes = [""], model_info_cls = DeepseekR1ModelInfo, is_multimodal = False, quant_types = [QuantType.NONE, QuantType.BF16, QuantType.GGUF], ) DeepseekR1ZeroMeta = ModelMeta( org = "deepseek-ai", base_name = "DeepSeek-R1", instruct_tags = [None], model_version = "Zero", model_sizes = [""], model_info_cls = DeepseekR1ModelInfo, is_multimodal = False, quant_types = [QuantType.NONE, QuantType.GGUF], ) DeepseekR1DistillLlamaMeta = ModelMeta( org = "deepseek-ai", base_name = "DeepSeek-R1-Distill", instruct_tags = [None], model_version = "Llama", model_sizes = ["8", "70"], model_info_cls = DeepseekR1ModelInfo, is_multimodal = False, quant_types = {"8": [QuantType.UNSLOTH, QuantType.GGUF], "70": [QuantType.GGUF]}, ) # Deepseek R1 Distill Qwen Model Meta DeepseekR1DistillQwenMeta = ModelMeta( org = "deepseek-ai", base_name = "DeepSeek-R1-Distill", instruct_tags = [None], model_version = "Qwen", model_sizes = ["1.5", "7", "14", "32"], model_info_cls = DeepseekR1ModelInfo, is_multimodal = False, quant_types = { "1.5": [QuantType.UNSLOTH, QuantType.BNB, QuantType.GGUF], "7": [QuantType.UNSLOTH, QuantType.BNB], "14": [QuantType.UNSLOTH, QuantType.BNB, QuantType.GGUF], "32": [QuantType.GGUF, QuantType.BNB], }, ) def register_deepseek_v3_models(include_original_model: bool = False): global _IS_DEEPSEEK_V3_REGISTERED if _IS_DEEPSEEK_V3_REGISTERED: return _register_models(DeepseekV3Meta, include_original_model = include_original_model) _IS_DEEPSEEK_V3_REGISTERED = True def register_deepseek_v3_0324_models(include_original_model: bool = False): global _IS_DEEPSEEK_V3_0324_REGISTERED if _IS_DEEPSEEK_V3_0324_REGISTERED: return _register_models(DeepseekV3_0324Meta, include_original_model = include_original_model) _IS_DEEPSEEK_V3_0324_REGISTERED = True def register_deepseek_r1_models(include_original_model: bool = False): global _IS_DEEPSEEK_R1_REGISTERED if _IS_DEEPSEEK_R1_REGISTERED: return _register_models(DeepseekR1Meta, include_original_model = include_original_model) _IS_DEEPSEEK_R1_REGISTERED = True def register_deepseek_r1_zero_models(include_original_model: bool = False): global _IS_DEEPSEEK_R1_ZERO_REGISTERED if _IS_DEEPSEEK_R1_ZERO_REGISTERED: return _register_models(DeepseekR1ZeroMeta, include_original_model = include_original_model) _IS_DEEPSEEK_R1_ZERO_REGISTERED = True def register_deepseek_r1_distill_llama_models(include_original_model: bool = False): global _IS_DEEPSEEK_R1_DISTILL_LLAMA_REGISTERED if _IS_DEEPSEEK_R1_DISTILL_LLAMA_REGISTERED: return _register_models( DeepseekR1DistillLlamaMeta, include_original_model = include_original_model ) _IS_DEEPSEEK_R1_DISTILL_LLAMA_REGISTERED = True def register_deepseek_r1_distill_qwen_models(include_original_model: bool = False): global _IS_DEEPSEEK_R1_DISTILL_QWEN_REGISTERED if _IS_DEEPSEEK_R1_DISTILL_QWEN_REGISTERED: return _register_models( DeepseekR1DistillQwenMeta, include_original_model = include_original_model ) _IS_DEEPSEEK_R1_DISTILL_QWEN_REGISTERED = True def register_deepseek_models(include_original_model: bool = False): register_deepseek_v3_models(include_original_model = include_original_model) register_deepseek_v3_0324_models(include_original_model = include_original_model) register_deepseek_r1_models(include_original_model = include_original_model) register_deepseek_r1_zero_models(include_original_model = include_original_model) register_deepseek_r1_distill_llama_models( include_original_model = include_original_model ) register_deepseek_r1_distill_qwen_models( include_original_model = include_original_model ) def _list_deepseek_r1_distill_models(): from unsloth.utils.hf_hub import ModelInfo as HfModelInfo from unsloth.utils.hf_hub import list_models models: list[HfModelInfo] = list_models( author = "unsloth", search = "Distill", limit = 1000 ) distill_models = [] for model in models: model_id = model.id model_name = model_id.split("/")[-1] # parse out only the version version = model_name.removeprefix("DeepSeek-R1-Distill-") distill_models.append(version) return distill_models register_deepseek_models(include_original_model = True) if __name__ == "__main__": from unsloth.registry.registry import MODEL_REGISTRY, _check_model_info MODEL_REGISTRY.clear() register_deepseek_models(include_original_model = True) for model_id, model_info in MODEL_REGISTRY.items(): model_info = _check_model_info(model_id) if model_info is None: print(f"\u2718 {model_id}") else: print(f"\u2713 {model_id}") # distill_models = _list_deepseek_r1_distill_models() # for model in sorted(distill_models): # if "qwen" in model.lower(): # print(model)
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/registry/__init__.py
unsloth/registry/__init__.py
from ._deepseek import register_deepseek_models as _register_deepseek_models from ._gemma import register_gemma_models as _register_gemma_models from ._llama import register_llama_models as _register_llama_models from ._mistral import register_mistral_models as _register_mistral_models from ._phi import register_phi_models as _register_phi_models from ._qwen import register_qwen_models as _register_qwen_models from .registry import MODEL_REGISTRY, ModelInfo, QuantType _ARE_MODELS_REGISTERED = False def register_models(): global _ARE_MODELS_REGISTERED if _ARE_MODELS_REGISTERED: return _register_deepseek_models() _register_gemma_models() _register_llama_models() _register_mistral_models() _register_phi_models() _register_qwen_models() _ARE_MODELS_REGISTERED = True def search_models( org: str = None, base_name: str = None, version: str = None, size: str = None, quant_types: list[QuantType] = None, search_pattern: str = None, ) -> list[ModelInfo]: """ Get model info from the registry. See registry.ModelInfo for more fields. If search_pattern is provided, the full model path will be matched against the pattern, where the model path is the model_id on huggingface hub. """ if not _ARE_MODELS_REGISTERED: register_models() model_infos = MODEL_REGISTRY.values() if org: model_infos = [ model_info for model_info in model_infos if model_info.org == org ] if base_name: model_infos = [ model_info for model_info in model_infos if model_info.base_name == base_name ] if version: model_infos = [ model_info for model_info in model_infos if model_info.version == version ] if size: model_infos = [ model_info for model_info in model_infos if model_info.size == size ] if quant_types: model_infos = [ model_info for model_info in model_infos if any(model_info.quant_type == quant_type for quant_type in quant_types) ] if search_pattern: model_infos = [ model_info for model_info in model_infos if search_pattern in model_info.model_path ] return model_infos
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/dataprep/synthetic.py
unsloth/dataprep/synthetic.py
# 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. __all__ = [ "SyntheticDataKit", ] import subprocess import threading from collections import deque import time import os os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" import requests import torch import gc import time import re from unsloth_zoo.vllm_utils import ( load_vllm, patch_vllm, delete_vllm, ) from unsloth_zoo.log import logger import numpy as np from .synthetic_configs import ( synthetic_qa_config, ) def terminate_tree(proc: subprocess.Popen, timeout = 15): if proc is None or proc.poll() is not None: return try: import psutil parent = psutil.Process(proc.pid) for child in parent.children(recursive = True): child.terminate() parent.terminate() parent.wait(timeout = timeout / 2) return except: pass if os.name == "nt": try: subprocess.run( ["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output = True, timeout = 5, ) proc.wait(timeout = 1) return except: pass proc.kill() try: proc.wait(timeout = 5) except: pass class PipeCapture: """Non blocking pipe capture""" def __init__( self, pipe, keep_lines = 2000, echo = False, name = "", text = True, encoding = "utf-8", errors = "replace", ready_regex = None, ): self.pipe = pipe self.buf = deque(maxlen = keep_lines) self.lock = threading.Lock() self.echo = echo self.name = name self.text = text self.encoding = encoding self.errors = errors self.ready_event = threading.Event() self.closed_event = threading.Event() self.ready_regex = None if ready_regex is not None: if not hasattr(ready_regex, "search"): ready_regex = re.compile(ready_regex) self.ready_regex = ready_regex self.t = threading.Thread(target = self._reader, daemon = True) self.t.start() def _reader(self): try: sentinel = "" if self.text else b"" for raw_line in iter(self.pipe.readline, sentinel): if not self.text: line = raw_line.decode(self.encoding, self.errors) else: line = raw_line line = line.rstrip("\r\n") if self.echo: if "platform is" not in line: print(f"{self.name}: {line}") with self.lock: self.buf.append(line) if self.ready_regex is not None and self.ready_regex.search(line): self.ready_event.set() finally: try: self.pipe.close() except Exception: pass self.closed_event.set() def wait_for_ready(self, timeout = None): return self.ready_event.wait(timeout) def has_closed(self): return self.closed_event.is_set() def wait_until_closed(self, timeout = None): return self.closed_event.wait(timeout) def tail(self, n = 200): with self.lock: return "\n".join(list(self.buf)[-n:]) class SyntheticDataKit: def __init__( self, model_name = "unsloth/Llama-3.1-8B-Instruct-unsloth-bnb-4bit", max_seq_length = 2048, gpu_memory_utilization = 0.98, float8_kv_cache = False, conservativeness = 1.0, token = None, timeout = 1200, # maybe this is not enough for large models if we need to download **kwargs, ): assert type(model_name) is str assert type(max_seq_length) is int assert type(gpu_memory_utilization) is float assert type(float8_kv_cache) is bool assert type(conservativeness) is float assert token is None or type(token) is str self.model_name = model_name self.max_seq_length = max_seq_length from transformers import AutoConfig, AutoTokenizer self.config = AutoConfig.from_pretrained( model_name, token = token, ) self.tokenizer = AutoTokenizer.from_pretrained( model_name, token = token, ) patch_vllm(debug = False) engine_args = load_vllm( model_name = model_name, config = self.config, gpu_memory_utilization = gpu_memory_utilization, max_seq_length = max_seq_length, disable_log_stats = True, float8_kv_cache = float8_kv_cache, conservativeness = conservativeness, return_args = True, enable_lora = False, use_bitsandbytes = False, compilation_config = 3, **kwargs, ) if "dtype" in engine_args: dtype_val = engine_args["dtype"] if dtype_val == torch.float16: dtype_val = "float16" elif dtype_val == torch.bfloat16: dtype_val = "bfloat16" elif dtype_val == torch.float32: dtype_val = "float32" engine_args["dtype"] = dtype_val # Convert torch.bfloat16, torch.float16, etc. to valid CLI string if hasattr(dtype_val, "name"): engine_args["dtype"] = dtype_val.name elif isinstance(dtype_val, str) and dtype_val.startswith("torch."): engine_args["dtype"] = dtype_val.split(".")[-1] # Only allow valid vLLM choices valid_dtypes = {"auto", "bfloat16", "float", "float16", "float32", "half"} if engine_args["dtype"] not in valid_dtypes: engine_args["dtype"] = "auto" if "device" in engine_args: del engine_args["device"] if "model" in engine_args: del engine_args["model"] subprocess_commands = [ "vllm", "serve", str(model_name), ] for key, value in engine_args.items(): flag = key.replace("_", "-") if key == "compilation_config": # [TODO] Unsure why subprocess doesn't process json properly # Also -O3 breaks on T4! # subprocess_commands += ["-O3",] continue which = str(value).replace("torch.", "") if which == "True": # Ignore --enforce-eager True subprocess_commands += [ "--" + flag, ] elif which == "False": # Ignore flag pass elif which == "None": # Ignore flag pass else: subprocess_commands += [ "--" + flag, which, ] logger.info(subprocess_commands) vllm_process = subprocess.Popen( subprocess_commands, stdout = subprocess.PIPE, stderr = subprocess.PIPE, start_new_session = True, ) ready_re = re.compile(r"Starting vLLM API server(?:\s+\d+)?\s+on\b") self.vllm_process = vllm_process self.stdout_capture = PipeCapture( vllm_process.stdout, keep_lines = 1000, echo = True, name = "vLLM STDOUT", ready_regex = ready_re, text = False, ) self.stderr_capture = PipeCapture( vllm_process.stderr, keep_lines = 2000, echo = False, name = "vLLM STDERR", ready_regex = None, text = False, ) # we don't print stderr to console but self.stderr_capture.tail(200) will print the last 200 lines ready = self.stdout_capture.wait_for_ready(timeout = timeout) if not ready: if self.stdout_capture.has_closed() or self.vllm_process.poll() is not None: print("Stdout stream ended before readiness message detected.") print("\n--- stdout tail ---\n", self.stdout_capture.tail(50)) print("\n--- stderr tail ---\n", self.stderr_capture.tail(50)) else: print(f"Unsloth: vllm_process failed to load! (timeout={timeout})") print("\n--- stdout tail ---\n", self.stdout_capture.tail(50)) print("\n--- stderr tail ---\n", self.stderr_capture.tail(50)) terminate_tree(self.vllm_process) return else: print("vLLM Server Ready Detected") trial = 0 while not self.check_vllm_status(): if trial >= 100: print("Unsloth: vllm_process failed to load!") print("\n--- stdout tail ---\n", self.stdout_capture.tail(50)) print("\n--- stderr tail ---\n", self.stderr_capture.tail(50)) terminate_tree(self.vllm_process) return trial += 1 time.sleep(1) return @staticmethod def from_pretrained( model_name = "unsloth/Llama-3.1-8B-Instruct-unsloth-bnb-4bit", max_seq_length = 2048, gpu_memory_utilization = 0.9, float8_kv_cache = False, conservativeness = 1.0, token = None, **kwargs, ): return SyntheticDataKit( model_name = model_name, max_seq_length = max_seq_length, gpu_memory_utilization = gpu_memory_utilization, float8_kv_cache = float8_kv_cache, conservativeness = conservativeness, token = token, **kwargs, ) @staticmethod def check_vllm_status(): try: response = requests.get("http://localhost:8000/metrics") if response.status_code == 200: return True except requests.exceptions.ConnectionError: return False def cleanup(self): if not hasattr(self, "vllm_process"): return vllm_process = self.vllm_process print("Attempting to terminate the VLLM server gracefully...") try: vllm_process.terminate() vllm_process.wait(timeout = 10) print("Server terminated gracefully.") except subprocess.TimeoutExpired: print( "Server did not terminate gracefully after 10 seconds. Forcing kill..." ) vllm_process.kill() vllm_process.wait() print("Server killed forcefully.") except Exception as e: print(f"An error occurred while trying to stop the process: {e}") try: if vllm_process.poll() is None: print("Attempting forceful kill due to error...") vllm_process.kill() vllm_process.wait() print("Server killed forcefully after error.") except Exception as kill_e: print(f"Error during forceful kill: {kill_e}") for _ in range(10): torch.cuda.empty_cache() gc.collect() # Delete vLLM module as well delete_vllm(llm = None) def __enter__(self): return self def __exit__(self, *exc): self.cleanup() def __del__(self): self.cleanup() def chunk_data(self, filename = None): # Chunks data by max tokens and generation length assert filename is not None assert os.path.exists(filename) assert hasattr(self, "tokenizer") if not hasattr(self, "max_seq_length"): raise RuntimeError( "Please use SynthetidDataKit.from_pretrained(...) first!" ) if not hasattr(self, "overlap") or not hasattr(self, "max_generation_tokens"): raise RuntimeError("Please use prepare_qa_generation first!") with open(filename, "r", encoding = "utf-8") as f: text = f.read() max_tokens = ( self.max_seq_length - self.max_generation_tokens * 2 - 128 ) # -128 to reduce errors if max_tokens <= 5: raise RuntimeError("Generation length is way too long!") input_ids = self.tokenizer(text, add_special_tokens = False).input_ids # Get left and right boundaries length = len(input_ids) n_chunks = int(np.ceil(length / (max_tokens - self.overlap))) boundaries = np.ceil(np.linspace(0, length - self.overlap, n_chunks)).astype( int ) boundaries = np.stack((boundaries[:-1], (boundaries + self.overlap)[1:])).T boundaries = np.minimum(boundaries, length).tolist() # Get extension of filename like .txt filename, extension = os.path.splitext(filename) if filename.endswith("/"): filename = filename[:-1] all_filenames = [] for i, (left, right) in enumerate(boundaries): chunked_text = self.tokenizer.decode(input_ids[left:right]) new_filename = f"{filename}_{i}{extension}" all_filenames.append(new_filename) with open(new_filename, "w", encoding = "utf-8") as f: f.write(chunked_text) return all_filenames def prepare_qa_generation( self, output_folder = "data", max_generation_tokens = 512, temperature = 0.7, top_p = 0.95, overlap = 64, default_num_pairs = 25, cleanup_threshold = 1.0, cleanup_batch_size = 4, cleanup_temperature = 0.3, ): assert hasattr(self, "model_name") assert hasattr(self, "max_seq_length") assert max_generation_tokens < self.max_seq_length locations = "pdf,html,youtube,docx,ppt,txt,output,generated,cleaned,final" locations = locations.split(",") for path in locations: os.makedirs(os.path.join(output_folder, path), exist_ok = True) self.max_generation_tokens = max_generation_tokens config = ( synthetic_qa_config.replace("{data_output_location}", str(output_folder)) .replace("{model_name}", str(self.model_name)) .replace("{temperature}", str(temperature)) .replace("{top_p}", str(top_p)) .replace( "{chunk_size}", str(self.max_seq_length - max_generation_tokens * 2 - 2) ) .replace("{overlap}", str(overlap)) .replace("{max_tokens}", str(max_generation_tokens)) .replace("{default_num_pairs}", str(default_num_pairs)) .replace("{cleanup_threshold}", str(cleanup_threshold)) .replace("{cleanup_batch_size}", str(cleanup_batch_size)) .replace("{cleanup_temperature}", str(cleanup_temperature)) ) with open("synthetic_data_kit_config.yaml", "w", encoding = "utf-8") as f: f.write(config) self.overlap = overlap
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/dataprep/synthetic_configs.py
unsloth/dataprep/synthetic_configs.py
# 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. synthetic_qa_config = """\ # Master configuration file for Synthetic Data Kit # Global paths configuration paths: # Input data locations input: pdf: "{data_output_location}/pdf" html: "{data_output_location}/html" youtube: "{data_output_location}/youtube" docx: "{data_output_location}/docx" ppt: "{data_output_location}/ppt" txt: "{data_output_location}/txt" # Output locations output: parsed: "{data_output_location}/output" # Where parsed text files are saved generated: "{data_output_location}/generated" # Where generated content is saved cleaned: "{data_output_location}/cleaned" # Where cleaned content is saved final: "{data_output_location}/final" # Where final formatted content is saved # VLLM server configuration vllm: api_base: "http://localhost:8000/v1" # Base URL for VLLM API port: 8000 # Port for VLLM server model: "{model_name}" # Default model to use max_retries: 3 # Number of retries for API calls retry_delay: 1.0 # Initial delay between retries (seconds) # Ingest configuration ingest: default_format: "txt" # Default output format for parsed files youtube_captions: "auto" # Options: "auto", "manual" - caption preference # LLM generation parameters generation: temperature: {temperature} # Higher = more creative, lower = more deterministic top_p: {top_p} # Nucleus sampling parameter chunk_size: {chunk_size} # Size of text chunks for processing overlap: {overlap} # Overlap between chunks to maintain context max_tokens: {max_tokens} # Maximum tokens in LLM responses num_pairs: {default_num_pairs} # Default number of QA pairs to generate # Content cleanup parameters cleanup: threshold: {cleanup_threshold} # Default quality threshold (1-10) batch_size: {cleanup_batch_size} # Number of items per batch for rating temperature: {cleanup_temperature} # Temperature for rating (lower = more consistent) # Format conversion parameters format: default: "jsonl" # Default output format include_metadata: true # Include metadata in output files pretty_json: true # Use indentation in JSON output # Prompts for different tasks prompts: # Summary generation prompt summary: | Summarize this document in 3-5 sentences, focusing on the main topic and key concepts. # QA pair generation prompt qa_generation: | Create {num_pairs} question-answer pairs from this text for LLM training. Rules: 1. Questions must be about important facts in the text 2. Answers must be directly supported by the text 3. Return JSON format only: [ {{ "question": "Question 1?", "answer": "Answer 1." }}, {{ "question": "Question 2?", "answer": "Answer 2." }} ] Text: {text} # QA pair rating prompt qa_rating: | Rate each of these question-answer pairs for quality and return exactly this JSON format: [ {{"question": "same question text", "answer": "same answer text", "rating": n}} ] Where n is a number from 1-10. DO NOT include any text outside of the JSON array, just return valid JSON: {pairs}"""
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/dataprep/__init__.py
unsloth/dataprep/__init__.py
# 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. from .synthetic import *
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/layernorm.py
unsloth/kernels/layernorm.py
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved. # Copyright 2024-present Andrej Karpathy & the llm.c 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 triton import triton.language as tl import torch from .utils import calculate_settings, torch_gpu_device from unsloth_zoo.patching_utils import ( patch_layernorm, ) @triton.jit def layernorm_forward( Y, Y_row_stride, X, X_row_stride, W, b, r, mu, n_cols: tl.constexpr, eps: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): row_idx = tl.program_id(0) col_offsets = tl.arange(0, BLOCK_SIZE) mask = col_offsets < n_cols Y += row_idx * Y_row_stride X += row_idx * X_row_stride r += row_idx mu += row_idx # According to https://pytorch.org/torchtune/stable/_modules/torchtune/modules/layer_norm.html#Fp32LayerNorm, all modules # are in float32! X_row = tl.load(X + col_offsets, mask = mask, other = 0).to(tl.float32) W_row = tl.load(W + col_offsets, mask = mask, other = 0).to(tl.float32) b_row = tl.load(b + col_offsets, mask = mask, other = 0).to(tl.float32) mean_X = tl.sum(X_row, axis = 0) / n_cols # (X[0] - mean) == -mean so we need to mask it out XX = tl.where(mask, X_row - mean_X, 0) row_var = tl.sum(XX * XX, axis = 0) / n_cols inv_var = tl.math.rsqrt(row_var + eps) tl.store(r, inv_var) tl.store(mu, mean_X) output = (XX * inv_var) * W_row + b_row tl.store(Y + col_offsets, output, mask = mask) @triton.jit def layernorm_backward( dY, dY_row_stride, X, X_row_stride, W, b, r, mu, n_cols: tl.constexpr, eps: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): # Approximately follows https://github.com/karpathy/llm.c/blob/master/doc/layernorm/layernorm.md row_idx = tl.program_id(0) col_offsets = tl.arange(0, BLOCK_SIZE) mask = col_offsets < n_cols dY += row_idx * dY_row_stride X += row_idx * X_row_stride r += row_idx mu += row_idx # According to https://pytorch.org/torchtune/stable/_modules/torchtune/modules/layer_norm.html#Fp32LayerNorm, all modules # are in float32! dY_row = tl.load(dY + col_offsets, mask = mask, other = 0).to(tl.float32) X_row = tl.load(X + col_offsets, mask = mask, other = 0).to(tl.float32) W_row = tl.load(W + col_offsets, mask = mask, other = 0).to(tl.float32) b_row = tl.load(b + col_offsets, mask = mask, other = 0).to(tl.float32) inv_var = tl.load(r).to(tl.float32) mean = tl.load(mu).to(tl.float32) normed = (X_row - mean) * inv_var dY_W = dY_row * W_row dX_row = ( dY_W - tl.sum(dY_W, axis = 0) / n_cols - normed * tl.sum(dY_W * normed, axis = 0) / n_cols ) dX_row = dX_row * inv_var tl.store(dY + col_offsets, dX_row, mask = mask) class Fast_Layernorm(torch.autograd.Function): @staticmethod def forward(ctx, X, W, b, eps): shape = X.shape dim = shape[-1] X = X.view(-1, dim) n_rows, n_cols = X.shape BLOCK_SIZE, num_warps = calculate_settings(n_cols) device = X.device Y = torch.empty((n_rows, n_cols), dtype = X.dtype, device = device) r = torch.empty(n_rows, dtype = torch.float32, device = device) mu = torch.empty(n_rows, dtype = torch.float32, device = device) with torch_gpu_device(device): layernorm_forward[(n_rows,)]( Y, Y.stride(0), X, X.stride(0), W, b, r, mu, n_cols, eps, BLOCK_SIZE = BLOCK_SIZE, num_warps = num_warps, ) ctx.eps = eps ctx.BLOCK_SIZE = BLOCK_SIZE ctx.num_warps = num_warps ctx.save_for_backward(X, W, b, r, mu) return Y.view(*shape) @staticmethod def backward(ctx, dY): shape = dY.shape dim = shape[-1] dY = dY.view(-1, dim) X, W, b, r, mu = ctx.saved_tensors n_rows, n_cols = dY.shape with torch_gpu_device(dY.device): layernorm_backward[(n_rows,)]( dY, dY.stride(0), X, X.stride(0), W, b, r, mu, n_cols, ctx.eps, BLOCK_SIZE = ctx.BLOCK_SIZE, num_warps = ctx.num_warps, ) dX = dY.view(*shape) return dX, None, None, None, None def fast_layernorm(layernorm, X): assert layernorm.elementwise_affine is True W = layernorm.weight bias = layernorm.bias eps = ( layernorm.variance_epsilon if hasattr(layernorm, "variance_epsilon") else layernorm.eps ) out = Fast_Layernorm.apply(X, W, bias, eps) return out def test_layernorm( dim = 1024, eps = 1e-5, dtype = torch.float16, bsz = 21, random_state = 3407, seqlen = 3341, ): from torch.nn import LayerNorm layernorm = LayerNorm((dim,), eps = eps, device = "cuda", dtype = dtype) torch.cuda.manual_seed(random_state) torch.manual_seed(random_state) torch.nn.init.uniform_(layernorm.weight) torch.nn.init.uniform_(layernorm.bias) X = torch.randn((bsz, seqlen, dim), dtype = dtype, device = "cuda") XX = X.clone() X.requires_grad_(True) XX.requires_grad_(True) Y = layernorm(X) YY = torch.randn((bsz, seqlen, dim), dtype = dtype, device = "cuda", requires_grad = True) Y.backward(YY) correct_grad = X.grad.clone() # from unsloth.kernels import fast_layernorm Y = fast_layernorm(layernorm, XX) Y.backward(YY) assert torch.dist(correct_grad, XX.grad).item() <= 0.1 def testing_suite_layernorm(): for dim in [512, 1024, 2048]: for dtype in [torch.float16, torch.bfloat16]: with torch.autocast(device_type = "cuda", dtype = dtype): for seqlen in [3341, 2048, 349]: for random_state in [3407, 42]: test_layernorm( dim = dim, eps = 1e-5, dtype = dtype, bsz = 21, random_state = random_state, seqlen = seqlen, )
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/cross_entropy_loss.py
unsloth/kernels/cross_entropy_loss.py
# 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 triton import triton.language as tl import torch from .utils import ( calculate_settings, MAX_FUSED_SIZE, triton_tanh, triton_cast, torch_gpu_device, is_cdna, ) from transformers.models.llama.modeling_llama import logger from packaging.version import Version from unsloth_zoo.loss_utils import ( patch_loss_functions as _patch_loss_functions, post_patch_loss_function, ) def _cross_entropy_forward( logits_ptr, logits_row_stride, loss_ptr, logsumexp_ptr, labels_ptr, VOCAB_SIZE: tl.constexpr, BLOCK_SIZE: tl.constexpr, DO_SOFTCAPPING: tl.constexpr, SOFTCAP: tl.constexpr, DO_LOGIT_SCALING: tl.constexpr, LOGIT_SCALE: tl.constexpr, ): """ Cross Entropy Loss = 1/n sum [ -yi log(Pi) ] Pi = exp(xi) / sum(exp(xi)) CE_i = -y log(p) = -y log[ exp(x) / sum(exp(x)) ] = -y [ x - log[sum(exp(x))] ] = y * (log[sum(exp(x))] - x) If y == 0: CE_i = 0 If y == 1: CE_i = logsumexp - x logsumexp is also stable Take y = log[sum(exp(x))] exp(y) = sum(exp(x)) exp(y) = sum(exp(x - c)*exp(c)) Since e^(x-c)*e^c = e^x exp(y) = exp(c)*sum(exp(x - c)) y = log(exp(c)*sum(exp(x - c))) y = c + log[sum(exp(x - c))] This means we can set c = max(x) to make sure exp(x - c) always is exp(x - max(x)). This ensures exp(x - max(x))'s maximum is 1 as exp(0) = 1. """ row_idx = tl.program_id(0) logits_ptr += row_idx * triton_cast(logits_row_stride, tl.int64) loss_ptr += row_idx logsumexp_ptr += row_idx labels_ptr += row_idx col_offsets = tl.arange(0, BLOCK_SIZE) mask = col_offsets < VOCAB_SIZE label_idx = tl.load(labels_ptr).to(tl.int32) logits = tl.load(logits_ptr + col_offsets, mask = mask, other = -float("inf")).to( tl.float32 ) # Go logit scaling for Cohere: t * x if DO_LOGIT_SCALING: logits = LOGIT_SCALE * logits # Do logit softcapping for Gemma 2: t * tanh(1/t * x) if DO_SOFTCAPPING: logits = SOFTCAP * triton_tanh(logits / SOFTCAP) c = tl.max(logits, 0) logsumexp = c + tl.log(tl.sum(tl.exp(logits - c), 0)) if label_idx != -100: x = tl.load(logits_ptr + label_idx).to(tl.float32) # Go logit scaling for Cohere: t * x if DO_LOGIT_SCALING: x = LOGIT_SCALE * x # Do logit softcapping for Gemma 2: t * tanh(1/t * x) if DO_SOFTCAPPING: x = SOFTCAP * triton_tanh(x / SOFTCAP) loss = logsumexp - x else: loss = 0.0 tl.store(logsumexp_ptr, logsumexp) tl.store(loss_ptr, loss) _cross_entropy_forward = triton.jit(_cross_entropy_forward) _cross_entropy_forward = triton.heuristics( { "DO_SOFTCAPPING": lambda args: bool(args["DO_SOFTCAPPING"]), "DO_LOGIT_SCALING": lambda args: bool(args["DO_LOGIT_SCALING"]), } )(_cross_entropy_forward) def _chunked_cross_entropy_forward( logits_ptr, logits_row_stride: tl.constexpr, loss_ptr, logsumexp_ptr, labels_ptr, VOCAB_SIZE: tl.constexpr, N_CHUNKS: tl.constexpr, BLOCK_SIZE: tl.constexpr, DO_SOFTCAPPING: tl.constexpr, SOFTCAP: tl.constexpr, DO_LOGIT_SCALING: tl.constexpr, LOGIT_SCALE: tl.constexpr, ): """ 256K vocab divided in 4 chunks |-65536-| |-65536-| |-65536-| |-65536-| |-------| |-------| |-------| |-------| |-------| |-------| |-------| |-------| If y == 0: CE_i = 0 If y == 1: CE_i = logsumexp - x Notice we can do logsumexp for each chunk and then logsumexp[chunk_sum(logsumexp)] == logsumexp chunk_sum = log[chunk_sum(logsumexp)] = log[exp(logsumexp(a)) + ... + exp(logsumexp(z))] = log[exp(log[sum(exp(a))]) + ... + exp(log[sum(exp(z))])] = log[sum(exp(a)) + ... + sum(exp(z))] = logsumexp(x) This means we can perform a logsumexp for each chunk, then do a final logsumexp reduction! Ie do: logsumexp(chunked_logsumexp) - x """ row_idx = tl.program_id(0) chunk_idx = tl.program_id(1) logits_ptr += row_idx * triton_cast(logits_row_stride, tl.int64) loss_ptr += row_idx logsumexp_ptr += row_idx * N_CHUNKS + chunk_idx labels_ptr += row_idx col_offsets = chunk_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = col_offsets < VOCAB_SIZE label_idx = tl.load(labels_ptr).to(tl.int32) logits = tl.load(logits_ptr + col_offsets, mask = mask, other = -float("inf")).to( tl.float32 ) # Go logit scaling for Cohere: t * x if DO_LOGIT_SCALING: logits = LOGIT_SCALE * logits # Do logit softcapping for Gemma 2: t * tanh(1/t * x) if DO_SOFTCAPPING: logits = SOFTCAP * triton_tanh(logits / SOFTCAP) c = tl.max(logits, 0) logsumexp = c + tl.log(tl.sum(tl.exp(logits - c), 0)) if chunk_idx == 0: # logsumexp(chunked_logsumexp) - x # Do the -x separately if label_idx != -100: x = tl.load(logits_ptr + label_idx).to(tl.float32) # Go logit scaling for Cohere: t * x if DO_LOGIT_SCALING: x = LOGIT_SCALE * x # Do logit softcapping for Gemma 2: t * tanh(1/t * x) if DO_SOFTCAPPING: x = SOFTCAP * triton_tanh(x / SOFTCAP) loss = -1.0 * x else: loss = 0.0 tl.store(loss_ptr, loss) tl.store(logsumexp_ptr, logsumexp) _chunked_cross_entropy_forward = triton.jit(_chunked_cross_entropy_forward) _chunked_cross_entropy_forward = triton.heuristics( { "DO_SOFTCAPPING": lambda args: bool(args["DO_SOFTCAPPING"]), "DO_LOGIT_SCALING": lambda args: bool(args["DO_LOGIT_SCALING"]), } )(_chunked_cross_entropy_forward) def _cross_entropy_backward( logits_ptr, logits_row_stride: tl.constexpr, dloss_ptr, dloss_row_stride: tl.constexpr, logsumexp_ptr, labels_ptr, VOCAB_SIZE: tl.constexpr, BLOCK_SIZE: tl.constexpr, DO_SOFTCAPPING: tl.constexpr, SOFTCAP: tl.constexpr, DO_LOGIT_SCALING: tl.constexpr, LOGIT_SCALE: tl.constexpr, ): """ CE_i = -y log(P) = y * (log[sum(exp(x))] - x) dC/dx = d/dx (y * log[sum(exp(x))] - x * y) From https://en.wikipedia.org/wiki/LogSumExp d/dx logsumexp = exp(x) / sum(exp(x)) = softmax(x) dC/dx = y * exp(x) / sum(exp(x)) - d/dx (x * y) dC/dx = y * exp[ log[exp(x) / sum(exp(x))] ] using x = exp(log(x)) trick dC/dx = y * exp[x - logsumexp] - d/dx (x * y) If y == 0: dC/dx = 0 If y == 1 and x == label: dC/dlabel = exp[x - logsumexp] - 1 If y == 1 and x != label: dC/dx = exp[x - logsumexp] """ row_idx = tl.program_id(0) block_idx = tl.program_id(1) logits_ptr += row_idx * triton_cast(logits_row_stride, tl.int64) dloss_ptr += row_idx * dloss_row_stride col_offsets = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = col_offsets < VOCAB_SIZE label_idx = tl.load(labels_ptr + row_idx).to(tl.int32) if label_idx != -100: dloss = tl.load(dloss_ptr) else: dloss = 0.0 x = tl.load(logits_ptr + col_offsets, mask = mask, other = -float("inf")).to(tl.float32) # Do logit scaling for Cohere if DO_LOGIT_SCALING: # d/dx [s * x] = s x = x * LOGIT_SCALE # Do logit softcapping for Gemma 2: t * tanh(1/t * x) partial = x if DO_SOFTCAPPING: # d/dx [t * tanh(1/t * x)] = 1 - tanh^2(1/t * x) partial = triton_tanh(x / SOFTCAP) x = SOFTCAP * partial logsumexp = tl.load(logsumexp_ptr + row_idx) y = tl.exp(x - logsumexp) y = tl.where( col_offsets == label_idx, y - 1.0, # exp(x - logsumexp) - 1 y, # exp(x - logsumexp) ) if DO_LOGIT_SCALING: # d/dx [s * x] = s y = y * LOGIT_SCALE if DO_SOFTCAPPING: # d/dx [t * tanh(1/t * x)] = 1 - tanh^2(1/t * x) y = y * (1.0 - partial * partial) # If y == 0: dC/dx = 0 ==> we already masked it to be = 0, so dloss = 0. tl.store(logits_ptr + col_offsets, dloss * y, mask = mask) _cross_entropy_backward = triton.jit(_cross_entropy_backward) _cross_entropy_backward = triton.heuristics( { "DO_SOFTCAPPING": lambda args: bool(args["DO_SOFTCAPPING"]), "DO_LOGIT_SCALING": lambda args: bool(args["DO_LOGIT_SCALING"]), } )(_cross_entropy_backward) MAX_FUSED_SIZE = 65536 # 2**16 class Fast_CrossEntropyLoss(torch.autograd.Function): @staticmethod def forward( ctx, logits, labels, logit_softcapping: float = 0, logit_scaling: float = 0 ): n_rows: int vocab_size: int n_rows, vocab_size = logits.shape device = logits.device div, mod = divmod(vocab_size, MAX_FUSED_SIZE) n_chunks: int = div + (mod != 0) losses = torch.empty(n_rows, dtype = torch.float32, device = device) DO_SOFTCAPPING: bool = bool(logit_softcapping != 0) DO_LOGIT_SCALING: bool = bool(logit_scaling != 0) BLOCK_SIZE: int num_warps: int if n_chunks == 1: # For small vocabs <= 65336 like Llama, Mistral BLOCK_SIZE, num_warps = calculate_settings(vocab_size) if is_cdna(): num_warps = num_warps // 2 logsumexp = torch.empty(n_rows, dtype = torch.float32, device = device) with torch_gpu_device(device): _cross_entropy_forward[(n_rows,)]( logits, logits.stride(0), losses, logsumexp, labels, VOCAB_SIZE = vocab_size, BLOCK_SIZE = BLOCK_SIZE, DO_SOFTCAPPING = DO_SOFTCAPPING, SOFTCAP = logit_softcapping, DO_LOGIT_SCALING = DO_LOGIT_SCALING, LOGIT_SCALE = logit_scaling, num_warps = num_warps, ) else: # For large vocabs > 65336 like Gemma 256K logsumexp = torch.empty( ( n_rows, n_chunks, ), dtype = torch.float32, device = device, ) with torch_gpu_device(device): _chunked_cross_entropy_forward[ ( n_rows, n_chunks, ) ]( logits, logits.stride(0), losses, logsumexp, labels, VOCAB_SIZE = vocab_size, N_CHUNKS = n_chunks, BLOCK_SIZE = MAX_FUSED_SIZE, DO_SOFTCAPPING = DO_SOFTCAPPING, SOFTCAP = logit_softcapping, DO_LOGIT_SCALING = DO_LOGIT_SCALING, LOGIT_SCALE = logit_scaling, num_warps = 32 if not is_cdna() else 16, ) # logsumexp(chunked_logsumexp) - x # Do the -x separately logsumexp = torch.logsumexp(logsumexp, dim = 1) # Row sum losses += logsumexp losses.masked_fill_(labels == -100, 0) # Don't forget to mask padding out! ctx.save_for_backward(logits, logsumexp, labels) ctx.DO_SOFTCAPPING = DO_SOFTCAPPING ctx.logit_softcapping = logit_softcapping ctx.DO_LOGIT_SCALING = DO_LOGIT_SCALING ctx.logit_scaling = logit_scaling return losses @staticmethod def backward(ctx, dlosses): logits, logsumexp, labels = ctx.saved_tensors n_rows: int vocab_size: int n_rows, vocab_size = logits.shape BLOCK_SIZE: int = 4096 div: int mod: int div, mod = divmod(vocab_size, BLOCK_SIZE) n_blocks: int = div + (mod != 0) with torch_gpu_device(dlosses.device): _cross_entropy_backward[ ( n_rows, n_blocks, ) ]( logits, logits.stride(0), dlosses, dlosses.stride(0), logsumexp, labels, VOCAB_SIZE = vocab_size, BLOCK_SIZE = BLOCK_SIZE, DO_SOFTCAPPING = ctx.DO_SOFTCAPPING, SOFTCAP = ctx.logit_softcapping, DO_LOGIT_SCALING = ctx.DO_LOGIT_SCALING, LOGIT_SCALE = ctx.logit_scaling, num_warps = 8, ) return ( logits, None, None, None, ) def fast_cross_entropy_loss( logits, labels, logit_softcapping = 0, logit_scaling = 0, n_items = None, ): """ Arguments: logits: (batch, seq_len, vocab_size) labels: (batch, seq_len,) Returns: losses: float """ batch, seq_len, d = logits.shape assert labels.shape == (batch, seq_len) loss = Fast_CrossEntropyLoss.apply( logits.view(batch * seq_len, d), labels.view(-1), logit_softcapping, logit_scaling, ) if n_items is None: n_items = torch.count_nonzero(labels != -100) return loss.sum() / n_items if (Version(torch.__version__) < Version("2.4.0")) and not hasattr( fast_cross_entropy_loss, "__wrapped__" ): fast_cross_entropy_loss = torch._disable_dynamo(fast_cross_entropy_loss) # Patch CE Losses in transformers def patch_loss_functions(torch_compile = True): _patch_loss_functions(fast_cross_entropy_loss, torch_compile = torch_compile)
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/swiglu.py
unsloth/kernels/swiglu.py
# 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 triton import triton.language as tl import torch from .utils import calculate_settings, torch_gpu_device # signed int32 max is 2**31-1 so num_elements cannot exceed 2**31 NUM_INT32_ELEMENTS = 2**31 SAFE_INT32_BUFFER_MULTIPLIER = 4 BLOCK_SIZE = 1024 INT32_SAFETY_BUFFER = NUM_INT32_ELEMENTS - BLOCK_SIZE * SAFE_INT32_BUFFER_MULTIPLIER @triton.jit def _fg_kernel( e, g, h, n_elements, BLOCK_SIZE: tl.constexpr, LONG_INDEXING: tl.constexpr, ): block_idx = tl.program_id(0) if LONG_INDEXING: offsets = block_idx.to(tl.int64) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE).to( tl.int64 ) n_elements = tl.cast(n_elements, tl.int64) else: offsets = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < n_elements e_row = tl.load(e + offsets, mask = mask, other = 0).to(tl.float32) g_row = tl.load(g + offsets, mask = mask, other = 0) # .to(tl.float32) # f = e * sigmoid(e) f_row = e_row * tl.sigmoid(e_row) # e_row / (1 + tl.exp(-e_row)) f_row = f_row.to(g_row.dtype) # Exact copy from HF # h = f * g h_row = f_row * g_row # Store h tl.store(h + offsets, h_row, mask = mask) def swiglu_fg_kernel(e, g): batch, seq_len, hd = e.shape n_elements = e.numel() h = torch.empty((batch, seq_len, hd), dtype = e.dtype, device = e.device) grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) with torch_gpu_device(e.device): _fg_kernel[grid]( e, g, h, n_elements, BLOCK_SIZE = BLOCK_SIZE, LONG_INDEXING = 0 if n_elements <= INT32_SAFETY_BUFFER else 1, ) return h @triton.jit def _DWf_DW_dfg_kernel( DW, e, g, n_elements, BLOCK_SIZE: tl.constexpr, LONG_INDEXING: tl.constexpr, ): """ e = e.float() se = 1.0 / (1.0 + torch.exp(-e)) f = (se * e).to(dtype) h = f * g df = DW * f dg = DW * g de = (dg.float() * se * (1.0 + e * (1.0 - se))).to(dtype) """ block_idx = tl.program_id(0) if LONG_INDEXING: offsets = block_idx.to(tl.int64) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE).to( tl.int64 ) n_elements = tl.cast(n_elements, tl.int64) else: offsets = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < n_elements DW_row = tl.load(DW + offsets, mask = mask, other = 0) # .to(tl.float32) e_row = tl.load(e + offsets, mask = mask, other = 0).to(tl.float32) g_row = tl.load(g + offsets, mask = mask, other = 0) # .to(tl.float32) # e = e.float() # se = 1.0 / (1.0 + torch.exp(-e)) se_row = tl.sigmoid(e_row) # 1.0 / (1.0 + tl.exp(-e_row)) # f = (se * e).to(dtype) f_row = se_row * e_row f_row = f_row.to(DW_row.dtype) # h = f * g h_row = f_row * g_row # df = DW * f df_row = DW_row * f_row # dg = DW * g dg_row = DW_row * g_row # de = (dg.float() * se * (1.0 + e * (1.0 - se))).to(dtype) de_row = dg_row.to(tl.float32) * se_row * (1.0 + e_row * (1.0 - se_row)) de_row = de_row.to(DW_row.dtype) # Store derivatives in buffers tl.store(DW + offsets, h_row, mask = mask) # h = f * g tl.store(e + offsets, df_row, mask = mask) # df = DW * f tl.store(g + offsets, de_row, mask = mask) # de def swiglu_DWf_DW_dfg_kernel(DW, e, g): batch_seq_len, hd = e.shape n_elements = e.numel() grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) with torch_gpu_device(e.device): _DWf_DW_dfg_kernel[grid]( DW, e, g, n_elements, BLOCK_SIZE = BLOCK_SIZE, LONG_INDEXING = 0 if n_elements <= INT32_SAFETY_BUFFER else 1, ) return DW, e, g
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/rms_layernorm.py
unsloth/kernels/rms_layernorm.py
# 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 triton import triton.language as tl import torch from .utils import calculate_settings, torch_gpu_device @triton.jit def _rms_layernorm_forward( Y, Y_row_stride: tl.constexpr, X, X_row_stride: tl.constexpr, W, W_row_stride: tl.constexpr, r, r_row_stride: tl.constexpr, n_cols: tl.constexpr, eps: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): """ Fast RMS Layernorm kernel Inspiration from a Triton tutorial: https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html """ row_idx = tl.program_id(0) col_offsets = tl.arange(0, BLOCK_SIZE) mask = col_offsets < n_cols Y += row_idx * Y_row_stride X += row_idx * X_row_stride r += row_idx * r_row_stride X_row = tl.load(X + col_offsets, mask = mask, other = 0).to(tl.float32) W_row = tl.load(W + col_offsets, mask = mask, other = 0) # .to(tl.float32) row_var = tl.sum(X_row * X_row, axis = 0) / n_cols inv_var = tl.math.rsqrt(row_var + eps) tl.store(r, inv_var) normed = X_row * inv_var normed = normed.to(W_row.dtype) # Exact copy from HF output = normed * W_row tl.store(Y + col_offsets, output, mask = mask) def _rms_layernorm_backward( dY, dY_row_stride: tl.constexpr, dX, dX_row_stride: tl.constexpr, X, X_row_stride: tl.constexpr, W, W_row_stride: tl.constexpr, r, r_row_stride: tl.constexpr, # dW, dW_row_stride, n_cols: tl.constexpr, eps: tl.constexpr, GEMMA: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): """ Fast RMS Layernorm kernel for the backward pass Inspiration from a Triton tutorial: https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html """ row_idx = tl.program_id(0) col_offsets = tl.arange(0, BLOCK_SIZE) mask = col_offsets < n_cols dY += row_idx * dY_row_stride X += row_idx * X_row_stride r += row_idx * r_row_stride if GEMMA: dX += row_idx * dY_row_stride else: dX = dY dY_row = tl.load(dY + col_offsets, mask = mask, other = 0).to(tl.float32) X_row = tl.load(X + col_offsets, mask = mask, other = 0).to(tl.float32) W_row = tl.load(W + col_offsets, mask = mask, other = 0).to(tl.float32) # Get saved row variance inv_var = tl.load(r).to(tl.float32) normed = X_row * inv_var if GEMMA: dY_W = dY_row * (W_row + 1.0) else: dY_W = dY_row * W_row rowsum_dY_normed = tl.sum(dY_W * normed, axis = 0) output = inv_var / n_cols * (n_cols * dY_W - normed * rowsum_dY_normed) tl.store(dX + col_offsets, output, mask = mask) _rms_layernorm_backward = triton.jit(_rms_layernorm_backward) _rms_layernorm_backward = triton.heuristics( { "GEMMA": lambda args: bool(args["GEMMA"]), } )(_rms_layernorm_backward) @triton.jit def _gemma_rms_layernorm_forward( Y, Y_row_stride: tl.constexpr, X, X_row_stride: tl.constexpr, W, W_row_stride: tl.constexpr, r, r_row_stride: tl.constexpr, n_cols: tl.constexpr, eps: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): # Copies https://github.com/google-deepmind/gemma/blob/main/gemma/layers.py#L31 # and https://github.com/keras-team/keras-nlp/blob/v0.8.2/keras_nlp/models/gemma/rms_normalization.py#L33 # exactly. Essentially all in float32! row_idx = tl.program_id(0) col_offsets = tl.arange(0, BLOCK_SIZE) mask = col_offsets < n_cols Y += row_idx * Y_row_stride X += row_idx * X_row_stride r += row_idx * r_row_stride X_row = tl.load(X + col_offsets, mask = mask, other = 0).to(tl.float32) W_row = tl.load(W + col_offsets, mask = mask, other = 0).to(tl.float32) row_var = tl.sum(X_row * X_row, axis = 0) / n_cols inv_var = tl.math.rsqrt(row_var + eps) tl.store(r, inv_var) normed = X_row * inv_var output = normed * (W_row + 1.0) tl.store(Y + col_offsets, output, mask = mask) class Fast_RMS_Layernorm(torch.autograd.Function): @staticmethod def forward(ctx, X: torch.Tensor, W: torch.Tensor, eps: float, gemma: bool = False): shape = X.shape dim: int = shape[-1] X = X.reshape(-1, dim) n_rows: int n_cols: int n_rows, n_cols = X.shape BLOCK_SIZE: int num_warps: int BLOCK_SIZE, num_warps = calculate_settings(n_cols) device = X.device Y = torch.empty((n_rows, n_cols), dtype = X.dtype, device = device) r = torch.empty(n_rows, dtype = torch.float32, device = device) fx = _gemma_rms_layernorm_forward if gemma else _rms_layernorm_forward with torch_gpu_device(device): fx[(n_rows,)]( Y, Y.stride(0), X, X.stride(0), W, W.stride(0), r, r.stride(0), n_cols, eps, BLOCK_SIZE = BLOCK_SIZE, num_warps = num_warps, ) ctx.eps = eps ctx.BLOCK_SIZE = BLOCK_SIZE ctx.num_warps = num_warps ctx.GEMMA = gemma ctx.save_for_backward(X, W, r) return Y.view(*shape) @staticmethod def backward(ctx, dY: torch.Tensor): shape = dY.shape dim: int = shape[-1] dY = dY.reshape(-1, dim) X, W, r = ctx.saved_tensors n_rows: int n_cols: int n_rows, n_cols = dY.shape # dW = X dX = torch.empty_like(dY) if ctx.GEMMA else dY with torch_gpu_device(dY.device): _rms_layernorm_backward[(n_rows,)]( dY, dY.stride(0), dX, dX.stride(0), X, X.stride(0), W, W.stride(0), r, r.stride(0), # dW, dW.stride(0), n_cols, ctx.eps, GEMMA = ctx.GEMMA, BLOCK_SIZE = ctx.BLOCK_SIZE, num_warps = ctx.num_warps, ) dX = dX.view(*shape) return dX, None, None, None # [TODO] Unsure why RMS Layernorm is not torch.compiling properly @torch.compiler.disable def fast_rms_layernorm(layernorm, X: torch.Tensor, gemma: bool = False): W: torch.Tensor = layernorm.weight eps: float = ( layernorm.variance_epsilon if hasattr(layernorm, "variance_epsilon") else layernorm.eps ) out = Fast_RMS_Layernorm.apply(X, W, eps, gemma) return out from transformers.models.llama.modeling_llama import LlamaRMSNorm class Unsloth_LlamaRMSNorm(LlamaRMSNorm): def forward(self, X): return fast_rms_layernorm(self, X, gemma = False) try: from transformers.models.mllama.modeling_mllama import MllamaTextRMSNorm class Unsloth_MllamaTextRMSNorm(MllamaTextRMSNorm): def forward(self, X): return fast_rms_layernorm(self, X, gemma = False) except: pass def patch_rms_layernorm(): import transformers.models.llama.modeling_llama transformers.models.llama.modeling_llama.LlamaRMSNorm = Unsloth_LlamaRMSNorm try: import transformers.models.mllama.modeling_mllama transformers.models.mllama.modeling_mllama.MllamaTextRMSNorm = ( Unsloth_MllamaTextRMSNorm ) except: pass return def unpatch_rms_layernorm(): import transformers.models.llama.modeling_llama transformers.models.llama.modeling_llama.LlamaRMSNorm = LlamaRMSNorm try: import transformers.models.mllama.modeling_mllama transformers.models.mllama.modeling_mllama.MllamaTextRMSNorm = MllamaTextRMSNorm except: pass return def test_rms_layernorm( dim = 1024, eps = 1e-5, dtype = torch.float16, bsz = 21, random_state = 3407, seqlen = 3341, ): from transformers.models.llama.modeling_llama import LlamaRMSNorm layernorm = LlamaRMSNorm((dim,), eps = eps).to("cuda") torch.cuda.manual_seed(random_state) torch.manual_seed(random_state) torch.nn.init.uniform_(layernorm.weight) X = torch.randn((bsz, seqlen, dim), dtype = dtype, device = "cuda") XX = X.clone() X.requires_grad_(True) XX.requires_grad_(True) Y = layernorm(X) YY = torch.randn((bsz, seqlen, dim), dtype = dtype, device = "cuda", requires_grad = True) Y.backward(YY) correct_grad = X.grad.clone() # from unsloth.kernels import fast_rms_layernorm Y = fast_rms_layernorm(layernorm, XX) Y.backward(YY) assert torch.amax(correct_grad - XX.grad).item() <= 0.05 def testing_suite_layernorm(): for dim in [512, 1024, 2048]: for dtype in [torch.float16, torch.bfloat16]: with torch.autocast(device_type = "cuda", dtype = dtype): for seqlen in [3341, 2048, 349]: for random_state in [3407, 42]: test_rms_layernorm( dim = dim, eps = 1e-5, dtype = dtype, bsz = 21, random_state = random_state, seqlen = seqlen, )
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/rope_embedding.py
unsloth/kernels/rope_embedding.py
# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import triton import triton.language as tl import torch from ..device_type import DEVICE_COUNT from .utils import calculate_settings, torch_gpu_device, torch_device_stream def _rope_embedding_QK( Q, Q_batch_stride, Q_head_stride, Q_seq_stride, K, K_batch_stride, K_head_stride, K_seq_stride, cos, cos_row_stride, sin, sin_row_stride, rope_embedding_indices, seqlen, head_dim: tl.constexpr, n_heads_K: tl.constexpr, BACKWARD_PASS: tl.constexpr, HAS_ROPE_INDICES: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): row_position = tl.program_id(0) head_position = tl.program_id(1) col_offsets = tl.arange(0, BLOCK_SIZE) half_head_dim = head_dim // 2 mask = col_offsets < half_head_dim if HAS_ROPE_INDICES: rot_position = tl.load( rope_embedding_indices + row_position, eviction_policy = "evict_first", ).to(tl.int32) else: rot_position = row_position % seqlen cos_ptr = cos + rot_position * cos_row_stride sin_ptr = sin + rot_position * sin_row_stride sin1 = tl.load( sin_ptr + col_offsets, mask = mask, other = 0, ) cos1 = tl.load( cos_ptr + col_offsets, mask = mask, other = 0, ) if BACKWARD_PASS: sin1 = -sin1 batch_id = row_position // seqlen seq_index = row_position - batch_id * seqlen q_ptr = ( Q + batch_id * Q_batch_stride + head_position * Q_head_stride + seq_index * Q_seq_stride ) q0 = tl.load(q_ptr + col_offsets, mask = mask, other = 0) q1 = tl.load(q_ptr + half_head_dim + col_offsets, mask = mask, other = 0) tl.store(q_ptr + col_offsets, q0 * cos1 - q1 * sin1, mask = mask) tl.store(q_ptr + half_head_dim + col_offsets, q1 * cos1 + q0 * sin1, mask = mask) if head_position < n_heads_K: k_ptr = ( K + batch_id * K_batch_stride + head_position * K_head_stride + seq_index * K_seq_stride ) k0 = tl.load(k_ptr + col_offsets, mask = mask, other = 0) k1 = tl.load(k_ptr + half_head_dim + col_offsets, mask = mask, other = 0) tl.store(k_ptr + col_offsets, k0 * cos1 - k1 * sin1, mask = mask) tl.store(k_ptr + half_head_dim + col_offsets, k1 * cos1 + k0 * sin1, mask = mask) _rope_embedding_QK = triton.jit(_rope_embedding_QK) _rope_embedding_QK = triton.heuristics( { "BACKWARD_PASS": lambda args: bool(args["BACKWARD_PASS"]), "HAS_ROPE_INDICES": lambda args: bool(args["HAS_ROPE_INDICES"]), } )(_rope_embedding_QK) ROPE_GROUP_SIZE: int = 4 def _rope_embedding( Q, Q_row_stride: tl.constexpr, cos, cos_row_stride: tl.constexpr, sin, sin_row_stride: tl.constexpr, seqlen, head_dim: tl.constexpr, n_heads: tl.constexpr, BACKWARD_PASS: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): """ Calculates the RoPE Embedding quickly RoPE is Q * cos + rotate_half(Q) * sin See our blog post for more info """ ROPE_GROUP_SIZE = 4 row_position = tl.program_id(0) group_head_position = tl.program_id(1) col_offsets = tl.arange(0, BLOCK_SIZE) half_head_dim = head_dim // 2 mask = col_offsets < half_head_dim sin1 = tl.load( sin + (row_position % seqlen) * sin_row_stride + half_head_dim * 0 + col_offsets, mask = mask, other = 0, ) cos1 = tl.load( cos + (row_position % seqlen) * cos_row_stride + half_head_dim * 0 + col_offsets, mask = mask, other = 0, ) if BACKWARD_PASS: # See our blog post for more info. sin1 = -sin1 # [TODO] Autotune ROPE_GROUP_SIZE to be 1, 2, 4, 8 head_start = group_head_position * ROPE_GROUP_SIZE head_end = min((head_start + ROPE_GROUP_SIZE), n_heads) # 10% Faster kernel from [HuyNguyen-hust](https://github.com/unslothai/unsloth/pull/238) for k in range(head_start, head_end): offs_q1 = row_position * Q_row_stride + k * head_dim + col_offsets offs_q2 = ( row_position * Q_row_stride + k * head_dim + col_offsets + half_head_dim ) # For Gemma - sometimes RoPE must be done in float32 and not bfloat16 Q1 = tl.load(Q + offs_q1, mask = mask, other = 0).to(sin1.dtype) Q2 = tl.load(Q + offs_q2, mask = mask, other = 0).to(sin1.dtype) tl.store(Q + offs_q1, Q1 * cos1 - Q2 * sin1, mask = mask) tl.store(Q + offs_q2, Q2 * cos1 + Q1 * sin1, mask = mask) _rope_embedding = triton.jit(_rope_embedding) _rope_embedding = triton.heuristics( { "BACKWARD_PASS": lambda args: bool(args["BACKWARD_PASS"]), } )(_rope_embedding) class Fast_RoPE_Embedding(torch.autograd.Function): @staticmethod def forward(ctx, Q, cos, sin): cos, sin = cos.squeeze(), sin.squeeze() batch: int seq_len: int n_heads: int head_dim: int batch, seq_len, n_heads, head_dim = Q.shape Q = Q.reshape(batch * seq_len, n_heads * head_dim) n_rows: int n_cols: int n_rows, n_cols = Q.shape assert seq_len <= cos.shape[0] # [TODO] Changing blocksize to head_dim//2 seems to have # some concurrency / un-deterministic issues. BLOCK_SIZE, num_warps = calculate_settings(head_dim // 2) # (head_dim//2) # group_size = 4 # 4 or 8, too large group_size can hurt performance. div: int mod: int div, mod = divmod(n_heads, ROPE_GROUP_SIZE) n_groups: int = div + (mod != 0) with torch_gpu_device(Q.device): _rope_embedding[ ( n_rows, n_groups, ) ]( Q, Q.stride(0), cos, cos.stride(0), sin, sin.stride(0), seq_len, head_dim, n_heads, BACKWARD_PASS = False, BLOCK_SIZE = BLOCK_SIZE, num_warps = num_warps, ) ctx.BLOCK_SIZE = BLOCK_SIZE ctx.num_warps = num_warps ctx.n_groups = n_groups ctx.cos = cos ctx.sin = sin return Q.reshape(batch, seq_len, n_heads, head_dim) @staticmethod def backward(ctx, dY): batch: int seq_len: int n_heads: int head_dim: int batch, seq_len, n_heads, head_dim = dY.shape dY = dY.reshape(batch * seq_len, n_heads * head_dim) n_rows: int n_cols: int n_rows, n_cols = dY.shape cos = ctx.cos sin = ctx.sin with torch_gpu_device(dY.device): _rope_embedding[ ( n_rows, ctx.n_groups, ) ]( dY, dY.stride(0), cos, cos.stride(0), sin, sin.stride(0), seq_len, head_dim, n_heads, BACKWARD_PASS = True, BLOCK_SIZE = ctx.BLOCK_SIZE, num_warps = ctx.num_warps, ) dY = dY.reshape(batch, seq_len, n_heads, head_dim) return ( dY, None, None, ) # [TODO] Unsure why RoPE Embedding is not torch.compiling properly @torch.compiler.disable def fast_rope_embedding( Q, K, cos, sin, rope_embedding_indices = None, ): if rope_embedding_indices is not None: Q_out, K_out = Fast_RoPE_Embedding_QK.apply( Q, K, cos, sin, rope_embedding_indices ) else: Q_out = Fast_RoPE_Embedding.apply( Q.transpose(1, 2).contiguous(), cos, sin ).transpose(1, 2) K_out = Fast_RoPE_Embedding.apply( K.transpose(1, 2).contiguous(), cos, sin ).transpose(1, 2) if DEVICE_COUNT > 1: torch_device_stream(Q.device).synchronize() return Q_out, K_out class Fast_RoPE_Embedding_QK(torch.autograd.Function): @staticmethod def forward(ctx, Q, K, cos, sin, rope_indices): has_indices = rope_indices is not None cos, sin = cos.squeeze(), sin.squeeze() batch, n_heads_Q, seq_len, head_dim = Q.shape _, n_heads_K, _, _ = K.shape # Inplace rotary embedding is generally fine Q_out = Q.clone() if not Q.is_contiguous() else Q K_out = K.clone() if not K.is_contiguous() else K if has_indices: # TRL's rotary indices are always in int32, so casting is just for safety rope_ptr = rope_indices.reshape(-1).to(dtype = torch.int32, device = Q.device) else: rope_ptr = cos.new_empty(1, dtype = torch.int32) BLOCK_SIZE, num_warps = calculate_settings(head_dim) Q_batch_stride, Q_head_stride, Q_seq_stride = ( Q_out.stride(0), Q_out.stride(1), Q_out.stride(2), ) K_batch_stride, K_head_stride, K_seq_stride = ( K_out.stride(0), K_out.stride(1), K_out.stride(2), ) with torch_gpu_device(Q.device): _rope_embedding_QK[(batch * seq_len, n_heads_Q)]( Q_out, Q_batch_stride, Q_head_stride, Q_seq_stride, K_out, K_batch_stride, K_head_stride, K_seq_stride, cos, cos.stride(0), sin, sin.stride(0), rope_ptr, seq_len, head_dim = head_dim, n_heads_K = n_heads_K, BACKWARD_PASS = False, HAS_ROPE_INDICES = has_indices, BLOCK_SIZE = BLOCK_SIZE, num_warps = num_warps, ) ctx.block_size = BLOCK_SIZE ctx.num_warps = num_warps ctx.has_indices = has_indices ctx.cos = cos ctx.sin = sin ctx.rope_indices = rope_ptr if has_indices else None ctx.seq_len = seq_len ctx.n_heads_Q = n_heads_Q ctx.n_heads_K = n_heads_K return ( Q_out, K_out, ) @staticmethod def backward(ctx, dQ, dK): batch, _, _, head_dim = dQ.shape rope_ptr = ( ctx.rope_indices if ctx.has_indices else ctx.cos.new_empty(1, dtype = torch.int32) ) # Inplace rotary embedding is generally fine dQ_out = dQ.clone() if not dQ.is_contiguous() else dQ dK_out = dK.clone() if not dK.is_contiguous() else dK Q_batch_stride, Q_head_stride, Q_seq_stride = ( dQ_out.stride(0), dQ_out.stride(1), dQ_out.stride(2), ) K_batch_stride, K_head_stride, K_seq_stride = ( dK_out.stride(0), dK_out.stride(1), dK_out.stride(2), ) with torch_gpu_device(dQ.device): _rope_embedding_QK[(batch * ctx.seq_len, ctx.n_heads_Q)]( dQ_out, Q_batch_stride, Q_head_stride, Q_seq_stride, dK_out, K_batch_stride, K_head_stride, K_seq_stride, ctx.cos, ctx.cos.stride(0), ctx.sin, ctx.sin.stride(0), rope_ptr, ctx.seq_len, head_dim = head_dim, n_heads_K = ctx.n_heads_K, BACKWARD_PASS = True, HAS_ROPE_INDICES = ctx.has_indices, BLOCK_SIZE = ctx.block_size, num_warps = ctx.num_warps, ) return (dQ_out, dK_out, None, None, None) class Slow_RoPE_Embedding(torch.autograd.Function): @staticmethod def forward(ctx, Q, cos, sin, position_ids): if position_ids is not None: # The first two dimensions of cos and sin are always 1, so we can `squeeze` them. cos = cos.squeeze(1).squeeze(0) # [seq_len, dim] sin = sin.squeeze(1).squeeze(0) # [seq_len, dim] cos = cos[position_ids].unsqueeze(2) # [bs, seq_len, 1, dim] sin = sin[position_ids].unsqueeze(2) # [bs, seq_len, 1, dim] # Q * cos + rotate_half(Q) * sin half = Q.shape[-1] // 2 RH_Q = torch.cat((-Q[..., half:], Q[..., :half]), dim = -1) Q *= cos Q.addcmul_(RH_Q, sin) # RH_Q *= sin # Q += RH_Q ctx.save_for_backward(cos, sin) return Q @staticmethod def backward(ctx, dY): cos, sin = ctx.saved_tensors # Q * cos + rotate_half.T(Q) * sin half = dY.shape[-1] // 2 RH_dY = torch.cat((dY[..., half:], -dY[..., :half]), dim = -1) dY *= cos dY.addcmul_(RH_dY, sin) # RH_dY *= sin # dY += RH_dY return dY, None, None, None def inplace_rope_embedding(Q, K, cos, sin, position_ids): Q = Slow_RoPE_Embedding.apply(Q, cos, sin, position_ids) K = Slow_RoPE_Embedding.apply(K, cos, sin, position_ids) torch_device_stream(Q.device).synchronize() return Q, K
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/fast_lora.py
unsloth/kernels/fast_lora.py
# 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 torch from .utils import ( _maybe_fake_quantize_activations, fast_dequantize, QUANT_STATE, get_lora_parameters, get_lora_parameters_bias, matmul_lora, torch_amp_custom_fwd, torch_amp_custom_bwd, ) class LoRA_MLP(torch.autograd.Function): """ ### LoRA weights G = G + Ag @ Bg U = U + Au @ Bu W = W + Aw @ Bw ### SwiGLU(X) e = X @ G f = e * sigmoid(e) g = X @ U h = f * g i = h @ W ### Backpropagation chain rule See our blog post for more details df = sigmoid(e) * (1 - f) + f dC/dW = h.T @ dY dC/dU = X.T @ (D @ W.T * f) dC/dG = X.T @ (D @ W.T * df * g) ### Down projection LoRA weights dC/dAw = dC/dW @ B.T dC/dBw = A.T @ dC/dW dC/dAw = h.T @ dY @ B.T dC/dBw = A.T @ h.T @ dY ### Up projection LoRA weights dC/dAu = X.T @ (D @ W.T * f) @ B.T dC/dBu = A.T @ X.T @ (D @ W.T * f) ### Gate projection LoRA weights dC/dAg = X.T @ (D @ W.T * df * g) @ B.T dC/dBg = A.T @ X.T @ (D @ W.T * df * g) Don't forget to see our blog post for more details! """ @staticmethod @torch_amp_custom_fwd def forward( ctx, X: torch.Tensor, gateW, gateW_quant, gateA, gateB, gateS, upW, upW_quant, upA, upB, upS, downW, downW_quant, downA, downB, downS, _forward_function, _backward_function, inplace = True, ): dtype = X.dtype e = matmul_lora(X, gateW, gateW_quant, gateA, gateB, gateS) g = matmul_lora(X, upW, upW_quant, upA, upB, upS) h = _forward_function(e, g) i = matmul_lora(h, downW, downW_quant, downA, downB, downS) ctx.custom_saved_tensors = ( gateW, gateW_quant, gateS, upW, upW_quant, upS, downW, downW_quant, downS, _backward_function, ) ctx.save_for_backward(gateA, gateB, upA, upB, downA, downB, X, e, g) ctx.inplace = inplace return i @staticmethod @torch_amp_custom_bwd def backward(ctx, dY: torch.Tensor): ( gateW, gateW_quant, gateS, upW, upW_quant, upS, downW, downW_quant, downS, _backward_function, ) = ctx.custom_saved_tensors gateA, gateB, upA, upB, downA, downB, X, e, g = ctx.saved_tensors batch, seq_len, hd = X.shape dY = dY.view(-1, dY.shape[-1]) X = X.view(-1, X.shape[-1]) e = e.view(-1, e.shape[-1]) g = g.view(-1, g.shape[-1]) dtype = X.dtype gateA, gateB, upA, upB, downA, downB = ( gateA.to(dtype), gateB.to(dtype), upA.to(dtype), upB.to(dtype), downA.to(dtype), downB.to(dtype), ) gateA, gateB, upA, upB, downA, downB = ( gateA.t(), gateB.t(), upA.t(), upB.t(), downA.t(), downB.t(), ) DW = matmul_lora(dY, downW.t(), downW_quant, downB, downA, downS) DW, e, g = _backward_function(DW, e, g) h, df, de = DW, e, g d_downA = torch.empty_like(downA) d_downB = torch.empty_like(downB) d_gateA = torch.empty_like(gateA) d_gateB = torch.empty_like(gateB) d_upA = torch.empty_like(upA) d_upB = torch.empty_like(upB) # Down projection LoRA weights # d_downA = h.t() @ (dY @ downB.t()) # d_downB = (downA.t() @ h.t()) @ dY # d_downA *= downS # d_downB *= downS d_downA.addmm_(h.t(), dY @ downB.t(), alpha = downS, beta = 0) d_downB.addmm_(downA.t() @ h.t(), dY, alpha = downS, beta = 0) # Up projection LoRA weights # d_upA = X.t() @ (df @ upB.t()) # d_upB = (upA.t() @ X.t()) @ df # d_upA *= upS # d_upB *= upS d_upA.addmm_(X.t(), df @ upB.t(), alpha = upS, beta = 0) d_upB.addmm_(upA.t() @ X.t(), df, alpha = upS, beta = 0) # Gate projection LoRA weights # d_gateA = X.t() @ (de @ gateB.t()) # d_gateB = (gateA.t() @ X.t()) @ de # d_gateA *= gateS # d_gateB *= gateS d_gateA.addmm_(X.t(), de @ gateB.t(), alpha = gateS, beta = 0) d_gateB.addmm_(gateA.t() @ X.t(), de, alpha = gateS, beta = 0) # dX = matmul_lora(df, upW.t(), upW_quant, upB, upA, upS) # dX += matmul_lora(de, gateW.t(), gateW_quant, gateB, gateA, gateS) upW = fast_dequantize(upW.t(), upW_quant) dX = torch.matmul(df, upW.t(), out = X if ctx.inplace else None) del upW # dX += df @ upB.to(dtype).t() @ (upS * upA.to(dtype).t()) dX.addmm_(df @ upB.t(), upA.t(), alpha = upS) gateW = fast_dequantize(gateW.t(), gateW_quant) # dX += de @ gateW.t() dX.addmm_(de, gateW.t()) del gateW # dX += de @ gateB.to(dtype).t() @ (gateS * gateA.to(dtype).t()) dX.addmm_(de @ gateB.t(), gateA.t(), alpha = gateS) # gateW, gateW_quant, gateA, gateB, gateS, # upW, upW_quant, upA, upB, upS, # downW, downW_quant, downA, downB, downS, return ( dX.view(batch, seq_len, hd), None, None, d_gateA.t(), d_gateB.t(), None, None, None, d_upA.t(), d_upB.t(), None, None, None, d_downA.t(), d_downB.t(), None, None, None, None, ) # _backward and _forward and inplace from .swiglu import swiglu_fg_kernel, swiglu_DWf_DW_dfg_kernel def apply_lora_mlp_swiglu(self, X, inplace = True): X = _maybe_fake_quantize_activations(X, self.gate_proj) gateW, gateW_quant, gateA, gateB, gateS = get_lora_parameters(self.gate_proj) upW, upW_quant, upA, upB, upS = get_lora_parameters(self.up_proj) downW, downW_quant, downA, downB, downS = get_lora_parameters(self.down_proj) out = LoRA_MLP.apply( X, gateW, gateW_quant, gateA, gateB, gateS, upW, upW_quant, upA, upB, upS, downW, downW_quant, downA, downB, downS, swiglu_fg_kernel, swiglu_DWf_DW_dfg_kernel, inplace, ) return out from .geglu import geglu_exact_forward_kernel, geglu_exact_backward_kernel def apply_lora_mlp_geglu_exact(self, X, inplace = True): X = _maybe_fake_quantize_activations(X, self.gate_proj) gateW, gateW_quant, gateA, gateB, gateS = get_lora_parameters(self.gate_proj) upW, upW_quant, upA, upB, upS = get_lora_parameters(self.up_proj) downW, downW_quant, downA, downB, downS = get_lora_parameters(self.down_proj) out = LoRA_MLP.apply( X, gateW, gateW_quant, gateA, gateB, gateS, upW, upW_quant, upA, upB, upS, downW, downW_quant, downA, downB, downS, geglu_exact_forward_kernel, geglu_exact_backward_kernel, inplace, ) return out from .geglu import geglu_approx_forward_kernel, geglu_approx_backward_kernel def apply_lora_mlp_geglu_approx(self, X): X = _maybe_fake_quantize_activations(X, self.gate_proj) gateW, gateW_quant, gateA, gateB, gateS = get_lora_parameters(self.gate_proj) upW, upW_quant, upA, upB, upS = get_lora_parameters(self.up_proj) downW, downW_quant, downA, downB, downS = get_lora_parameters(self.down_proj) out = LoRA_MLP.apply( X, gateW, gateW_quant, gateA, gateB, gateS, upW, upW_quant, upA, upB, upS, downW, downW_quant, downA, downB, downS, geglu_approx_forward_kernel, geglu_approx_backward_kernel, ) return out class LoRA_QKV(torch.autograd.Function): """ ### LoRA weights Wq = Wq + Aq @ Bq Wk = Wk + Ak @ Bk Wv = Wv + Av @ Bv Q = X @ Wq = X @ Wq + X @ Aq @ Bq K = X @ Wk = X @ Wk + X @ Ak @ Bk V = X @ Wv = X @ Wv + X @ Av @ Bv ### Backpropagation chain rule See our blogpost for more details. dC/dWq = X.T @ D(Wq) dC/dWk = X.T @ D(Wk) dC/dWv = X.T @ D(Wv) We then sum them all find dC/dX ### Q projection LoRA weights dC/dAq = X.T @ D(Wq) @ B.T dC/dBq = A.T @ X.T @ D(Wq) ### K projection LoRA weights dC/dAk = X.T @ D(Wk) @ B.T dC/dBk = A.T @ X.T @ D(Wk) ### V projection LoRA weights dC/dAv = X.T @ D(Wv) @ B.T dC/dBv = A.T @ X.T @ D(Wv) """ @staticmethod @torch_amp_custom_fwd def forward( ctx, X: torch.Tensor, QW, QW_quant, QA, QB, QS, KW, KW_quant, KA, KB, KS, VW, VW_quant, VA, VB, VS, inplace = True, ): dtype = X.dtype # bitsandbytes 8-bit matmul expects 2D inputs. # TorchInductor/AOTAutograd fails on 3D tensors during backward, # so we explicitly flatten the sequence dimension. orig_shape = X.shape X_for_matmul = X if X.dim() == 3: X_for_matmul = X.view(-1, X.shape[-1]) Q = matmul_lora(X_for_matmul, QW, QW_quant, QA, QB, QS) K = matmul_lora(X_for_matmul, KW, KW_quant, KA, KB, KS) V = matmul_lora(X_for_matmul, VW, VW_quant, VA, VB, VS) # Restore original shape after matmul if len(orig_shape) == 3: Q = Q.view(orig_shape[0], orig_shape[1], -1) K = K.view(orig_shape[0], orig_shape[1], -1) V = V.view(orig_shape[0], orig_shape[1], -1) ctx.custom_saved_tensors = ( QW, QW_quant, QS, KW, KW_quant, KS, VW, VW_quant, VS, ) ctx.save_for_backward( X, QA, QB, KA, KB, VA, VB, ) ctx.inplace = inplace return Q, K, V @staticmethod @torch_amp_custom_bwd def backward(ctx, dQ, dK, dV): QW, QW_quant, QS, KW, KW_quant, KS, VW, VW_quant, VS = ctx.custom_saved_tensors ( X, QA, QB, KA, KB, VA, VB, ) = ctx.saved_tensors batch, seq_len, hd = X.shape dQ = dQ.view(-1, dQ.shape[-1]) dK = dK.reshape(-1, dK.shape[-1]) # view doesn't work on K.T dV = dV.view(-1, dV.shape[-1]) X = X.view(-1, X.shape[-1]) dtype = X.dtype QA, QB, KA, KB, VA, VB = ( QA.to(dtype), QB.to(dtype), KA.to(dtype), KB.to(dtype), VA.to(dtype), VB.to(dtype), ) QA, QB, KA, KB, VA, VB = QA.t(), QB.t(), KA.t(), KB.t(), VA.t(), VB.t() ### Weight projection LoRA weights # See our blogpost for more details. d_QA = torch.empty_like(QA) d_QB = torch.empty_like(QB) d_KA = torch.empty_like(KA) d_KB = torch.empty_like(KB) d_VA = torch.empty_like(VA) d_VB = torch.empty_like(VB) # Q Projection # d_QA = X.t() @ (dQ @ QB.t()) # d_QB = (QA.t() @ X.t()) @ dQ # d_QA *= QS # d_QB *= QS d_QA.addmm_(X.t(), dQ @ QB.t(), alpha = QS, beta = 0) d_QB.addmm_(QA.t() @ X.t(), dQ, alpha = QS, beta = 0) # K Projection # d_KA = X.t() @ (dK @ KB.t()) # d_KB = (KA.t() @ X.t()) @ dK # d_KA *= KS # d_KB *= KS d_KA.addmm_(X.t(), dK @ KB.t(), alpha = KS, beta = 0) d_KB.addmm_(KA.t() @ X.t(), dK, alpha = KS, beta = 0) # V Projection # d_VA = X.t() @ (dV @ VB.t()) # d_VB = (VA.t() @ X.t()) @ dV # d_VA *= VS # d_VB *= VS d_VA.addmm_(X.t(), dV @ VB.t(), alpha = VS, beta = 0) d_VB.addmm_(VA.t() @ X.t(), dV, alpha = VS, beta = 0) # Combine derivatives to find dX # dQ QW = fast_dequantize(QW.t(), QW_quant) dX = torch.matmul(dQ, QW.t(), out = X if ctx.inplace else None) del QW # dX += (dQ @ QB.to(dtype).t() @ (QS * QA.to(dtype).t())) dX.addmm_(dQ @ QB.t(), QA.t(), alpha = QS) # dK KW = fast_dequantize(KW.t(), KW_quant) # dX += dK @ KW.t() dX.addmm_(dK, KW.t()) del KW # dX += dK @ KB.to(dtype).t() @ (KS * KA.to(dtype).t()) dX.addmm_(dK @ KB.t(), KA.t(), alpha = KS) # dV VW = fast_dequantize(VW.t(), VW_quant) # dX += dV @ VW.t() dX.addmm_(dV, VW.t()) del VW # dX += dV @ VB.to(dtype).t() @ (VS * VA.to(dtype).t()) dX.addmm_(dV @ VB.t(), VA.t(), alpha = VS) # QW, QW_quant, QA, QB, QS, # KW, KW_quant, KA, KB, KS, # VW, VW_quant, VA, VB, VS, return ( dX.view(batch, seq_len, hd), None, None, d_QA.t(), d_QB.t(), None, None, None, d_KA.t(), d_KB.t(), None, None, None, d_VA.t(), d_VB.t(), None, None, ) def apply_lora_qkv(self, X, inplace = True): X = _maybe_fake_quantize_activations(X, self.q_proj) QW, QW_quant, QA, QB, QS = get_lora_parameters(self.q_proj) KW, KW_quant, KA, KB, KS = get_lora_parameters(self.k_proj) VW, VW_quant, VA, VB, VS = get_lora_parameters(self.v_proj) Q, K, V = LoRA_QKV.apply( X, QW, QW_quant, QA, QB, QS, KW, KW_quant, KA, KB, KS, VW, VW_quant, VA, VB, VS, inplace, ) return Q, K, V class LoRA_W(torch.autograd.Function): """ ### LoRA weights Wq = Wq + Aq @ Bq Wk = Wk + Ak @ Bk Wv = Wv + Av @ Bv Q = X @ Wq = X @ Wq + X @ Aq @ Bq K = X @ Wk = X @ Wk + X @ Ak @ Bk V = X @ Wv = X @ Wv + X @ Av @ Bv ### Backpropagation chain rule dC/dWq = X.T @ D(Wq) dC/dWk = X.T @ D(Wk) dC/dWv = X.T @ D(Wv) ### Q projection LoRA weights dC/dAq = X.T @ D(Wq) @ B.T dC/dBq = A.T @ X.T @ D(Wq) ### K projection LoRA weights dC/dAk = X.T @ D(Wk) @ B.T dC/dBk = A.T @ X.T @ D(Wk) ### V projection LoRA weights dC/dAv = X.T @ D(Wv) @ B.T dC/dBv = A.T @ X.T @ D(Wv) """ @staticmethod @torch_amp_custom_fwd def forward(ctx, X: torch.Tensor, W, W_quant, A, B, S): dtype = X.dtype XW = matmul_lora(X, W, W_quant, A, B, S) ctx.custom_saved_tensors = ( W, W_quant, S, ) ctx.save_for_backward(A, B, X) return XW @staticmethod @torch_amp_custom_bwd def backward(ctx, dY: torch.Tensor): W, W_quant, S = ctx.custom_saved_tensors A, B, X = ctx.saved_tensors batch, seq_len, hd = X.shape dY = dY.reshape(-1, dY.shape[-1]) # Must be reshape X = X.reshape(-1, X.shape[-1]) # Must be reshape dtype = X.dtype A, B = A.to(dtype), B.to(dtype) A, B = A.t(), B.t() d_A = torch.empty_like(A) d_B = torch.empty_like(B) ### Weight projection LoRA weights # Weight projection # d_A = X.t() @ (dY @ B.t()) # d_B = (A.t() @ X.t()) @ dY # d_A *= S # d_B *= S d_A.addmm_(X.t(), dY @ B.t(), alpha = S, beta = 0) d_B.addmm_(A.t() @ X.t(), dY, alpha = S, beta = 0) # Get derivative for dX W = fast_dequantize(W.t(), W_quant) dX = dY @ W.t() del W # dX += dY @ B.to(dtype).t() @ (S * A.to(dtype).t()) dX.addmm_(dY @ B.t(), A.t(), alpha = S) # W, W_quant, A, B, S return dX.view(batch, seq_len, hd), None, None, d_A.t(), d_B.t(), None def apply_lora_o(self, X): X = _maybe_fake_quantize_activations(X, self.o_proj) OW, OW_quant, OA, OB, OS = get_lora_parameters(self.o_proj) O = LoRA_W.apply(X, OW, OW_quant, OA, OB, OS) return O IDENTITY_DROPOUT = torch.nn.Identity @torch._disable_dynamo def fast_lora_forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: raise NotImplementedError( "Unsloth: Currently not supported yet - reshaping done incorrectly" ) self._check_forward_args(x, *args, **kwargs) adapter_names = kwargs.pop("adapter_names", None) if self.disable_adapters: if self.merged: self.unmerge() result = self.base_layer(x, *args, **kwargs) elif adapter_names is not None: result = self._mixed_batch_forward( x, *args, adapter_names = adapter_names, **kwargs ) elif self.merged: result = self.base_layer(x, *args, **kwargs) else: # Fastpath if len(self.active_adapters) == 1: active_adapter = self.active_adapters[0] if active_adapter not in self.lora_A.keys(): return self.base_layer(x, *args, **kwargs) dropout = self.lora_dropout[active_adapter] if ( isinstance(dropout, IDENTITY_DROPOUT) and not self.use_dora[active_adapter] ): lora_A = self.lora_A[active_adapter].weight lora_B = self.lora_B[active_adapter].weight scaling = self.scaling[active_adapter] W = self.base_layer.weight return LoRA_W.apply(x, W, QUANT_STATE(W), lora_A, lora_B, scaling) pass pass result = self.base_layer(x, *args, **kwargs) # As per Tim Dettmers, for 4bit, we need to defensively clone here. # The reason is that in some cases, an error can occur that backprop # does not work on a manipulated view. This issue may be solved with # newer PyTorch versions but this would need extensive testing to be # sure. result = result.clone() for active_adapter in self.active_adapters: if active_adapter not in self.lora_A.keys(): continue lora_A = self.lora_A[active_adapter] lora_B = self.lora_B[active_adapter] dropout = self.lora_dropout[active_adapter] scaling = self.scaling[active_adapter] requires_conversion = not torch.is_autocast_enabled() if requires_conversion: expected_dtype = result.dtype x = x.to(lora_A.weight.dtype) if not self.use_dora[active_adapter]: result = result + lora_B(lora_A(dropout(x))) * scaling else: if isinstance(dropout, torch.nn.Identity) or not self.training: base_result = result else: x = dropout(x) base_result = None result = result + self.lora_magnitude_vector[active_adapter]( x, lora_A = lora_A, lora_B = lora_B, scaling = scaling, base_layer = self.get_base_layer(), base_result = base_result, ) if requires_conversion: result = result.to(expected_dtype) return result
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/flex_attention.py
unsloth/kernels/flex_attention.py
# 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 torch from functools import lru_cache from transformers.models.llama.modeling_llama import logger import os torch_compile_options = { "epilogue_fusion": True, "max_autotune": True, "shape_padding": True, "trace.enabled": os.environ.get("UNSLOTH_COMPILE_DEBUG", "0") == "1", "triton.cudagraphs": False, } # Flex Attention supported from torch 2.5 onwards only try: from torch.nn.attention.flex_attention import ( flex_attention as _flex_attention, create_block_mask as _create_block_mask, ) _flex_attention = torch.compile( _flex_attention, dynamic = True, options = torch_compile_options ) HAS_FLEX_ATTENTION = False except: HAS_FLEX_ATTENTION = False if not HAS_FLEX_ATTENTION: # Logit softcapping @torch.compile(fullgraph = True, dynamic = True, options = torch_compile_options) def slow_attention_softcapping(Q, K, V, causal_mask, self, bsz, q_len): n_heads = self.config.num_attention_heads head_dim = self.head_dim n_kv_heads = self.config.num_key_value_heads n_groups = self.num_key_value_groups # Grouped query attention K = K[:, :, None, :, :].expand(bsz, n_kv_heads, n_groups, q_len, head_dim) V = V[:, :, None, :, :].expand(bsz, n_kv_heads, n_groups, q_len, head_dim) K = K.reshape(bsz, n_heads, q_len, head_dim) V = V.reshape(bsz, n_heads, q_len, head_dim) # See https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e # Gemma 9b should use 256 and not 224 (hs / nah). 27b uses the below # We default to using the config file itself # s = self.config.hidden_size // self.config.num_attention_heads s = self.config.query_pre_attn_scalar t = self.config.attn_logit_softcapping Q = Q * torch.tensor(s**-0.5, dtype = Q.dtype) # Follow Keras exactly A = torch.matmul(Q, K.transpose(2, 3)) A = t * torch.tanh(A / t) # Logit softcapping A += causal_mask[:q_len, :q_len] # Much slower in torch compile! # A.masked_fill_(causal_mask[:q_len, :q_len], -float("inf")) A = torch.nn.functional.softmax(A, dim = -1, dtype = torch.float32).to(Q.dtype) A = torch.matmul(A, V) A = A.transpose(1, 2).contiguous() A = A.reshape(bsz, q_len, n_heads * head_dim) return A create_flex_attention_causal_mask = None create_flex_attention_sliding_window_mask = None else: # See https://github.com/pytorch-labs/attention-gym/blob/main/examples/flex_attn.ipynb # for more examples # BSD 3-Clause License Copyright (c) 2023, Driss Guessous, Horace He et al import functools, math def generate_tanh_softcap(t): def tanh_softcap(x, b, h, q_idx, kv_idx): return t * torch.tanh(x / t) return tanh_softcap def causal_masker(b, h, q_idx, kv_idx): return q_idx >= kv_idx @functools.lru_cache def sliding_window_masker(size = 4096): def sliding_window(b, h, q_idx, kv_idx): causal_mask = q_idx >= kv_idx window_mask = q_idx - kv_idx <= size return causal_mask & window_mask return sliding_window @functools.lru_cache def create_block_mask(mask, n = 128): return _create_block_mask( mask, 1, 1, n, n, BLOCK_SIZE = 128, _compile = True, ) def create_flex_attention_causal_mask(max_seq_length = 8192): causal_mask = create_block_mask(causal_masker, max_seq_length) return causal_mask def create_flex_attention_sliding_window_mask( max_seq_length = 8192, sliding_window = 4096 ): sliding_masker = sliding_window_masker(sliding_window) causal_mask = create_block_mask(sliding_masker, max_seq_length) return causal_mask @functools.lru_cache def flex_attention(s, t): scale = 1.0 / math.sqrt(s) score_mod = generate_tanh_softcap(t) return functools.partial( _flex_attention, score_mod = score_mod, scale = scale, enable_gqa = True, ) def slow_attention_softcapping(Q, K, V, causal_mask, self, bsz, q_len): n_heads = self.config.num_attention_heads head_dim = self.head_dim s = self.config.query_pre_attn_scalar t = self.config.attn_logit_softcapping fx = flex_attention(s, t) A = fx(query = Q, key = K, value = V, block_mask = causal_mask) A = A.transpose(1, 2).contiguous() A = A.reshape(bsz, q_len, n_heads * head_dim) return A torch_matmul = torch.matmul torch_tanh = torch.tanh torch_nn_functional_softmax = torch.nn.functional.softmax def slow_inference_attention_softcapping(Q, K, V, causal_mask, self, bsz, q_len): n_heads = self.config.num_attention_heads head_dim = self.head_dim n_kv_heads = self.config.num_key_value_heads n_groups = self.num_key_value_groups # Grouped query attention K = K[:, :, None, :, :].expand(bsz, n_kv_heads, n_groups, q_len, head_dim) V = V[:, :, None, :, :].expand(bsz, n_kv_heads, n_groups, q_len, head_dim) K = K.reshape(bsz, n_heads, q_len, head_dim) V = V.reshape(bsz, n_heads, q_len, head_dim) # See https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e # Gemma 9b should use 256 and not 224 (hs / nah). 27b uses the below # We default to using the config file itself # s = self.config.hidden_size // self.config.num_attention_heads s = self.config.query_pre_attn_scalar t = self.config.attn_logit_softcapping Q = Q * torch.tensor(s**-0.5, dtype = Q.dtype) # Follow Keras exactly A = torch_matmul(Q, K.transpose(2, 3)) # Logit softcapping A /= t torch_tanh(A, out = A) A *= t A += causal_mask[:q_len, :q_len] # Much slower in torch compile! # A.masked_fill_(causal_mask[:q_len, :q_len], -float("inf")) A = torch_nn_functional_softmax(A, dim = -1, dtype = torch.float32).to(Q.dtype) A = torch_matmul(A, V) A = A.transpose(1, 2).contiguous() A = A.reshape(bsz, q_len, n_heads * head_dim) return A
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/utils.py
unsloth/kernels/utils.py
# 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 importlib import triton import ctypes MAX_FUSED_SIZE: int = 65536 next_power_of_2 = triton.next_power_of_2 import functools from typing import Optional from ..device_type import ( is_hip, get_device_type, DEVICE_TYPE, DEVICE_TYPE_TORCH, DEVICE_COUNT, ALLOW_PREQUANTIZED_MODELS, ) from .fp8 import weight_dequant, fp8_linear import functools # torch.cuda.amp.custom_fwd is deprecated >= 2.4 import torch torch_Tensor = torch.Tensor from unsloth_zoo.utils import Version if DEVICE_TYPE == "xpu" and Version(torch.__version__) < Version("2.6.0"): raise RuntimeError( "Intel xpu currently supports unsloth with torch.version >= 2.6.0" ) if Version(torch.__version__) < Version("2.4.0"): torch_amp_custom_fwd = torch.cuda.amp.custom_fwd torch_amp_custom_bwd = torch.cuda.amp.custom_bwd else: torch_amp_custom_fwd = torch.amp.custom_fwd(device_type = "cuda") torch_amp_custom_bwd = torch.amp.custom_bwd(device_type = "cuda") if DEVICE_TYPE == "xpu": torch_amp_custom_fwd = torch.amp.custom_fwd(device_type = "xpu") torch_amp_custom_bwd = torch.amp.custom_bwd(device_type = "xpu") # tl.math.tanh now is libdevice.tanh import triton import triton.language as tl if Version(triton.__version__) >= Version("3.0.0"): if DEVICE_TYPE == "xpu": triton_tanh = tl.extra.intel.libdevice.tanh else: from triton.language.extra import libdevice triton_tanh = libdevice.tanh triton_cast = tl.cast else: triton_tanh = tl.math.tanh # No casting in old Triton versions @triton.jit def triton_cast(x, dtype): return x.to(dtype) @functools.lru_cache(1) def is_cdna(): return is_hip() and triton.runtime.driver.active.get_current_target().arch in ( "gfx940", "gfx941", "gfx942", ) def calculate_settings( n: int, ) -> ( int, int, ): BLOCK_SIZE: int = next_power_of_2(n) if BLOCK_SIZE > MAX_FUSED_SIZE: raise RuntimeError( f"Cannot launch Triton kernel since n = {n} exceeds " f"the maximum CUDA blocksize = {MAX_FUSED_SIZE}." ) num_warps: int = 4 if BLOCK_SIZE >= 32768: num_warps = 32 elif BLOCK_SIZE >= 8192: num_warps = 16 elif BLOCK_SIZE >= 2048: num_warps = 8 return BLOCK_SIZE, num_warps HAS_CUDA_STREAM = False import bitsandbytes as bnb # https://github.com/bitsandbytes-foundation/bitsandbytes/pull/1330/files HAS_CUDA_STREAM = Version(bnb.__version__) > Version("0.43.3") get_ptr = bnb.functional.get_ptr if DEVICE_TYPE == "xpu": HAS_XPU_STREAM = True if DEVICE_COUNT > 1: if DEVICE_TYPE in ("cuda", "hip"): torch_gpu_device = torch.cuda.device elif DEVICE_TYPE == "xpu": torch_gpu_device = torch.xpu.device else: from contextlib import nullcontext def torch_gpu_device(device): return nullcontext() # INTEL GPU Specific Logic if DEVICE_TYPE == "xpu": _gpu_getCurrentRawStream = torch._C._xpu_getCurrentRawStream # NVIDIA GPU Default Logic else: _gpu_getCurrentRawStream = torch._C._cuda_getCurrentRawStream c_void_p = ctypes.c_void_p def _get_tensor_stream(tensor: torch_Tensor) -> c_void_p: return c_void_p(_gpu_getCurrentRawStream(tensor.device.index)) # Get array of CUDA streams and other buffers global CUDA_STREAMS global XPU_STREAMS global WEIGHT_BUFFERS global ABSMAX_BUFFERS # INTEL GPU Specific Logic if DEVICE_TYPE == "xpu": _XPU_STREAMS = { (index := torch.xpu.device(i).idx): ctypes.c_void_p( torch._C._xpu_getCurrentRawStream(index) ) for i in range(DEVICE_COUNT) } XPU_STREAMS = [None] * (max(_XPU_STREAMS.keys()) + 1) WEIGHT_BUFFERS = [None] * (max(_XPU_STREAMS.keys()) + 1) ABSMAX_BUFFERS = [None] * (max(_XPU_STREAMS.keys()) + 1) for k, v in _XPU_STREAMS.items(): XPU_STREAMS[k] = v XPU_STREAMS = tuple(XPU_STREAMS) del _XPU_STREAMS else: # NVIDIA GPU Default Logic _CUDA_STREAMS = { (index := torch.cuda.device(i).idx): ctypes.c_void_p( torch._C._cuda_getCurrentRawStream(index) ) for i in range(DEVICE_COUNT) } CUDA_STREAMS = [None] * (max(_CUDA_STREAMS.keys()) + 1) WEIGHT_BUFFERS = [None] * (max(_CUDA_STREAMS.keys()) + 1) ABSMAX_BUFFERS = [None] * (max(_CUDA_STREAMS.keys()) + 1) for k, v in _CUDA_STREAMS.items(): CUDA_STREAMS[k] = v CUDA_STREAMS = tuple(CUDA_STREAMS) del _CUDA_STREAMS # Bitsandbytes operations ctypes_c_int = ctypes.c_int ctypes_c_int32 = ctypes.c_int32 cdequantize_blockwise_fp32 = bnb.functional.lib.cdequantize_blockwise_fp32 cdequantize_blockwise_fp16_nf4 = bnb.functional.lib.cdequantize_blockwise_fp16_nf4 cdequantize_blockwise_bf16_nf4 = bnb.functional.lib.cdequantize_blockwise_bf16_nf4 if DEVICE_TYPE == "xpu": # https://github.com/bitsandbytes-foundation/bitsandbytes/blob/c3b8de268fdb55a88f92feada23fc811a1e6877a/bitsandbytes/backends/xpu/ops.py#L115 # for xpu, inference gemv using above link cgemm_4bit_inference_naive_fp16 = bnb.functional.lib.cgemv_4bit_inference_fp16 cgemm_4bit_inference_naive_bf16 = bnb.functional.lib.cgemv_4bit_inference_bf16 else: cgemm_4bit_inference_naive_fp16 = bnb.functional.lib.cgemm_4bit_inference_naive_fp16 cgemm_4bit_inference_naive_bf16 = bnb.functional.lib.cgemm_4bit_inference_naive_bf16 torch_device_stream = ( torch.xpu.current_stream if DEVICE_TYPE == "xpu" else torch.cuda.current_stream ) torch_mm = torch.mm torch_mv = torch.mv torch_matmul = torch.matmul torch_addmm = torch.addmm torch_empty = torch.empty torch_float32 = torch.float32 torch_float16 = torch.float16 torch_bfloat16 = torch.bfloat16 # Check whether torchao can be imported to get Float8Tensor if importlib.util.find_spec("torchao") is not None: try: from torchao.quantization import Float8Tensor except: import torchao if Version(torchao.__version__) >= Version("0.15.0"): print( f"Unsloth: `from torchao.quantization import Float8Tensor` failed on version={torchao.__version__}" ) Float8Tensor = type(None) else: Float8Tensor = type(None) def QUANT_STATE(W): return getattr(W, "quant_state", None) def get_lora_parameters(proj): """ Return a 5-tuple of (weight, weight quant_state, lora A, lora B, and lora scale). If QAT is enabled, additionally fake quantize the base layer and lora weights. """ # For DPO or disabled adapters base_layer = getattr( proj, "base_layer", proj ) # (proj.base_layer if hasattr(proj, "base_layer") else proj) W = base_layer.weight # Optionally apply fake quantization to base layer weights for QAT if hasattr(base_layer, "weight_fake_quantizer"): weight_fake_quantizer = getattr(base_layer, "weight_fake_quantizer", None) if weight_fake_quantizer is not None: W = weight_fake_quantizer(W) # Get quant state for 4bit or FP8 W_quant = getattr(W, "quant_state", None) if W_quant is None: W_quant = getattr(base_layer, "weight_scale_inv", None) if W_quant is None: W_quant = getattr(base_layer, "weight_scale", None) if getattr(base_layer, "quant_method", None) == "fp8": # we need to somehow store and pass this information :) W.block_size = getattr(base_layer, "block_size", [128, 128]) W_quant.block_size = W.block_size # if not hasattr(proj, "disable_adapters") or proj.disable_adapters or proj.merged: if getattr(proj, "disable_adapters", True) or proj.merged: return W, W_quant, None, None, None adapter = getattr(proj, "active_adapters", None) if adapter is None: adapter = getattr(proj, "active_adapter", ("default")) adapter = adapter[0] # Optionally apply fake quantization to lora weights for QAT lora_A_linear = proj.lora_A[adapter] lora_B_linear = proj.lora_B[adapter] A = lora_A_linear.weight B = lora_B_linear.weight if hasattr(lora_A_linear, "weight_fake_quantizer"): lora_A_fake_quantizer = getattr(lora_A_linear, "weight_fake_quantizer", None) if lora_A_fake_quantizer is not None: A = lora_A_fake_quantizer(A) if hasattr(lora_B_linear, "weight_fake_quantizer"): lora_B_fake_quantizer = getattr(lora_B_linear, "weight_fake_quantizer", None) if lora_B_fake_quantizer is not None: B = lora_B_fake_quantizer(B) return ( W, W_quant, A, B, proj.scaling[adapter], ) def get_lora_parameters_bias(proj): # For DPO or disabled adapters base_layer = getattr( proj, "base_layer", proj ) # (proj.base_layer if hasattr(proj, "base_layer") else proj) W = base_layer.weight # Get quant state for 4bit or FP8 W_quant = getattr(W, "quant_state", None) if W_quant is None: W_quant = getattr(base_layer, "weight_scale_inv", None) if W_quant is None: W_quant = getattr(base_layer, "weight_scale", None) # if not hasattr(proj, "disable_adapters") or proj.disable_adapters or proj.merged: if getattr(proj, "disable_adapters", True) or proj.merged: return W, W_quant, None, None, None, base_layer.bias if getattr(base_layer, "quant_method", None) == "fp8": # we need to somehow store and pass this information :) W.block_size = getattr(base_layer, "block_size", [128, 128]) W_quant.block_size = W.block_size adapter = getattr(proj, "active_adapters", None) if adapter is None: adapter = getattr(proj, "active_adapter", ("default")) adapter = adapter[0] return ( W, W_quant, proj.lora_A[adapter].weight, proj.lora_B[adapter].weight, proj.scaling[adapter], base_layer.bias, ) def _maybe_fake_quantize_activations( X: torch.Tensor, proj: torch.nn.Module ) -> torch.Tensor: """ If QAT is enabled, fake quantize the input activations. Otherwise, just return the input activations as is. Weights are fake quantized separately in `get_lora_parameters`. """ base_layer = getattr(proj, "base_layer", proj) activation_fake_quantizer = getattr(base_layer, "activation_fake_quantizer", None) if activation_fake_quantizer is not None: X = activation_fake_quantizer(X) return X # INTEL GPU Specific Logic if DEVICE_TYPE == "xpu" and HAS_XPU_STREAM: @torch.inference_mode def fast_dequantize(W, quant_state = None, out = None, use_global_buffer = False): # TODO: After adding XPU BNB support, check this function if isinstance(W, Float8Tensor): return W.dequantize() if quant_state is None: return W if W.dtype == torch.float8_e4m3fn: return weight_dequant(W, quant_state) if type(quant_state) is not list: # New quant_state as a class # https://github.com/TimDettmers/bitsandbytes/pull/763/files absmax = quant_state.absmax shape = quant_state.shape dtype = quant_state.dtype blocksize = quant_state.blocksize offset = quant_state.offset state2 = quant_state.state2 absmax2 = state2.absmax code2 = state2.code blocksize2 = state2.blocksize else: # Old quant_state as a list of lists absmax, shape, dtype, blocksize, compressed_stats, _, _ = quant_state offset, state2 = compressed_stats absmax2, code2, blocksize2, _, _, _, _ = state2 global XPU_STREAMS device = W.device device_index = device.index XPU_STREAM = XPU_STREAMS[device_index] n_elements_absmax = absmax.numel() # Create weight matrix if use_global_buffer: # Use same buffers for faster inference size = shape[0] * shape[1] global WEIGHT_BUFFERS global ABSMAX_BUFFERS WEIGHT_BUFFER = WEIGHT_BUFFERS[device_index] ABSMAX_BUFFER = ABSMAX_BUFFERS[device_index] if WEIGHT_BUFFER is None: WEIGHT_BUFFERS[device_index] = WEIGHT_BUFFER = torch_empty( size, dtype = dtype, device = device, requires_grad = False ) ABSMAX_BUFFERS[device_index] = ABSMAX_BUFFER = torch_empty( n_elements_absmax, dtype = torch.float32, device = device, requires_grad = False, ) if size > WEIGHT_BUFFER.numel(): WEIGHT_BUFFER.resize_(size) if n_elements_absmax > ABSMAX_BUFFER.numel(): ABSMAX_BUFFER.resize_(n_elements_absmax) out = WEIGHT_BUFFER[:size].view(shape) out_absmax = ABSMAX_BUFFER[:n_elements_absmax] else: if out is None: out = torch_empty( shape, dtype = dtype, device = device, requires_grad = False ) else: assert out.shape == shape assert out.dtype == dtype out_absmax = torch_empty( n_elements_absmax, dtype = torch_float32, device = device, requires_grad = False, ) # NF4 dequantization of statistics ptr_out_absmax = get_ptr(out_absmax) with torch_gpu_device(device): cdequantize_blockwise_fp32( get_ptr(code2), get_ptr(absmax), get_ptr(absmax2), ptr_out_absmax, ctypes_c_int(blocksize2), ctypes_c_int(n_elements_absmax), XPU_STREAM, ) out_absmax += offset # Dequantize W fx = ( cdequantize_blockwise_fp16_nf4 if dtype == torch_float16 else cdequantize_blockwise_bf16_nf4 ) fx( get_ptr(None), get_ptr(W), ptr_out_absmax, get_ptr(out), ctypes_c_int(blocksize), ctypes_c_int(out.numel()), XPU_STREAM, ) # Careful returning transposed data is_transposed = True if W.shape[0] == 1 else False return out.t() if is_transposed else out # NVIDIA GPU Default Logic elif DEVICE_TYPE in ("cuda", "hip") and HAS_CUDA_STREAM: @torch.inference_mode def fast_dequantize(W, quant_state = None, out = None, use_global_buffer = False): if isinstance(W, Float8Tensor): return W.dequantize() if quant_state is None: return W if W.dtype == torch.float8_e4m3fn: return weight_dequant(W, quant_state) if type(quant_state) is not list: # New quant_state as a class # https://github.com/TimDettmers/bitsandbytes/pull/763/files absmax = quant_state.absmax shape = quant_state.shape dtype = quant_state.dtype blocksize = quant_state.blocksize offset = quant_state.offset state2 = quant_state.state2 absmax2 = state2.absmax code2 = state2.code blocksize2 = state2.blocksize else: # Old quant_state as a list of lists absmax, shape, dtype, blocksize, compressed_stats, _, _ = quant_state offset, state2 = compressed_stats absmax2, code2, blocksize2, _, _, _, _ = state2 pass global CUDA_STREAMS device = W.device device_index = device.index CUDA_STREAM = CUDA_STREAMS[device_index] n_elements_absmax = absmax.numel() # Create weight matrix if use_global_buffer: # Use same buffers for faster inference size = shape[0] * shape[1] global WEIGHT_BUFFERS global ABSMAX_BUFFERS WEIGHT_BUFFER = WEIGHT_BUFFERS[device_index] ABSMAX_BUFFER = ABSMAX_BUFFERS[device_index] if WEIGHT_BUFFER is None: WEIGHT_BUFFERS[device_index] = WEIGHT_BUFFER = torch_empty( size, dtype = dtype, device = device, requires_grad = False ) ABSMAX_BUFFERS[device_index] = ABSMAX_BUFFER = torch_empty( n_elements_absmax, dtype = torch_float32, device = device, requires_grad = False, ) if size > WEIGHT_BUFFER.numel(): WEIGHT_BUFFER.resize_(size) if n_elements_absmax > ABSMAX_BUFFER.numel(): ABSMAX_BUFFER.resize_(n_elements_absmax) out = WEIGHT_BUFFER[:size].view(shape) out_absmax = ABSMAX_BUFFER[:n_elements_absmax] else: if out is None: out = torch_empty( shape, dtype = dtype, device = device, requires_grad = False ) else: assert out.shape == shape assert out.dtype == dtype out_absmax = torch_empty( n_elements_absmax, dtype = torch_float32, device = device, requires_grad = False, ) pass # NF4 dequantization of statistics ptr_out_absmax = get_ptr(out_absmax) with torch_gpu_device(device): cdequantize_blockwise_fp32( get_ptr(code2), get_ptr(absmax), get_ptr(absmax2), ptr_out_absmax, ctypes_c_int(blocksize2), ctypes_c_int(n_elements_absmax), CUDA_STREAM, ) out_absmax += offset # Dequantize W fx = ( cdequantize_blockwise_fp16_nf4 if dtype == torch_float16 else cdequantize_blockwise_bf16_nf4 ) fx( get_ptr(None), get_ptr(W), ptr_out_absmax, get_ptr(out), ctypes_c_int(blocksize), ctypes_c_int(out.numel()), CUDA_STREAM, ) pass # Careful returning transposed data is_transposed = True if W.shape[0] == 1 else False return out.t() if is_transposed else out pass else: @torch.inference_mode def fast_dequantize(W, quant_state = None, out = None, use_global_buffer = False): if isinstance(W, Float8Tensor): return W.dequantize() if quant_state is None: return W if W.dtype == torch.float8_e4m3fn: return weight_dequant(W, quant_state) if type(quant_state) is not list: # New quant_state as a class # https://github.com/TimDettmers/bitsandbytes/pull/763/files absmax = quant_state.absmax shape = quant_state.shape dtype = quant_state.dtype blocksize = quant_state.blocksize offset = quant_state.offset state2 = quant_state.state2 absmax2 = state2.absmax code2 = state2.code blocksize2 = state2.blocksize else: # Old quant_state as a list of lists absmax, shape, dtype, blocksize, compressed_stats, _, _ = quant_state offset, state2 = compressed_stats absmax2, code2, blocksize2, _, _, _, _ = state2 pass n_elements_absmax = absmax.numel() device = W.device # Create weight matrix if out is None: out = torch_empty(shape, dtype = dtype, device = device, requires_grad = False) else: assert out.shape == shape assert out.dtype == dtype out_absmax = torch_empty( n_elements_absmax, dtype = torch_float32, device = device, requires_grad = False ) # Do dequantization ptr_out_absmax = get_ptr(out_absmax) cdequantize_blockwise_fp32( get_ptr(code2), get_ptr(absmax), get_ptr(absmax2), ptr_out_absmax, ctypes_c_int(blocksize2), ctypes_c_int(n_elements_absmax), ) out_absmax += offset fx = ( cdequantize_blockwise_fp16_nf4 if dtype == torch_float16 else cdequantize_blockwise_bf16_nf4 ) fx( get_ptr(None), get_ptr(W), ptr_out_absmax, get_ptr(out), ctypes_c_int(blocksize), ctypes_c_int(out.numel()), ) # Careful returning transposed data is_transposed = True if W.shape[0] == 1 else False return out.t() if is_transposed else out pass # INTEL GPU Specific Logic if DEVICE_TYPE == "xpu" and HAS_XPU_STREAM: def fast_gemv(X, W, quant_state, out = None): if quant_state is None: return torch_matmul(X, W, out = out) # For fast X @ W where seq_len == 1 # From https://github.com/TimDettmers/bitsandbytes/blob/main/bitsandbytes/functional.py#L1469 _, q_len, hd = X.shape # assert(q_len == 1) if type(quant_state) is not list: # https://github.com/TimDettmers/bitsandbytes/pull/763/files absmax = quant_state.absmax shape = quant_state.shape dtype = quant_state.dtype blocksize = quant_state.blocksize stats = quant_state.code offset = quant_state.offset state2 = quant_state.state2 absmax2 = state2.absmax code2 = state2.code blocksize2 = state2.blocksize else: absmax, shape, dtype, blocksize, compressed_stats, quant_type, stats = ( quant_state ) offset, state2 = compressed_stats absmax2, code2, blocksize2, _, _, _, _ = state2 global XPU_STREAMS device = W.device device_index = device.index XPU_STREAM = XPU_STREAMS[device_index] # assert(dtype == X.dtype) bout = shape[0] if out is None: out = torch_empty( ( 1, 1, bout, ), dtype = dtype, device = device, ) # else: # assert(out.shape == (1, 1, bout,)) # pass if DEVICE_TYPE == "xpu": m = 1 n = shape[0] else: n = 1 m = shape[0] k = shape[1] lda = shape[0] ldc = shape[0] ldb = (hd + 1) // 2 m = ctypes_c_int32(m) n = ctypes_c_int32(n) k = ctypes_c_int32(k) lda = ctypes_c_int32(lda) ldb = ctypes_c_int32(ldb) ldc = ctypes_c_int32(ldc) df = torch_empty(absmax.shape, dtype = torch_float32, device = device) with torch_gpu_device(device): cdequantize_blockwise_fp32( get_ptr(code2), get_ptr(absmax), get_ptr(absmax2), get_ptr(df), ctypes_c_int(blocksize2), ctypes_c_int(df.numel()), XPU_STREAM, ) df += offset absmax = df fx = ( cgemm_4bit_inference_naive_fp16 if dtype == torch_float16 else cgemm_4bit_inference_naive_bf16 ) blocksize = ctypes_c_int32(blocksize) fx( m, n, k, get_ptr(X), get_ptr(W), get_ptr(absmax), get_ptr(stats), get_ptr(out), lda, ldb, ldc, blocksize, XPU_STREAM, ) return out elif DEVICE_TYPE in ("cuda", "hip") and HAS_CUDA_STREAM: def fast_gemv(X, W, quant_state, out = None): if quant_state is None: return torch_matmul(X, W, out = out) # For fast X @ W where seq_len == 1 # From https://github.com/TimDettmers/bitsandbytes/blob/main/bitsandbytes/functional.py#L1469 _, q_len, hd = X.shape # assert(q_len == 1) if type(quant_state) is not list: # https://github.com/TimDettmers/bitsandbytes/pull/763/files absmax = quant_state.absmax shape = quant_state.shape dtype = quant_state.dtype blocksize = quant_state.blocksize stats = quant_state.code offset = quant_state.offset state2 = quant_state.state2 absmax2 = state2.absmax code2 = state2.code blocksize2 = state2.blocksize else: absmax, shape, dtype, blocksize, compressed_stats, quant_type, stats = ( quant_state ) offset, state2 = compressed_stats absmax2, code2, blocksize2, _, _, _, _ = state2 pass global CUDA_STREAMS device = W.device device_index = device.index CUDA_STREAM = CUDA_STREAMS[device_index] # assert(dtype == X.dtype) bout = shape[0] if out is None: out = torch_empty( ( 1, 1, bout, ), dtype = dtype, device = device, ) # else: # assert(out.shape == (1, 1, bout,)) # pass n = 1 m = shape[0] k = shape[1] lda = shape[0] ldc = shape[0] ldb = (hd + 1) // 2 m = ctypes_c_int32(m) n = ctypes_c_int32(n) k = ctypes_c_int32(k) lda = ctypes_c_int32(lda) ldb = ctypes_c_int32(ldb) ldc = ctypes_c_int32(ldc) df = torch_empty(absmax.shape, dtype = torch_float32, device = device) with torch_gpu_device(device): cdequantize_blockwise_fp32( get_ptr(code2), get_ptr(absmax), get_ptr(absmax2), get_ptr(df), ctypes_c_int(blocksize2), ctypes_c_int(df.numel()), CUDA_STREAM, ) df += offset absmax = df fx = ( cgemm_4bit_inference_naive_fp16 if dtype == torch_float16 else cgemm_4bit_inference_naive_bf16 ) blocksize = ctypes_c_int32(blocksize) fx( m, n, k, get_ptr(X), get_ptr(W), get_ptr(absmax), get_ptr(stats), get_ptr(out), lda, ldb, ldc, blocksize, CUDA_STREAM, ) pass return out pass else: def fast_gemv(X, W, quant_state, out = None): if quant_state is None: return torch_matmul(X, W, out = out) # For fast X @ W where seq_len == 1 # From https://github.com/TimDettmers/bitsandbytes/blob/main/bitsandbytes/functional.py#L1469 _, q_len, hd = X.shape # assert(q_len == 1) if type(quant_state) is not list: # https://github.com/TimDettmers/bitsandbytes/pull/763/files absmax = quant_state.absmax shape = quant_state.shape dtype = quant_state.dtype blocksize = quant_state.blocksize stats = quant_state.code offset = quant_state.offset state2 = quant_state.state2 absmax2 = state2.absmax code2 = state2.code blocksize2 = state2.blocksize else: absmax, shape, dtype, blocksize, compressed_stats, quant_type, stats = ( quant_state ) offset, state2 = compressed_stats absmax2, code2, blocksize2, _, _, _, _ = state2 pass # assert(dtype == X.dtype) bout = shape[0] device = W.device if out is None: out = torch_empty( ( 1, 1, bout, ), dtype = dtype, device = device, ) # else: # assert(out.shape == (1, 1, bout,)) # pass n = 1 m = shape[0] k = shape[1] lda = shape[0] ldc = shape[0] ldb = (hd + 1) // 2 m = ctypes_c_int32(m) n = ctypes_c_int32(n) k = ctypes_c_int32(k) lda = ctypes_c_int32(lda) ldb = ctypes_c_int32(ldb) ldc = ctypes_c_int32(ldc) df = torch_empty(absmax.shape, dtype = torch_float32, device = device) cdequantize_blockwise_fp32( get_ptr(code2), get_ptr(absmax), get_ptr(absmax2), get_ptr(df), ctypes_c_int(blocksize2), ctypes_c_int(df.numel()), ) df += offset absmax = df fx = ( cgemm_4bit_inference_naive_fp16 if dtype == torch_float16 else cgemm_4bit_inference_naive_bf16 ) blocksize = ctypes_c_int32(blocksize) fx( m, n, k, get_ptr(X), get_ptr(W), get_ptr(absmax), get_ptr(stats), get_ptr(out), lda, ldb, ldc, blocksize, ) return out pass def fast_linear_forward(proj, X, temp_lora = None, out = None): W, W_quant, lora_A, lora_B, lora_S, bias = get_lora_parameters_bias(proj) bsz, q_len, in_dim = X.shape if q_len != 1: return matmul_lora(X, W, W_quant, lora_A, lora_B, lora_S) if W_quant is None: out = torch_matmul(X, W.t(), out = out) elif W.dtype == torch.float8_e4m3fn: out = fp8_linear(X, W, W_quant, bias) elif bsz == 1 and q_len == 1: out = fast_gemv(X, W, W_quant, out = out) else: W = fast_dequantize(W.t(), W_quant, use_global_buffer = True) out = torch_matmul(X, W, out = out) # Add in LoRA weights if lora_A is not None: out_dim = out.shape[2] dtype = X.dtype if not hasattr(lora_A, "_fast_lora"): lora_A._fast_lora = lora_A.to(dtype) lora_B._fast_lora = lora_B.to(dtype) if bsz == 1: out = out.view(out_dim) temp_lora = torch_mv(lora_A._fast_lora, X.ravel(), out = temp_lora) out.addmv_(lora_B._fast_lora, temp_lora, alpha = lora_S) else: out = out.view(bsz, out_dim) temp_lora = torch_mm( X.view(bsz, in_dim), lora_A._fast_lora.t(), out = temp_lora ) out.addmm_(temp_lora, lora_B._fast_lora.t(), alpha = lora_S) out = out.view(bsz, 1, out_dim) if bias is not None: out += bias return out def matmul_lora(X, W, W_quant, A, B, s, out = None): dtype = X.dtype if X.dim() == 3: batch, seq_len, d = X.shape X = X.view(-1, X.shape[-1]) reshape = True else: reshape = False if isinstance(W, Float8Tensor): assert W.ndim == 2 if W.block_size[0] == W.shape[0] and W.block_size[1] == 1: # In the backward pass, rowwise scaled becomes colwise scaled after we # transpose the weight tensor. Use this case to detect backward. # TODO: would be simpler if we simply don't call `matmul_lora` in backward W = W.dequantize() else: W = W.contiguous()
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
true
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/geglu.py
unsloth/kernels/geglu.py
# 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 triton import triton.language as tl import torch from .utils import ( calculate_settings, triton_tanh, torch_gpu_device, ) # signed int32 max is 2**31-1 so num_elements cannot exceed 2**31 NUM_INT32_ELEMENTS = 2**31 SAFE_INT32_BUFFER_MULTIPLIER = 4 BLOCK_SIZE = 1024 INT32_SAFETY_BUFFER = NUM_INT32_ELEMENTS - BLOCK_SIZE * SAFE_INT32_BUFFER_MULTIPLIER @triton.jit def _exact_forward_kernel( e, g, h, n_elements, BLOCK_SIZE: tl.constexpr, LONG_INDEXING: tl.constexpr, ): block_idx = tl.program_id(0) if LONG_INDEXING: offsets = block_idx.to(tl.int64) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE).to( tl.int64 ) n_elements = tl.cast(n_elements, tl.int64) else: offsets = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < n_elements # f = 1/2 * e * (1 + erf(1/sqrt(2) * e)) # h = f * up e_row = tl.load(e + offsets, mask = mask, other = 0).to(tl.float32) g_row = tl.load(g + offsets, mask = mask, other = 0) # .to(tl.float32) f_row = 0.5 * e_row * (tl.math.erf(tl.math.rsqrt(2.0) * e_row) + 1.0) f_row = f_row.to(g_row.dtype) # Exact copy from HF h_row = f_row * g_row # Store h tl.store(h + offsets, h_row, mask = mask) def geglu_exact_forward_kernel(gate, up): batch, seq_len, hd = gate.shape n_elements = gate.numel() device = gate.device out = torch.empty((batch, seq_len, hd), dtype = gate.dtype, device = device) grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) with torch_gpu_device(device): _exact_forward_kernel[grid]( gate, up, out, n_elements, BLOCK_SIZE = BLOCK_SIZE, LONG_INDEXING = 0 if n_elements <= INT32_SAFETY_BUFFER else 1, ) return out @triton.jit def _exact_backward_kernel( DW, e, g, n_elements, BLOCK_SIZE: tl.constexpr, LONG_INDEXING: tl.constexpr, ): """ f = 1/2 * e * (1 + erf(1/sqrt(2) * e)) h = f * up df/de (with help of Wolfram :) df/de = 1/2 * (1 + erf(1/sqrt(2) * e)) + 1/sqrt(2*pi) * e * exp(-1/2 * e^2) Reuse via f = 1/2 * (1 + erf(1/sqrt(2) * e)) * e """ block_idx = tl.program_id(0) if LONG_INDEXING: offsets = block_idx.to(tl.int64) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE).to( tl.int64 ) n_elements = tl.cast(n_elements, tl.int64) else: offsets = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < n_elements DW_row = tl.load(DW + offsets, mask = mask, other = 0) # .to(tl.float32) e_row = tl.load(e + offsets, mask = mask, other = 0).to(tl.float32) g_row = tl.load(g + offsets, mask = mask, other = 0) # .to(tl.float32) # Break e_row away for re-use # f = 1/2 * e * (1 + erf(1/sqrt(2) * e)) f_partial_row = 0.5 * (tl.math.erf(tl.math.rsqrt(2.0) * e_row) + 1.0) f_row = f_partial_row * e_row f_row = f_row.to(DW_row.dtype) # h = f * g h_row = f_row * g_row # df = DW * f df_row = DW_row * f_row # dg = DW * g dg_row = DW_row * g_row # df/de = 1/2 * (1 + erf(1/sqrt(2) * e)) + 1/sqrt(2*pi) * e * exp(-1/2 * e^2) t = 0.3989422804014327 # 1/sqrt(2*pi) df_de = f_partial_row + t * e_row * tl.exp(-0.5 * e_row * e_row) de_row = dg_row.to(tl.float32) * df_de de_row = de_row.to(DW_row.dtype) # Store derivatives in buffers tl.store(DW + offsets, h_row, mask = mask) # h = f * g tl.store(e + offsets, df_row, mask = mask) # df = DW * f tl.store(g + offsets, de_row, mask = mask) # de def geglu_exact_backward_kernel(DW, e, g): batch_seq_len, hd = e.shape n_elements = e.numel() grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) with torch_gpu_device(e.device): _exact_backward_kernel[grid]( DW, e, g, n_elements, BLOCK_SIZE = BLOCK_SIZE, LONG_INDEXING = 0 if n_elements <= INT32_SAFETY_BUFFER else 1, ) return DW, e, g @triton.jit def _approx_forward_kernel( e, g, h, n_elements, BLOCK_SIZE: tl.constexpr, LONG_INDEXING: tl.constexpr, ): block_idx = tl.program_id(0) if LONG_INDEXING: offsets = block_idx.to(tl.int64) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE).to( tl.int64 ) n_elements = tl.cast(n_elements, tl.int64) else: offsets = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < n_elements # f = 1/2 * e * (1 + tanh( sqrt(2/pi) * (x + 0.044715 * x^3 ) )) # f = 1/2 * e * (1 + tanh( sqrt(2/pi) * x * (1 + 0.044715 * x^2 ) )) # h = f * up s = 0.7978845608028654 # math.sqrt(2 / math.pi) e_row = tl.load(e + offsets, mask = mask, other = 0).to(tl.float32) g_row = tl.load(g + offsets, mask = mask, other = 0) # .to(tl.float32) f_row = ( 0.5 * e_row * (triton_tanh(s * e_row * (1.0 + 0.044715 * e_row * e_row)) + 1.0) ) f_row = f_row.to(g_row.dtype) # Exact copy from HF h_row = f_row * g_row # Store h tl.store(h + offsets, h_row, mask = mask) def geglu_approx_forward_kernel(gate, up): batch, seq_len, hd = gate.shape n_elements = gate.numel() device = gate.device out = torch.empty((batch, seq_len, hd), dtype = gate.dtype, device = device) grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) with torch_gpu_device(device): _approx_forward_kernel[grid]( gate, up, out, n_elements, BLOCK_SIZE = BLOCK_SIZE, LONG_INDEXING = 0 if n_elements <= INT32_SAFETY_BUFFER else 1, ) return out @triton.jit def _approx_backward_kernel( DW, e, g, n_elements, BLOCK_SIZE: tl.constexpr, LONG_INDEXING: tl.constexpr, ): """ f = 1/2 * e * (1 + tanh( sqrt(2/pi) * x * (1 + 0.044715 * x^2 ) )) h = f * up df/de (with help from https://arxiv.org/pdf/2305.12073.pdf :)) df/de = 1/2 * [1 + tanh( sqrt(2/pi) * x * (1 + 0.044715 * x^2 ) )] + 1/2 * sech^2 [ sqrt(2/pi) * x * (1 + 0.044715 * x^2 ) ] * \ ( sqrt(2/pi) * x * (1 + 0.044715 * x^2 * 3 ) ) Notice sech^2(x) = 1 - tanh^2(x) So reuse tanh( sqrt(2/pi) * x * (1 + 0.044715 * x^2 ) ) See https://www.desmos.com/calculator/nqprfoni6x """ block_idx = tl.program_id(0) if LONG_INDEXING: offsets = block_idx.to(tl.int64) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE).to( tl.int64 ) n_elements = tl.cast(n_elements, tl.int64) else: offsets = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < n_elements DW_row = tl.load(DW + offsets, mask = mask, other = 0) # .to(tl.float32) e_row = tl.load(e + offsets, mask = mask, other = 0).to(tl.float32) g_row = tl.load(g + offsets, mask = mask, other = 0) # .to(tl.float32) # See https://www.desmos.com/calculator/nqprfoni6x s = 0.7978845608028654 # math.sqrt(2 / math.pi) a = s * e_row # a = sqrt(2 / pi) * x b = a * 0.044715 * e_row * e_row # b = a * 0.044715 * x^2 T = 1.0 + triton_tanh(a + b) T2 = 0.5 * T # Q = 0.5 * -T * (T - 2.0) * (a + 3.0 * b) Q2 = -T2 * (T - 2.0) * (a + 3.0 * b) df_de = T2 + Q2 # 1/2 * (T + Q) # f = 1/2 * e * (1 + tanh( sqrt(2/pi) * (x + 0.044715 * x^3 ) )) f_row = T2 * e_row f_row = f_row.to(DW_row.dtype) # h = f * g h_row = f_row * g_row # df = DW * f df_row = DW_row * f_row # dg = DW * g dg_row = DW_row * g_row de_row = dg_row.to(tl.float32) * df_de de_row = de_row.to(DW_row.dtype) # Store derivatives in buffers tl.store(DW + offsets, h_row, mask = mask) # h = f * g tl.store(e + offsets, df_row, mask = mask) # df = DW * f tl.store(g + offsets, de_row, mask = mask) # de def geglu_approx_backward_kernel(DW, e, g): batch_seq_len, hd = e.shape n_elements = e.numel() grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) with torch_gpu_device(e.device): _approx_backward_kernel[grid]( DW, e, g, n_elements, BLOCK_SIZE = BLOCK_SIZE, LONG_INDEXING = 0 if n_elements <= INT32_SAFETY_BUFFER else 1, ) return DW, e, g
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/fp8.py
unsloth/kernels/fp8.py
# 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 os import torch import torch.nn as nn import triton import triton.language as tl from torch.nn import functional as F import math from unsloth_zoo.utils import Version from unsloth_zoo.log import logger from unsloth_zoo.temporary_patches.common import torch_compile torch_matmul = torch.matmul try: from transformers.integrations.finegrained_fp8 import FP8Linear except: FP8Linear = None logger.info( "Unsloth: FP8 models need importing FP8Linear from `transformers.integrations.finegrained_fp8` but we don't see it." ) try: from transformers.integrations.fbgemm_fp8 import FbgemmFp8Linear except: FbgemmFp8Linear = None logger.info( "Unsloth: FP8 models need importing FbgemmFP8Linear from `transformers.integrations.fbgemm_fp8` but we don't see it." ) try: from fbgemm_gpu.experimental.gemm.triton_gemm.fp8_gemm import ( triton_quantize_fp8_block, ) except: triton_quantize_fp8_block = None logger.info( "Unsloth: Could not find fbgemm_gpu.experimental.gemm.triton_gemm.fp8_gemm.triton_quantize_fp8_block" ) try: from torchao.prototype.blockwise_fp8_inference.blockwise_quantization import ( blockwise_fp8_gemm as torchao_blockwise_gemm, ) except: torchao_blockwise_gemm = None logger.info( "Unsloth: Could not find torchao.prototype.blockwise_fp8_inference.blockwise_quantization.blockwise_fp8_gemm" ) @triton.jit def weight_dequant_kernel(x_ptr, s_ptr, y_ptr, M, N, BLOCK_SIZE: tl.constexpr): pid_m = tl.program_id(axis = 0) pid_n = tl.program_id(axis = 1) n = tl.cdiv(N, BLOCK_SIZE) offs_m = pid_m * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) offs_n = pid_n * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) offs = offs_m[:, None] * N + offs_n[None, :] mask = (offs_m[:, None] < M) & (offs_n[None, :] < N) x = tl.load(x_ptr + offs, mask = mask).to(tl.float32) s = tl.load(s_ptr + pid_m * n + pid_n) y = x * s tl.store(y_ptr + offs, y, mask = mask) def weight_dequant_block( x: torch.Tensor, s: torch.Tensor, block_size: int = 128, dtype = torch.bfloat16 ) -> torch.Tensor: if not x.is_contiguous(): x = x.contiguous() if not s.is_contiguous(): s = s.contiguous() assert x.dim() == 2 and s.dim() == 2 M, N = x.size() y = torch.empty_like(x, dtype = dtype) grid = lambda meta: ( triton.cdiv(M, meta["BLOCK_SIZE"]), triton.cdiv(N, meta["BLOCK_SIZE"]), ) weight_dequant_kernel[grid](x, s, y, M, N, BLOCK_SIZE = block_size) return y def weight_dequant(x: torch.Tensor, s: torch.Tensor, dtype = torch.bfloat16): if s.shape[1] == 1: # this is row quantized weight, just simple multiplication suffices if x.shape[0] == s.shape[0]: y = x.to(dtype) * s.to(dtype) elif x.shape[1] == s.shape[0]: # sometimes, this is called with the transpose of the weight. Adjust for that. y = x.t().to(dtype) * s.to(dtype) y = y.t() else: raise ValueError(f"Incompatible shapes {x.shape = }, {s.shape = }") return y else: # this is block quantized weight return weight_dequant_block(x, s, dtype = dtype) # Copied from https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/inference/kernel.py @triton.jit def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr): pid = tl.program_id(axis = 0) offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) x = tl.load(x_ptr + offs).to(tl.float32) s = tl.max(tl.abs(x)) / 448.0 # For a row of all zeros, lets return zeros as is # for LoRA, there are cases where dY has 0 in it and we should not let it be NaN # this is a deviation from the original implementation. s = 1.0 if s == 0 else s y = x / s y = y.to(y_ptr.dtype.element_ty) tl.store(y_ptr + offs, y) tl.store(s_ptr + pid, s) def act_quant( x: torch.Tensor, block_size: int = 128 ) -> tuple[torch.Tensor, torch.Tensor]: if not x.is_contiguous(): x = x.contiguous() assert x.shape[-1] % block_size == 0 y = torch.empty_like(x, dtype = torch.float8_e4m3fn) s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype = torch.float32) def grid(meta): return (triton.cdiv(x.numel(), meta["BLOCK_SIZE"]),) act_quant_kernel[grid](x, y, s, BLOCK_SIZE = block_size) return y, s # Adapted from https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/quantization/fp8_kernel.py @triton.jit def _w8a8_block_fp8_matmul( # Pointers to inputs and output A, B, C, As, Bs, # Shape for matmul M, N, K, # Block size for block-wise quantization group_n, group_k, # Stride for inputs and output stride_am, stride_ak, stride_bk, stride_bn, stride_cm, stride_cn, stride_As_m, stride_As_k, stride_Bs_k, stride_Bs_n, # Meta-parameters BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, GROUP_SIZE_M: tl.constexpr, ): """Triton-accelerated function used to perform linear operations (dot product) on input tensors `A` and `B` with block-wise quantization, and store the result in output tensor `C`. """ pid = tl.program_id(axis = 0) num_pid_m = tl.cdiv(M, BLOCK_SIZE_M) num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) num_pid_in_group = GROUP_SIZE_M * num_pid_n group_id = pid // num_pid_in_group first_pid_m = group_id * GROUP_SIZE_M group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M) pid_m = first_pid_m + (pid % group_size_m) pid_n = (pid % num_pid_in_group) // group_size_m offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N offs_k = tl.arange(0, BLOCK_SIZE_K) a_ptrs = A + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak) b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn) As_ptrs = As + offs_am * stride_As_m offs_bsn = offs_bn // group_n Bs_ptrs = Bs + offs_bsn * stride_Bs_n accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype = tl.float32) for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)): a = tl.load(a_ptrs, mask = offs_k[None, :] < K - k * BLOCK_SIZE_K, other = 0.0) b = tl.load(b_ptrs, mask = offs_k[:, None] < K - k * BLOCK_SIZE_K, other = 0.0) k_start = k * BLOCK_SIZE_K offs_ks = k_start // group_k a_s = tl.load(As_ptrs + offs_ks * stride_As_k) b_s = tl.load(Bs_ptrs + offs_ks * stride_Bs_k) accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :] a_ptrs += BLOCK_SIZE_K * stride_ak b_ptrs += BLOCK_SIZE_K * stride_bk if C.dtype.element_ty == tl.bfloat16: c = accumulator.to(tl.bfloat16) elif C.dtype.element_ty == tl.float16: c = accumulator.to(tl.float16) else: c = accumulator.to(tl.float32) offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) c_ptrs = C + stride_cm * offs_cm[:, None] + stride_cn * offs_cn[None, :] c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < N) tl.store(c_ptrs, c, mask = c_mask) def w8a8_block_fp8_matmul_triton( A: torch.Tensor, B: torch.Tensor, As: torch.Tensor, Bs: torch.Tensor, block_size: list[int], output_dtype: torch.dtype = torch.float32, ) -> torch.Tensor: """This function performs matrix multiplication with block-wise quantization. It takes two input tensors `A` and `B` with scales `As` and `Bs`. The output is returned in the specified `output_dtype`. Args: A: The input tensor, e.g., activation. B: The input tensor, e.g., weight. As: The per-token-group quantization scale for `A`. Bs: The per-block quantization scale for `B`. block_size: The block size for per-block quantization. It should be 2-dim, e.g., [128, 128]. output_dytpe: The dtype of the returned tensor. Returns: torch.Tensor: The result of matmul. """ assert len(block_size) == 2 block_n, block_k = block_size[0], block_size[1] assert A.shape[-1] == B.shape[-1] assert A.shape[:-1] == As.shape[:-1] and A.is_contiguous() assert triton.cdiv(A.shape[-1], block_k) == As.shape[-1] M = A.numel() // A.shape[-1] assert B.ndim == 2 and B.is_contiguous() and Bs.ndim == 2 N, K = B.shape assert triton.cdiv(N, block_n) == Bs.shape[0] assert triton.cdiv(K, block_k) == Bs.shape[1] C_shape = A.shape[:-1] + (N,) C = A.new_empty(C_shape, dtype = output_dtype) BLOCK_SIZE_M = 128 if M < BLOCK_SIZE_M: BLOCK_SIZE_M = triton.next_power_of_2(M) BLOCK_SIZE_M = max(BLOCK_SIZE_M, 16) BLOCK_SIZE_K = block_k assert block_k % BLOCK_SIZE_K == 0 BLOCK_SIZE_N = block_n def grid(META): return ( triton.cdiv(M, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]), ) _w8a8_block_fp8_matmul[grid]( A, B, C, As, Bs, M, N, K, block_n, block_k, A.stride(-2), A.stride(-1), B.stride(1), B.stride(0), C.stride(-2), C.stride(-1), As.stride(-2), As.stride(-1), Bs.stride(1), Bs.stride(0), BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, GROUP_SIZE_M = 8, ) return C def torchao_block_matmul( act_q: torch.Tensor, weight_q: torch.Tensor, act_scale: torch.Tensor, weight_scale: torch.Tensor, block_size: tuple[int, int], output_dtype: torch.dtype = torch.bfloat16, ): out = torchao_blockwise_gemm( act_q.contiguous(), act_scale.contiguous(), weight_q.contiguous(), weight_scale.contiguous(), block_size = block_size[1], ) return out.to(output_dtype) # Note that older versions of fbgemm (<=1.3.0) cause numerical imprecisions resulting in NaNs especially when X has high values in it. # So our preference order is fbgemm (>=1.4.0) > torchao > triton. All of these have similar outputs/losses. Never use fbgemm (<=1.3.0) for block quantized FP8 matmul. # This torchao FP8 matmul seems to be ~3x faster than the w8a8_block_fp8_matmul_triton. Though torchao is 15-30% slower than fbgemm implementation (on H100 GPUs). fp8_block_matmul = ( torchao_block_matmul if torchao_blockwise_gemm is not None else w8a8_block_fp8_matmul_triton ) class FP8BlockQuantLinear(torch.autograd.Function): @staticmethod def forward(ctx, X, weight, weight_scale): # block_size = getattr(weight, 'block_size', [128,128]) m, n = weight.shape p, q = weight_scale.shape block_size = getattr(weight, "block_size", None) or getattr( weight_scale, "block_size", [128, 128] ) assert block_size is not None, "block_size is not set" if triton.cdiv(m, block_size[0]) != p or triton.cdiv(n, block_size[1]) != q: if ( triton.cdiv(m, block_size[0]) == q and triton.cdiv(n, block_size[1]) == p ): # weights are transposed during backward pass for training :) # We transpose weight scale to counter that. Note that transposing weight would cause issues with matmul with input X weight_scale = weight_scale.T else: raise ValueError( f"Weight shape {weight.shape} and scales shape {weight_scale.shape} is not compatible with block size {block_size}" ) if not weight.is_contiguous(): weight = weight.contiguous() # this is replica of https://github.com/huggingface/transformers/blob/01c9e1ba683b3e50d7c76bf92f2d470759fd5e81/src/transformers/integrations/finegrained_fp8.py#L331-L353 qinput, scale = act_quant(X, block_size[1]) output = fp8_block_matmul( qinput, weight, scale, weight_scale, block_size, output_dtype = X.dtype, ) ctx.weight = weight ctx.weight_scale = weight_scale ctx.block_size = block_size return output.to(X.dtype) @staticmethod def backward(ctx, grad_output): W_deq = weight_dequant(ctx.weight, ctx.weight_scale) grad_X = torch_matmul(grad_output, W_deq) del W_deq return grad_X, None, None @torch_compile def fp8_torch_block_quant_forward(X, weight, weight_scale): return FP8BlockQuantLinear.apply(X, weight, weight_scale) class FbgemmFp8Linear_matmul(torch.autograd.Function): @staticmethod def forward(ctx, x, weight, weight_scale, bias = None): if weight.shape[0] == weight_scale.shape[0] and ( weight.shape[0] % 8 == 0 and weight.shape[1] % 8 == 0 ): # Edit: The kernel seems to expect that the weight has dimensions divisible by 8. Otherwise it throws `RuntimeError: cutlass cannot implement` # One thing we can do is to pad the weight and weight scale to multiple of 8 and perform a F8F8BF16 operation. # I tried benchmarking that for speed but observed that dequantize+bf16 matmul is significantly faster than padding+f8f8bf16 matmul. So we'll go that route. # So essentially, f8f8bf16_rowise only happens when shapes are proper (no transposes) and divisible by 8. # quantize_fp8_per_row will squash the leading dimensions, so save the desired shape here output_shape = (*x.shape[:-1], -1) # x_quantized and x_scale are not necessarily on the same device as x, this is an issue. # https://github.com/pytorch/FBGEMM/blob/e08af8539c391437f447173863df0f3f6f6f1855/fbgemm_gpu/experimental/gen_ai/src/quantize/quantize.cu#L1237C3-L1237C45 x_quantized, x_scale = torch.ops.fbgemm.quantize_fp8_per_row( x.view(-1, x.shape[-1]).contiguous(), scale_ub = getattr(weight, "input_scale_ub", None), ) # moving x_quantized, x_scale here creates glibberish output ... However, if we move the output, it works # x_quantized, x_scale = x_quantized.to(x.device), x_scale.to(x.device) # The computation still happens on the device where self.weight is even if x_quantized is not on the same device as self.weight weight_scale_float32 = weight_scale.to(torch.float32) if not weight.is_contiguous(): weight = weight.contiguous() if not weight_scale.is_contiguous(): weight_scale = weight_scale.contiguous() output = torch.ops.fbgemm.f8f8bf16_rowwise( x_quantized, weight, x_scale, weight_scale_float32, use_fast_accum = True ) output = output + bias if bias is not None else output # Hacky for now, we have the output to the device of x output = output.to(x.device, x.dtype) output = output.reshape(output_shape) del x_quantized, x_scale elif ( weight.shape[0] != weight_scale.shape[0] and weight.shape[1] == weight_scale.shape[0] ) or (weight.shape[0] // 8 != 0 or weight.shape[1] // 8 != 0): # Either the weight/scale is transposed or its shape is not divisible by 8. Both cases, dequantizing is the preferred way. # The transpose case is generally noticed in backward pass when we do dY@W instead of @W.T as we do for forward. # The shape case, I noticed to happen in MLP of Qwen 2.5 VL 7B where the gate proj is of shape (3420, 1280) and 3420/8=427.5 W_deq = weight_dequant(weight, weight_scale).T output = torch_matmul(x, W_deq) del W_deq else: raise ValueError( f"Shapes are incompatible {weight.shape = }, {weight_scale.shape = }, {x.shape = }" ) ctx.weight = weight ctx.weight_scale = weight_scale return output @staticmethod def backward(ctx, grad_output): W_deq = weight_dequant(ctx.weight, ctx.weight_scale) grad_X = torch_matmul(grad_output, W_deq) del W_deq return grad_X, None, None, None, None @torch_compile def fbgemm_fp8_linear(X, weight, weight_scale, bias = None): return FbgemmFp8Linear_matmul.apply(X, weight, weight_scale, bias) class FP8_fbgemm_block_linear(torch.autograd.Function): @staticmethod def forward(ctx, X, weight, weight_scale, bias = None): orig_shape = X.shape X = X.view(-1, X.shape[-1]) bs_n, bs_k = getattr(weight, "block_size", None) or getattr( weight_scale, "block_size", [128, 128] ) bs_m = bs_n m, n = weight.shape p, q = weight_scale.shape if triton.cdiv(m, bs_n) != p or triton.cdiv(n, bs_k) != q: if triton.cdiv(m, bs_n) == q and triton.cdiv(n, bs_k) == p: # weights are transposed during backward pass for training :) # We transpose weight scale to counter that. Note that transposing weight would cause issues with matmul with input X weight_scale = weight_scale.T else: raise ValueError( f"Weight shape {weight.shape} and scales shape {weight_scale.shape} is not compatible with block size {bs_n, bs_k}" ) xq, xs = triton_quantize_fp8_block(X, bs_m, bs_n, None) ## TODO: Investigate and resolve the high divergence of this output from baseline # WARNING: This causes the outputs to diverge from expected when X has high values in it. # That results in the model producing gibberish, especially on longer sequences and training loss starting at high values like 8 instead of <1 ideally # Please refrain from using this till this issue is resolved. This exists here just for a future headstart. output = torch.ops.fbgemm.f8f8bf16_blockwise( xq, weight.contiguous(), xs, weight_scale.contiguous(), bs_m, bs_n, bs_k ) output = output + bias if bias is not None else output output = output.view(*orig_shape[:-1], -1) del xq del xs ctx.weight = weight ctx.weight_scale = weight_scale ctx.block_size = [bs_m, bs_n, bs_k] return output @staticmethod def backward(ctx, grad_output): W_deq = weight_dequant(ctx.weight, ctx.weight_scale) grad_X = torch_matmul(grad_output, W_deq) del W_deq return grad_X, None, None, None, None @torch_compile def fp8_fbgemm_block_linear(X, weight, weight_scale, bias = None): return FP8_fbgemm_block_linear.apply(X, weight, weight_scale, bias) def test_has_fbgemm(): # We must manually check if the faster FBGEMM works on the specific GPU # For example RTX 5090 and RTX 4090 does not work # [TODO] Investigate with TorchAO why FBGEMM fails on consumer GPUs M, N, K = 128, 128, 128 xq = torch.ones(M, K, dtype = torch.float8_e4m3fn, device = "cuda") wq = xq M, K = xq.shape N, _ = wq.shape block_scale = torch.ones(M // 128, K // 128, dtype = torch.float32, device = "cuda") has_fbgemm = False try: out = torch.ops.fbgemm.f8f8bf16_blockwise(xq, wq, block_scale, block_scale) assert torch.unique(out).item() == 128 has_fbgemm = True del out except Exception as e: e = str(e) if "cutlass cannot initialize" in e.lower(): print( f"Unsloth: FBGEMM on the current GPU cannot load - will switch to Triton kernels" ) else: print( f"Unsloth: FBGEMM on the current GPU cannot load with error = {e} - will switch to Triton kernels" ) has_fbgemm = False del block_scale, xq torch.cuda.empty_cache() return has_fbgemm fp8_block_quant_linear = fp8_torch_block_quant_forward if "UNSLOTH_HAS_FBGEMM" not in os.environ: os.environ["UNSLOTH_HAS_FBGEMM"] = "0" try: import fbgemm_gpu # Older versions cause numerical imprecisions resulting in NaNs especially when X has high values in it. # This is both fast and accurate hence preferred. # This makes it 15% faster than the torchao implementation. if Version(fbgemm_gpu.__version__) >= Version("1.4.0"): # We must manually confirm if blockwise FBGEMM works! # This check is a must for consumer grade GPUs which fail if test_has_fbgemm(): os.environ["UNSLOTH_HAS_FBGEMM"] = "1" logger.info(f"Using fbgemm_gpu block quantized FP8 matmul") fp8_block_quant_linear = fp8_fbgemm_block_linear else: os.environ["UNSLOTH_HAS_FBGEMM"] = "0" except: pass @torch_compile def fp8_linear(X, weight, weight_scale, bias = None): if weight_scale.ndim == 2 and weight_scale.shape[1] > 1: # This is block quantized FP8 matmul out = fp8_block_quant_linear(X, weight, weight_scale) else: # Row quantized FP8 out = fbgemm_fp8_linear(X, weight, weight_scale, bias) return out def module_forward_patch(forward_function, scale_attr = "weight_scale"): def patched_forward(self, X): return forward_function(X, self.weight, getattr(self, scale_attr)) return patched_forward # Patch the forward functions of the layers (for compiled models) if FbgemmFp8Linear is not None: FbgemmFp8Linear.forward = module_forward_patch(fbgemm_fp8_linear, "weight_scale") if FP8Linear is not None: FP8Linear.forward = module_forward_patch(fp8_block_quant_linear, "weight_scale_inv")
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/__init__.py
unsloth/kernels/__init__.py
# 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. from .cross_entropy_loss import ( fast_cross_entropy_loss, post_patch_loss_function, patch_loss_functions, ) from .rms_layernorm import ( fast_rms_layernorm, patch_rms_layernorm, unpatch_rms_layernorm, ) from .layernorm import ( fast_layernorm, patch_layernorm, ) from .rope_embedding import fast_rope_embedding, inplace_rope_embedding from .swiglu import swiglu_fg_kernel, swiglu_DWf_DW_dfg_kernel from .geglu import ( geglu_exact_forward_kernel, geglu_exact_backward_kernel, geglu_approx_forward_kernel, geglu_approx_backward_kernel, ) from .fast_lora import ( get_lora_parameters, get_lora_parameters_bias, apply_lora_mlp_swiglu, apply_lora_mlp_geglu_exact, apply_lora_mlp_geglu_approx, apply_lora_qkv, apply_lora_o, fast_lora_forward, ) from .fp8 import * # This step is to ensure that we patch the FbgmemFP8Linear and FP8Linear's forward functions before the execution of model creation so that this applies to compiled non fast inference models as well from .utils import ( fast_dequantize, fast_gemv, QUANT_STATE, fast_linear_forward, matmul_lora, ) from .flex_attention import ( HAS_FLEX_ATTENTION, slow_attention_softcapping, slow_inference_attention_softcapping, create_flex_attention_causal_mask, create_flex_attention_sliding_window_mask, ) import os if "UNSLOTH_ZOO_IS_PRESENT" not in os.environ: try: print( "🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning." ) except: print("Unsloth: Will patch your computer to enable 2x faster free finetuning.") del os
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/__init__.py
unsloth/kernels/moe/__init__.py
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/benchmark/benchmark_fused_moe.py
unsloth/kernels/moe/benchmark/benchmark_fused_moe.py
import argparse import time from contextlib import nullcontext import torch from transformers import AutoConfig from transformers.models.llama4 import Llama4TextConfig from transformers.models.llama4.modeling_llama4 import Llama4TextMoe from transformers.models.qwen3_moe import Qwen3MoeConfig from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeSparseMoeBlock from triton.testing import do_bench from utils import ( create_kernel_configs, get_autotuner, post_process_results, postprocess_autotune_results, save_results, ) from grouped_gemm.kernels.autotuning import ( DEFAULT_K_BLOCK_SIZES, DEFAULT_M_BLOCK_SIZES, DEFAULT_N_BLOCK_SIZES, DEFAULT_NUM_STAGES, DEFAULT_NUM_WARPS, ) from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, KernelResult, TritonTuningContext, ) from grouped_gemm.reference.layers.llama4_moe import Llama4TritonTextMoe from grouped_gemm.reference.layers.qwen3_moe import Qwen3MoeFusedGroupedGEMMBlock SEED = 42 LLAMA4_ID = "meta-llama/Llama-4-Scout-17B-16E" QWEN3_MODEL_ID = "Qwen/Qwen3-30B-A3B" def run_benchmark_forward( ref_model: torch.nn.Module, tt_model: torch.nn.Module, config: AutoConfig, seqlen: int, dtype: torch.dtype, autotune: bool, kernel_config_fwd: KernelConfigForward = None, bs: int = 1, ): torch.manual_seed( SEED ) # Should not be needed when running using pytest -- autouse fixture in conftest.py device = "cuda" hidden_size = config.hidden_size X = torch.randn( bs, seqlen, hidden_size, dtype = dtype, device = device, requires_grad = True ) # Forward bench_forward_ref = lambda: ref_model(X) # noqa: E731 bench_forward_fused = lambda: tt_model(X) # noqa: E731 ref_forward_time = do_bench(bench_forward_ref) if not autotune: assert kernel_config_fwd is not None tuning_context = TritonTuningContext(kernel_config_fwd) else: tuning_context = nullcontext() with tuning_context: fused_forward_time = do_bench(bench_forward_fused) if (not autotune) and (not tuning_context.success): return 0, 1 print( f"Forward: ref {ref_forward_time:.4f}, fused {fused_forward_time:.4f}, speedup {ref_forward_time / fused_forward_time:.1f}x" ) return ref_forward_time, fused_forward_time def run_benchmark_backward( ref_model: torch.nn.Module, tt_model: torch.nn.Module, config: AutoConfig, seqlen: int, dtype: torch.dtype, bs = 1, ): torch.manual_seed( SEED ) # Should not be needed when running using pytest -- autouse fixture in conftest.py device = "cuda" hidden_size = config.hidden_size X = torch.randn( bs, seqlen, hidden_size, dtype = dtype, device = device, requires_grad = True ) X_test = X.detach().clone().requires_grad_(True) output, _ = ref_model(X) # Prevent autotuning forward pass from grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel _autotuned_grouped_gemm_forward_kernel.configs = ( _autotuned_grouped_gemm_forward_kernel.configs[:20] ) test_output, _ = tt_model(X_test) # Bench grad_output = torch.randn_like(output) bench_backward_ref = lambda: output.backward(grad_output, retain_graph = True) # noqa: E731 bench_backward_fused = lambda: test_output.backward(grad_output, retain_graph = True) # noqa: E731 ref_backward_time = do_bench( bench_backward_ref, grad_to_none = [X, *ref_model.parameters()] ) fused_backward_time = do_bench( bench_backward_fused, grad_to_none = [X_test, *tt_model.parameters()] ) print( f"Backward: ref {ref_backward_time:.4f}, fused {fused_backward_time:.4f}, speedup {ref_backward_time / fused_backward_time:.1f}x" ) return ref_backward_time, fused_backward_time def setup_model( config: Qwen3MoeConfig | Llama4TextConfig, dtype, permute_x, permute_y, autotune, kernel_config_fwd, kernel_config_bwd_dW, kernel_config_bwd_dX, dX_only = False, dW_only = False, overlap_router_shared = False, device = "cuda", ): if isinstance(config, Qwen3MoeConfig): ref_model = Qwen3MoeSparseMoeBlock(config).to(device, dtype) # Triton kernel grouped gemm version of MoE Block -- this is what we're testing tt_model = Qwen3MoeFusedGroupedGEMMBlock.from_hf( ref_model, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, dX_only = dX_only, dW_only = dW_only, ).to(device, dtype) elif isinstance(config, Llama4TextConfig): ref_model = Llama4TextMoe(config).to(device, dtype) tt_model = Llama4TritonTextMoe( config, overlap_router_shared = overlap_router_shared, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, dX_only = dX_only, dW_only = dW_only, ).to(device, dtype) else: raise ValueError(f"Unrecognized config {type(config).__name__}") return ref_model, tt_model def run_benchmark( mode: str, model_config: Qwen3MoeConfig | Llama4TextConfig, seqlen: int, dtype: torch.dtype, permute_x: bool, permute_y: bool, autotune: bool, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, overlap_router_shared: bool = False, results_dir: str = None, ): if autotune: autotuner = get_autotuner(mode) if mode == "dW": dW_only = True elif mode == "dX": dX_only = True else: dW_only = dX_only = False ref_model, tt_model = setup_model( model_config, dtype = dtype, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, dX_only = dX_only, dW_only = dW_only, overlap_router_shared = overlap_router_shared, ) if mode == "forward": ref_time, fused_time = run_benchmark_forward( ref_model, tt_model, config = model_config, seqlen = seqlen, dtype = dtype, autotune = autotune, kernel_config_fwd = kernel_config_fwd, ) else: ref_time, fused_time = run_benchmark_backward( ref_model, tt_model, config = model_config, seqlen = seqlen, dtype = dtype ) if autotune: if mode == "backward": autotuner_dW, autotuner_dX = autotuner postprocess_autotune_results( autotuner_dW, "dW", ref_time, fused_time, results_dir ) postprocess_autotune_results( autotuner_dX, "dX", ref_time, fused_time, results_dir ) else: postprocess_autotune_results( autotuner, mode, ref_time, fused_time, results_dir ) return ref_time, fused_time if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--results_dir", type = str, default = "benchmark_results") parser.add_argument("--model", type = str, choices = ["llama4", "qwen3"], required = True) parser.add_argument("--seqlen", type = int, default = 1024) parser.add_argument( "--dtype", type = str, choices = ["bfloat16", "float16"], default = "bfloat16" ) parser.add_argument("--permute_x", action = "store_true") parser.add_argument("--permute_y", action = "store_true") parser.add_argument("--autotune", action = "store_true") parser.add_argument("--overlap_router_shared", action = "store_true") parser.add_argument( "--BLOCK_SIZE_M", nargs = 2, type = int, default = [DEFAULT_M_BLOCK_SIZES[0], DEFAULT_M_BLOCK_SIZES[-1]], ) parser.add_argument( "--BLOCK_SIZE_N", nargs = 2, type = int, default = [DEFAULT_N_BLOCK_SIZES[0], DEFAULT_N_BLOCK_SIZES[-1]], ) parser.add_argument( "--BLOCK_SIZE_K", nargs = 2, type = int, default = [DEFAULT_K_BLOCK_SIZES[0], DEFAULT_K_BLOCK_SIZES[-1]], ) parser.add_argument( "--num_warps", nargs = 2, type = int, default = [DEFAULT_NUM_WARPS[0], DEFAULT_NUM_WARPS[-1]], ) parser.add_argument( "--num_stages", nargs = 2, type = int, default = [DEFAULT_NUM_STAGES[0], DEFAULT_NUM_STAGES[-1]], ) parser.add_argument( "--use_tma_load_w", action = "store_true" ) # No need to specify, will automatically parametrize these for each kernel config parser.add_argument( "--use_tma_load_x", action = "store_true" ) # No need to specify, will automatically parametrize these for each kernel config parser.add_argument( "--use_tma_load_dy", action = "store_true" ) # No need to specify, will automatically parametrize these for each kernel config parser.add_argument( "--mode", type = str, choices = ["forward", "backward", "dW", "dX"], default = "forward", ) args = parser.parse_args() args.dtype = getattr(torch, args.dtype) model_id = QWEN3_MODEL_ID if args.model == "qwen3" else LLAMA4_ID model_config = AutoConfig.from_pretrained(model_id) model_config = model_config.text_config if args.model == "llama4" else model_config mode = args.mode if args.autotune: # logging.basicConfig(level=logging.INFO) print( f"Benchmarking {model_id} {mode}: seqlen={args.seqlen}, dtype={args.dtype}, permute_x={args.permute_x}, permute_y={args.permute_y}, autotune" ) start_time = time.time() ref_time, fused_time = run_benchmark( args.mode, model_config, seqlen = args.seqlen, dtype = args.dtype, permute_x = args.permute_x, permute_y = args.permute_y, autotune = args.autotune, overlap_router_shared = args.overlap_router_shared, results_dir = args.results_dir, ) end_time = time.time() print(f"Total time: {end_time - start_time:.4f} seconds") # NOTE: better to use autotuner for now, since the MoE block needs 2 different kernel configs for forward (2 grouped gemms, gate_up_proj and down_proj) # and the backward pass needs 4 different kernel configs (2 grouped gemms each for dW and dX) # The benchmark only supports 1 kernel config at a time so the same config will be used for both grouped gemms, which is suboptimal. else: assert False, "Use autotune for now" kernel_configs = create_kernel_configs(args, args.permute_x, args.permute_y) print(f"Running {len(kernel_configs)} kernel configs") default_kernel_config_fwd = KernelConfigForward( permute_x = args.permute_x, permute_y = args.permute_y ) default_kernel_config_bwd_dW = KernelConfigBackward_dW( permute_x = args.permute_x, permute_y = args.permute_y ) default_kernel_config_bwd_dX = KernelConfigBackward_dX( permute_x = args.permute_x, permute_y = args.permute_y ) results = [] for kernel_config in kernel_configs: if args.mode == "forward": kernel_config_fwd = kernel_config kernel_config_bwd_dW = default_kernel_config_bwd_dW kernel_config_bwd_dX = default_kernel_config_bwd_dX elif args.mode == "dW": kernel_config_fwd = default_kernel_config_fwd kernel_config_bwd_dW = kernel_config kernel_config_bwd_dX = default_kernel_config_bwd_dX elif args.mode == "dX": kernel_config_fwd = default_kernel_config_fwd kernel_config_bwd_dW = default_kernel_config_bwd_dW kernel_config_bwd_dX = kernel_config else: raise ValueError(f"Invalid mode: {args.mode}") print( f"Benchmarking {model_id} {args.mode} with seqlen={args.seqlen}, dtype={args.dtype}, permute_x={args.permute_x}, permute_y={args.permute_y}, kernel_config_fwd={kernel_config_fwd}, kernel_config_bwd_dW={kernel_config_bwd_dW}, kernel_config_bwd_dX={kernel_config_bwd_dX}" ) ref_time, fused_time = run_benchmark( args.mode, model_config, seqlen = args.seqlen, dtype = args.dtype, permute_x = kernel_config.permute_x, permute_y = kernel_config.permute_y, autotune = False, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, ) results.append( KernelResult( torch_time = ref_time, triton_time = fused_time, speedup = ref_time / fused_time, kernel_config = kernel_config, ) ) df = post_process_results( results, args.mode, args.seqlen, args.dtype, args.autotune ) save_results( df, args.results_dir, args.mode, args.seqlen, args.dtype, args.autotune )
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/benchmark/utils.py
unsloth/kernels/moe/benchmark/utils.py
import argparse import datetime import json import logging import math import os from itertools import product import pandas as pd import torch from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, KernelResult, ) SEED = 42 def create_merged_results( df: pd.DataFrame, mode: str, seqlen: int, dtype: torch.dtype, autotune: bool ): kernel_result_cols = df.columns.to_list() test_config_dict = { "mode": mode, "seqlen": seqlen, "dtype": dtype, "autotune": autotune, } test_config_cols = list(test_config_dict.keys()) for col in test_config_cols: df[col] = test_config_dict[col] # Reorder columns so that test config cols are first df = df[test_config_cols + kernel_result_cols] return df def post_process_results( results: list[KernelResult], mode: str, seqlen: int, dtype: torch.dtype, autotune: bool, ): df = KernelResult.to_dataframe(results, sort_by = "speedup") df = create_merged_results(df, mode, seqlen, dtype, autotune) return df def save_results( df: pd.DataFrame, results_dir: str, mode: str, seqlen: int, dtype: torch.dtype, autotune: bool, ): dt = datetime.datetime.now().strftime("%Y%m%d_%H%M") save_dir = f"{results_dir}/{mode}" save_path = f"{save_dir}/{dt}_{seqlen}_{str(dtype).split('.')[-1]}.csv" if not os.path.exists(save_dir): os.makedirs(save_dir) print(f"Saving results to {save_path}") df.to_csv(save_path, index = False) def create_kernel_configs(args: argparse.Namespace, permute_x: bool, permute_y: bool): block_m_range = power_of_two_range(args.BLOCK_SIZE_M[0], args.BLOCK_SIZE_M[1]) block_n_range = power_of_two_range(args.BLOCK_SIZE_N[0], args.BLOCK_SIZE_N[1]) block_k_range = power_of_two_range(args.BLOCK_SIZE_K[0], args.BLOCK_SIZE_K[1]) num_warps_range = multiples_of_range(args.num_warps[0], args.num_warps[1], step = 2) num_stages_range = multiples_of_range( args.num_stages[0], args.num_stages[1], step = 1 ) mode = args.mode kernel_configs = [] for ( block_m, block_n, block_k, num_warps, num_stages, tma_load_a, tma_load_b, ) in product( block_m_range, block_n_range, block_k_range, num_warps_range, num_stages_range, [True, False], [True, False], ): if mode == "forward": kernel_config = KernelConfigForward( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = num_warps, num_stages = num_stages, use_tma_load_w = tma_load_a, use_tma_load_x = tma_load_b, permute_x = permute_x, permute_y = permute_y, ) elif mode == "dW": kernel_config = KernelConfigBackward_dW( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = num_warps, num_stages = num_stages, use_tma_load_dy = tma_load_a, use_tma_load_x = tma_load_b, permute_x = permute_x, permute_y = permute_y, ) elif mode == "dX": kernel_config = KernelConfigBackward_dX( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = num_warps, num_stages = num_stages, use_tma_load_dy = tma_load_a, use_tma_load_w = tma_load_b, permute_x = permute_x, permute_y = permute_y, ) else: raise ValueError(f"Invalid mode: {mode}") kernel_configs.append(kernel_config) logging.info(f"Pruning {len(kernel_configs)} kernel configs") pruned_configs = [] for config in kernel_configs: if mode == "forward": if permute_x and config.use_tma_load_x: continue elif mode == "dW": if permute_x and config.use_tma_load_x: continue if permute_y and config.use_tma_load_dy: continue elif mode == "dX": if permute_y and config.use_tma_load_dy: continue pruned_configs.append(config) logging.info(f"After pruning, {len(pruned_configs)} kernel configs") return pruned_configs def power_of_two_range(start, end): start = math.log2(start) end = math.log2(end) return [2**i for i in range(int(start), int(end) + 1)] def multiples_of_range(start, end, step = 1): return list(range(start, end + step, step)) def map_key_to_args(key, mode): pass def save_autotune_results(autotune_cache, mode, ref_time, fused_time, results_dir): device_name = torch.cuda.get_device_name().replace(" ", "_") dt = datetime.datetime.now().strftime("%Y%m%d_%H%M") save_dir = f"{results_dir}/{mode}/autotune/{dt}/{device_name}" if not os.path.exists(save_dir): os.makedirs(save_dir) for key, config in autotune_cache.items(): key = [ str(k) if not "torch" in str(k) else str(k.split("torch.")[-1]) for k in key ] filename = "_".join(key) save_path = f"{save_dir}/{filename}.json" print(f"Saving autotune results to {save_path}") with open(save_path, "w") as f: result = { **config.all_kwargs(), "ref_time": ref_time, "fused_time": fused_time, } json.dump(result, f) def get_autotuner(mode): if mode == "forward": from grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel return _autotuned_grouped_gemm_forward_kernel elif mode == "dW": from grouped_gemm.kernels.backward import _autotuned_grouped_gemm_dW_kernel return _autotuned_grouped_gemm_dW_kernel elif mode == "dX": from grouped_gemm.kernels.backward import _autotuned_grouped_gemm_dX_kernel return _autotuned_grouped_gemm_dX_kernel elif mode == "backward": from grouped_gemm.kernels.backward import ( _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel, ) return _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel else: raise ValueError(f"Invalid mode: {mode}") def postprocess_autotune_results(autotuner, mode, ref_time, fused_time, results_dir): for key, value in autotuner.cache.items(): print(f"{mode} {key}: {value.all_kwargs()}") save_autotune_results( autotuner.cache, mode = mode, ref_time = ref_time, fused_time = fused_time, results_dir = results_dir, )
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/tests/test_grouped_gemm.py
unsloth/kernels/moe/tests/test_grouped_gemm.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. from dataclasses import asdict import pytest import torch from grouped_gemm.interface import ( grouped_gemm, grouped_gemm_dW, grouped_gemm_dX, grouped_gemm_forward, ) from grouped_gemm.kernels.tuning import ( KernelConfig, KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from grouped_gemm.reference.moe_ops import ( calculate_topk, get_routing_indices, permute, torch_grouped_gemm, unpermute, ) from .common import ( DATA_CONFIGS, KERNEL_CONFIGS_FWD, LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG, SMALL_MODEL_CONFIGS, TOLERANCE, DataConfig, KERNEL_CONFIGS_BWD_dW, KERNEL_CONFIGS_BWD_dX, ModelConfig, make_inputs, ) SEED = 0 # Only certain combinations of permute_x, permute_y, use_W1 are valid. # use_W1 => first grouped GEMM in a fused MoE MLP # use_W2 => second grouped GEMM in a fused MoE MLP # permute_x => permute the input to the grouped GEMM, only done for the first grouped GEMM # permute_y => permute the output of the grouped GEMM, only done for the second grouped GEMM # fuse_mul_post => fuse the multiplication of topk weights in the epilogue of the second grouped GEMM; only used for inference, not currently tested def check_valid_config( permute_x, permute_y, use_W1, fuse_mul_post = False, is_backward = False, verbose = False ): use_W2 = not use_W1 if permute_x and permute_y: if verbose: print(f"Skipping test: {permute_x = } {permute_y = }") return False if use_W2 and permute_x: if verbose: print(f"Skipping test: {permute_x = } {use_W2 = }") return False if use_W1 and permute_y: if verbose: print(f"Skipping test: {permute_y = } {use_W1 = }") return False if fuse_mul_post and use_W1: if verbose: print(f"Skipping test: {fuse_mul_post = } {use_W1 = }") return False if is_backward and fuse_mul_post: if verbose: print(f"Skipping test: {fuse_mul_post = } {is_backward = }") return False return True """ grouped_gemm_forward permute_x: typically in a fused MoE MLP, we can fuse the permutation of hidden states (X) from token order to expert grouped order needed for grouped GEMM by directly loading X in permuted order rather than launching a separate permutation kernel. permute_y: We can also fuse the unpermutation of tokens after the second grouped GEMM to restore to original token order. This is fused into the second grouped GEMM by directly storing the output in unpermuted order. fuse_mul: We can also fuse the multiplication of topk weights in the epilogue of the second grouped GEMM. Note that this is only supported for inference and not training, although this may change in the future. use_W1 test the shapes for the first grouped GEMM in a fused MoE MLP use_W2 = `not use_W1` tests the shapes for the second grouped GEMM in a fused MoE MLP Given the above, only certain combinations are valid: - use_W1 is always False when permute_y is True since we only permute the second grouped GEMM - use_W2 is always False when permute_x is True since we only permute the first grouped GEMM - only one of permute_x and permute_y can be True - fuse_mul is only True if permute_y is also True See `check_valid_config` for more details. """ def _test_grouped_gemm_forward( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, # W1 -> first grouped GEMM in a fused MoE MLP, not W1 -> second grouped GEMM in a fused MoE MLP fuse_mul_post: bool = False, flatten: bool = True, # Manually tuned parameters use_tma_load_w: bool = False, use_tma_load_x: bool = False, use_tma_store: bool = False, BLOCK_SIZE_M: int = None, BLOCK_SIZE_N: int = None, BLOCK_SIZE_K: int = None, num_warps: int = None, num_stages: int = None, # Autotuning parameters autotune: bool = False, num_autotune_configs: int = None, # Flag to manually enable TMA store allow_tma_store: bool = False, use_autograd: bool = False, ): if not check_valid_config( permute_x, permute_y, use_W1 = use_W1, fuse_mul_post = fuse_mul_post ): pytest.skip( f"Skipping test due to invalid config: {permute_x = } {permute_y = } {use_W1 = } {fuse_mul_post = }" ) if use_tma_store and not allow_tma_store: pytest.skip("TMA store needs to be debugged due to non-deterministic behavior") X1, X2, W1, W2, gating_output = make_inputs( M = data_config.bs * data_config.seq_len, N = model_config.intermediate_size, K = model_config.hidden_size, E = model_config.num_experts, topk = model_config.topk, dtype = data_config.dtype, ) topk = model_config.topk use_sigmoid = model_config.use_sigmoid renormalize = model_config.renormalize X = X1 if use_W1 else X2 num_tokens = data_config.bs * data_config.seq_len E, K, N = W2.shape # E = num_experts, K = hidden_size, N = intermediate_size assert W1.shape == (E, 2 * N, K) W = W1 if use_W1 else W2 if use_W1: assert X.shape == ( num_tokens, K, ), f"X.shape: {X.shape}, num_tokens: {num_tokens}, K: {K}" else: assert X.shape == ( num_tokens * topk, N, ), f"X.shape: {X.shape}, num_tokens: {num_tokens}, topk: {topk}, N: {N}" total_tokens = num_tokens * topk output_shape = (total_tokens, 2 * N) if use_W1 else (total_tokens, K) topk_weights, topk_ids = calculate_topk( gating_output, topk, use_sigmoid = use_sigmoid, renormalize = renormalize ) topk_weights = topk_weights.view(-1) # num_tokens * topk topk_ids = topk_ids.view(-1) # num_tokens * topk expert_token_counts, gather_indices = get_routing_indices(topk_ids, num_experts = E) assert len(gather_indices) == total_tokens assert len(expert_token_counts) == E atol, rtol = TOLERANCE[X.dtype] Xperm = permute(X, gather_indices, topk) Xref = Xperm assert ( Xperm.shape == (total_tokens, K) if use_W1 else (total_tokens, N) ), f"Xperm.shape: {Xperm.shape}, total_tokens: {total_tokens}, K: {K}" ref_output = torch_grouped_gemm(X = Xref, W = W, m_sizes = expert_token_counts) if permute_x: X_test = X else: X_test = Xperm # No need to run all configs for tests, otherwise takes too long if autotune: from grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel if num_autotune_configs is not None: _autotuned_grouped_gemm_forward_kernel.configs = ( _autotuned_grouped_gemm_forward_kernel.configs[:num_autotune_configs] ) # Use autograd.Function interface if use_autograd: from grouped_gemm.interface import grouped_gemm kernel_config_fwd = KernelConfigForward( BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, permute_x = permute_x, permute_y = permute_y, fuse_mul_post = fuse_mul_post, use_tma_load_w = use_tma_load_w, use_tma_load_x = use_tma_load_x, use_tma_store = use_tma_store, ) test_output = grouped_gemm( X = X_test, W = W, topk = topk, m_sizes = expert_token_counts, gather_indices = gather_indices, topk_weights = topk_weights if fuse_mul_post else None, permute_x = permute_x, permute_y = permute_y, fuse_mul_post = fuse_mul_post, kernel_config_fwd = kernel_config_fwd, autotune = autotune, is_first_gemm = use_W1, ) # Use manual interface else: test_output = grouped_gemm_forward( X = X_test, W = W, topk = topk, m_sizes = expert_token_counts, gather_indices = gather_indices, topk_weights = topk_weights if fuse_mul_post else None, permute_x = permute_x, permute_y = permute_y, fuse_mul_post = fuse_mul_post, use_tma_load_w = use_tma_load_w, use_tma_load_x = use_tma_load_x, use_tma_store = use_tma_store, autotune = autotune, BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, flatten = flatten, ) assert ref_output.shape == output_shape assert test_output.shape == output_shape if permute_y: ref_output = unpermute(ref_output, gather_indices) if fuse_mul_post: # if we don't permute_y, then test output is permuted with topk weights applied # the ref output needs to be unpermuted before multiplying by topk weights since topk weights are in token order if not permute_y: ref_output = unpermute(ref_output, gather_indices) test_output = unpermute(test_output, gather_indices) ref_output = ref_output * topk_weights[:, None] assert torch.allclose( ref_output, test_output, atol = atol, rtol = rtol ), f"Grouped gemm forward failed: {(ref_output - test_output).abs().max().item():.6f}" # NOTE: Fuse multiplication of topk weights is only supported for inference and not training, although this may change in the future; not currently tested. @pytest.mark.parametrize( "kernel_config", KERNEL_CONFIGS_FWD, ids = lambda x: x.to_string(include_tuning_params = True, include_tma = True), ) @pytest.mark.parametrize( "model_config", SMALL_MODEL_CONFIGS + [QWEN_MODEL_CONFIG, LLAMA_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_forward_manual( data_config: DataConfig, model_config: ModelConfig, kernel_config: KernelConfigForward, use_W1: bool, ): _test_grouped_gemm_forward( data_config = data_config, model_config = model_config, use_W1 = use_W1, **asdict(kernel_config), ) @pytest.mark.parametrize( "kernel_config", KERNEL_CONFIGS_FWD, ids = lambda x: x.to_string(include_tuning_params = True, include_tma = True), ) @pytest.mark.parametrize( "model_config", SMALL_MODEL_CONFIGS + [QWEN_MODEL_CONFIG, LLAMA_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_forward_manual_autograd( data_config: DataConfig, model_config: ModelConfig, kernel_config: KernelConfigForward, use_W1: bool, ): _test_grouped_gemm_forward( data_config = data_config, model_config = model_config, use_W1 = use_W1, use_autograd = True, **asdict(kernel_config), ) @pytest.mark.parametrize( "num_autotune_configs", [10], ids = lambda x: f"num_autotune_configs={x}" ) @pytest.mark.parametrize( "permute_x", [True, False], ids = lambda x: "permute_x" if x else "" ) @pytest.mark.parametrize( "permute_y", [True, False], ids = lambda x: "permute_y" if x else "" ) @pytest.mark.parametrize( "model_config", [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_forward_autotune( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, num_autotune_configs: int, ): _test_grouped_gemm_forward( data_config = data_config, model_config = model_config, permute_x = permute_x, permute_y = permute_y, use_W1 = use_W1, num_autotune_configs = num_autotune_configs, autotune = True, use_autograd = False, ) @pytest.mark.parametrize( "num_autotune_configs", [10], ids = lambda x: f"num_autotune_configs={x}" ) @pytest.mark.parametrize( "permute_x", [True, False], ids = lambda x: "permute_x" if x else "" ) @pytest.mark.parametrize( "permute_y", [True, False], ids = lambda x: "permute_y" if x else "" ) @pytest.mark.parametrize( "model_config", [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_forward_autotune_autograd( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, num_autotune_configs: int, ): _test_grouped_gemm_forward( data_config = data_config, model_config = model_config, permute_x = permute_x, permute_y = permute_y, use_W1 = use_W1, num_autotune_configs = num_autotune_configs, autotune = True, use_autograd = True, ) """ grouped_gemm_backward_dX use_W1 test the shapes for the first grouped GEMM in a fused MoE MLP use_W2 = `not use_W1` tests the shapes for the second grouped GEMM in a fused MoE MLP Only certain combinations of permute_x, permute_y, and fuse_mul are supported. Typically in a fused MoE MLP, we can fuse the permutation of hidden states (X) from token order to expert grouped order needed for grouped GEMM by directly loading X in permuted order rather than launching a separate permutation kernel. We can also fuse the unpermutation of tokens after the second grouped GEMM to restore to original token order. This is fused into the second grouped GEMM by directly storing the output in unpermuted order. Hence the following conditions: - If use_W1 there are two cases: - permute_x is False and topk > 1: - dX_test is still in permuted order and has shape (total_tokens, K) - it needs to be unpermuted and summed across topk before comparing to ref_grad - permute_x is True: - dX_test is already unpermuted and summed across topk with shape (num_tokens, K) - no further processing is needed - permute_x is False and topk == 1: - dX_test needs to be permuted, no need to sum since topk == 1 - If use_W2: - permute_x is always False - if permute_y: - grad_output needs to be unpermuted before passing to grouped_gemm_dX - dX_test is permuted and has shape (total_tokens, N) - it needs to be unpermuted before comparing to ref_grad or can be compared directly to Xperm.grad - if not permute_y: - dX_test is not permuted and has shape (total_tokens, N) - no further processing is needed """ def _test_grouped_gemm_backward_dX( data_config: DataConfig, model_config: ModelConfig, permute_x: bool = False, permute_y: bool = False, use_tma_load_dy: bool = False, use_tma_load_w: bool = False, use_tma_store: bool = False, use_W1: bool = True, autotune: bool = False, num_autotune_configs: int = None, BLOCK_SIZE_M: int = None, BLOCK_SIZE_N: int = None, BLOCK_SIZE_K: int = None, num_warps: int = None, num_stages: int = None, flatten: bool = True, allow_tma_store: bool = False, use_autograd: bool = False, fuse_mul_post: bool = False, ): if not check_valid_config(permute_x, permute_y, use_W1 = use_W1, is_backward = True): pytest.skip( f"Skipping test due to invalid config: {permute_x = } {permute_y = } {use_W1 = }" ) if use_tma_store and not allow_tma_store: pytest.skip("TMA store needs to be debugged due to non-deterministic behavior") if ( autotune and model_config.intermediate_size <= 128 and model_config.hidden_size <= 128 ): pytest.skip("Skipping autotuning for small model configs") # Prevent OOM for large intermediate sizes if model_config.intermediate_size > 2048: model_config.intermediate_size = 1024 if model_config.hidden_size > 2048: model_config.hidden_size = 1024 use_W2 = not use_W1 X1, X2, W1, W2, gating_output = make_inputs( M = data_config.bs * data_config.seq_len, N = model_config.intermediate_size, K = model_config.hidden_size, E = model_config.num_experts, topk = model_config.topk, dtype = data_config.dtype, requires_grad = True, ) topk = model_config.topk num_experts = model_config.num_experts use_sigmoid = model_config.use_sigmoid renormalize = model_config.renormalize X = X1 if use_W1 else X2 num_tokens = data_config.bs * data_config.seq_len total_tokens = num_tokens * topk E, K, N = W2.shape # E = num_experts, K = hidden_size, N = intermediate_size assert W1.shape == (E, 2 * N, K) W = W1 if use_W1 else W2 if use_W1: assert X.shape == ( num_tokens, K, ), f"X.shape: {X.shape}, num_tokens: {num_tokens}, K: {K}" else: assert X.shape == ( total_tokens, N, ), f"X.shape: {X.shape}, total_tokens: {total_tokens}, N: {N}" W_test = W.detach().clone().requires_grad_(True) topk_weights, topk_ids = calculate_topk( gating_output, topk, use_sigmoid = use_sigmoid, renormalize = renormalize ) topk_weights = topk_weights.view(-1) # num_tokens * topk topk_ids = topk_ids.view(-1) # num_tokens * topk expert_token_counts, gather_indices = get_routing_indices(topk_ids, num_experts = E) assert len(gather_indices) == total_tokens assert len(expert_token_counts) == num_experts atol, rtol = TOLERANCE[X.dtype] Xperm = permute(X, gather_indices, topk) # Need to retain grad otherwise grad is not propagated X.retain_grad() W.retain_grad() Xperm.retain_grad() assert Xperm.shape == (total_tokens, K) if use_W1 else (total_tokens, N) output_shape = (total_tokens, 2 * N) if use_W1 else (total_tokens, K) ref_output = torch_grouped_gemm(X = Xperm, W = W, m_sizes = expert_token_counts) assert ( ref_output.shape == output_shape ), f"ref_output.shape: {ref_output.shape}, output_shape: {output_shape}" if permute_y: ref_output = unpermute(ref_output, gather_indices) grad_output = torch.randn_like(ref_output) ref_output.backward(grad_output) assert X.grad is not None assert W.grad is not None ref_grad = Xperm.grad if autotune: # No need to run all configs for autotuning from grouped_gemm.kernels.backward import _autotuned_grouped_gemm_dX_kernel if num_autotune_configs is not None: _autotuned_grouped_gemm_dX_kernel.configs = ( _autotuned_grouped_gemm_dX_kernel.configs[:num_autotune_configs] ) if use_autograd: from grouped_gemm.interface import grouped_gemm if not autotune: kernel_config_fwd = KernelConfigForward() kernel_config_bwd_dX = KernelConfigBackward_dX( use_tma_load_dy = use_tma_load_dy, use_tma_load_w = use_tma_load_w, use_tma_store = use_tma_store, BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, ) kernel_config_bwd_dW = KernelConfigBackward_dW() else: from grouped_gemm.kernels.backward import ( _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel, ) from grouped_gemm.kernels.forward import ( _autotuned_grouped_gemm_forward_kernel, ) if num_autotune_configs is not None: _autotuned_grouped_gemm_dX_kernel.configs = ( _autotuned_grouped_gemm_dX_kernel.configs[:num_autotune_configs] ) _autotuned_grouped_gemm_forward_kernel.configs = ( _autotuned_grouped_gemm_forward_kernel.configs[ :num_autotune_configs ] ) kernel_config_fwd = None kernel_config_bwd_dX = None X_ = ( X.detach().clone().requires_grad_(True) if permute_x else Xperm.detach().clone().requires_grad_(True) ) test_output = grouped_gemm( X = X_, W = W_test, m_sizes = expert_token_counts, gather_indices = gather_indices, topk = topk, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dX = kernel_config_bwd_dX, is_first_gemm = use_W1, dX_only = True, ) assert ( test_output.shape == ref_output.shape ), f"test_output.shape: {test_output.shape}, ref_output.shape: {ref_output.shape}" assert torch.allclose( test_output, ref_output, atol = atol, rtol = rtol ), f"Grouped gemm backward_dX forward outputs mismatch: {(test_output - ref_output).abs().max().item():.6f}" test_output.backward(grad_output) assert X_.grad is not None # NOTE:need to handle grad differenlty in this case due to errors arising to do how torch autograd handles unpermute and sum reduction # the grad of Xperm unpermuted and reduced across topk should match X_.grad # However, both will have a numerical difference with that of ref_grad # This is due to the fact that torch autograd handles unpermute and sum reduction differently see: https://discuss.pytorch.org/t/permute-unpermute-gradient/219557 else: if permute_x and use_W1: X_grad_unperm = unpermute(Xperm.grad, gather_indices) manual_grad_check = X_grad_unperm.view(num_tokens, topk, K).sum(dim = 1) assert ( manual_grad_check.shape == X_.grad.shape ), f"manual_grad_check.shape: {manual_grad_check.shape}, X_.grad.shape: {X_.grad.shape}" assert torch.allclose( manual_grad_check, X_.grad, atol = atol, rtol = rtol ), f"Grouped gemm backward_dX forward outputs mismatch: {(manual_grad_check - X_.grad).abs().max().item():.6f}" manual_diff = (X_.grad - manual_grad_check).abs().max().item() autograd_diff = (X_.grad - X.grad).abs().max().item() print(f"manual_diff: {manual_diff:.6f}, autograd_diff: {autograd_diff:.6f}") else: assert torch.allclose( X_.grad, ref_grad, atol = atol, rtol = rtol ), f"Grouped gemm backward_dX forward outputs mismatch: {(X_.grad - ref_grad).abs().max().item():.6f}" return else: dX_test = grouped_gemm_dX( dY = grad_output, W = W_test, gather_indices = gather_indices, m_sizes = expert_token_counts, topk = topk, permute_x = permute_x, permute_y = permute_y, use_tma_load_w = use_tma_load_w, use_tma_load_dy = use_tma_load_dy, use_tma_store = use_tma_store, autotune = autotune, BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, flatten = flatten, # debug=True, ) # if permute_x and use_W1 (first grouped GEMM) then the kernel should have unpermuted the dX # therefore we need to unpermute the ref_grad to compare to the output of the kernel if permute_x and use_W1: ref_grad = unpermute(ref_grad, gather_indices) assert ( ref_grad.shape == dX_test.shape ), f"Grouped gemm manual backward_dX outputs mismatch: ref_grad: {ref_grad.shape}, dX_test: {dX_test.shape}" diff = (ref_grad - dX_test).abs().max().item() assert torch.allclose( ref_grad, dX_test, atol = atol, rtol = rtol ), f"Grouped gemm manual backward_dX outputs mismatch: {diff:.6f}" if permute_x and use_W1: # Show that reduction results in diffs # First calculate X.grad manually by backpropping through unpermuted ref_grad dX_ref_check = ref_grad.view(num_tokens, topk, K).sum(dim = 1) # Do the same for the actual output of the kernel dX_test_check = dX_test.view(num_tokens, topk, K).sum(dim = 1) # Show diffs for each combination diff_ref_check = (X.grad - dX_ref_check).abs().max().item() diff_test_check = (X.grad - dX_test_check).abs().max().item() diff_check_test = (dX_ref_check - dX_test_check).abs().max().item() print( f"diff_ref_check: {diff_ref_check:.6f}, diff_test_check: {diff_test_check:.6f}, diff_check_test: {diff_check_test:.6f}" ) # NOTE: We reduce the size of the Llama4 model configs to prevent OOM # Important to note that for the full model size (5120, 8192), the tests do result in diffs on the order of 1e-2. @pytest.mark.parametrize( "kernel_config", KERNEL_CONFIGS_BWD_dX, ids = lambda x: x.to_string(include_tuning_params = True, include_tma = True), ) @pytest.mark.parametrize( "model_config", SMALL_MODEL_CONFIGS[:1] + [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dX_manual( data_config: DataConfig, model_config: ModelConfig, kernel_config: KernelConfigBackward_dX, use_W1: bool, ): _test_grouped_gemm_backward_dX( data_config = data_config, model_config = model_config, use_W1 = use_W1, use_autograd = False, **asdict(kernel_config), ) @pytest.mark.parametrize( "kernel_config", KERNEL_CONFIGS_BWD_dX, ids = lambda x: x.to_string(include_tuning_params = True, include_tma = True), ) @pytest.mark.parametrize( "model_config", SMALL_MODEL_CONFIGS[:1] + [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dX_manual_autograd( data_config: DataConfig, model_config: ModelConfig, kernel_config: KernelConfigBackward_dX, use_W1: bool, ): _test_grouped_gemm_backward_dX( data_config = data_config, model_config = model_config, use_W1 = use_W1, use_autograd = True, **asdict(kernel_config), ) @pytest.mark.parametrize( "num_autotune_configs", [20], ids = lambda x: f"num_autotune_configs={x}" ) @pytest.mark.parametrize( "permute_x", [True, False], ids = lambda x: "permute_x" if x else "" ) @pytest.mark.parametrize( "permute_y", [True, False], ids = lambda x: "permute_y" if x else "" ) @pytest.mark.parametrize( "model_config", [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dX_autotune( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, num_autotune_configs: int, ): # TMA loads / stores will be autotuned _test_grouped_gemm_backward_dX( data_config = data_config, model_config = model_config, permute_x = permute_x, permute_y = permute_y, use_W1 = use_W1, autotune = True, use_autograd = False, num_autotune_configs = num_autotune_configs, ) @pytest.mark.parametrize( "num_autotune_configs", [20], ids = lambda x: f"num_autotune_configs={x}" ) @pytest.mark.parametrize( "permute_x", [True, False], ids = lambda x: "permute_x" if x else "" ) @pytest.mark.parametrize( "permute_y", [True, False], ids = lambda x: "permute_y" if x else "" ) @pytest.mark.parametrize( "model_config", [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dX_autotune_autograd( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, num_autotune_configs: int, ): # TMA loads / stores will be autotuned _test_grouped_gemm_backward_dX( data_config = data_config, model_config = model_config, permute_x = permute_x, permute_y = permute_y, use_W1 = use_W1, autotune = True, use_autograd = True, num_autotune_configs = num_autotune_configs, ) def _test_grouped_gemm_backward_dW( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, use_tma_load_dy: bool = False, use_tma_load_x: bool = False, use_tma_store: bool = False, BLOCK_SIZE_M: int = None, BLOCK_SIZE_N: int = None, BLOCK_SIZE_K: int = None, num_warps: int = None, num_stages: int = None, flatten: bool = True, autotune: bool = False, num_autotune_configs: int = None, allow_tma_store: bool = False, debug: bool = False, fuse_mul_post: bool = False, # Unused for backward_dW use_autograd: bool = False, ): if not check_valid_config( permute_x, permute_y, fuse_mul_post = fuse_mul_post, use_W1 = use_W1, is_backward = True, ): pytest.skip( f"Skipping test due to invalid config: {permute_x = } {permute_y = } {use_W1 = }" ) if use_tma_store and not allow_tma_store: pytest.skip("TMA store needs to be debugged due to non-deterministic behavior") X1, X2, W1, W2, gating_output = make_inputs( M = data_config.bs * data_config.seq_len, N = model_config.intermediate_size, K = model_config.hidden_size, E = model_config.num_experts, topk = model_config.topk, dtype = data_config.dtype, requires_grad = True, ) topk = model_config.topk num_experts = model_config.num_experts use_sigmoid = model_config.use_sigmoid renormalize = model_config.renormalize X = X1 if use_W1 else X2 num_tokens = data_config.bs * data_config.seq_len E, K, N = W2.shape # E = num_experts, K = hidden_size, N = intermediate_size
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
true
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/tests/moe_utils.py
unsloth/kernels/moe/tests/moe_utils.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. from dataclasses import dataclass, fields import torch import torch.nn as nn from huggingface_hub import HfApi from huggingface_hub.utils import _safetensors from transformers.models.qwen3_moe.configuration_qwen3_moe import Qwen3MoeConfig from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeSparseMoeBlock from grouped_gemm.interface import grouped_gemm from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from grouped_gemm.reference.layers.qwen3_moe import ( GroupedGEMMResult, Qwen3MoeGroupedGEMMBlock, ) from grouped_gemm.reference.moe_ops import permute, unpermute def rebind_experts_to_shared_buffer( moe_block: Qwen3MoeSparseMoeBlock, config: Qwen3MoeConfig ): num_experts = config.num_experts hidden_size = config.hidden_size interm_size = config.moe_intermediate_size device = moe_block.experts[0].down_proj.weight.device dtype = moe_block.experts[0].down_proj.weight.dtype buffer_up = torch.empty( num_experts, interm_size, hidden_size, device = device, dtype = dtype ) buffer_gate = torch.empty( num_experts, interm_size, hidden_size, device = device, dtype = dtype ) buffer_down = torch.empty( num_experts, hidden_size, interm_size, device = device, dtype = dtype ) # Step 2: Copy existing expert weights into buffers for i, expert in enumerate(moe_block.experts): buffer_up[i].copy_(expert.up_proj.weight.data) buffer_gate[i].copy_(expert.gate_proj.weight.data) buffer_down[i].copy_(expert.down_proj.weight.data) # Step 3: Rebind expert weights to views in shared buffer for i, expert in enumerate(moe_block.experts): expert.up_proj.weight = torch.nn.Parameter(buffer_up[i]) expert.gate_proj.weight = torch.nn.Parameter(buffer_gate[i]) expert.down_proj.weight = torch.nn.Parameter(buffer_down[i]) return buffer_up, buffer_gate, buffer_down def get_expert_metadata(model_id: str): api = HfApi() metadata: _safetensors.SafetensorsRepoMetadata = api.get_safetensors_metadata( model_id ) return metadata.files_metadata def clone_experts( moe_block: Qwen3MoeSparseMoeBlock, config: Qwen3MoeConfig, copy: bool = True ): down_projs = torch.empty( config.num_experts, config.hidden_size, config.moe_intermediate_size ) up_projs = torch.empty( config.num_experts, config.moe_intermediate_size, config.hidden_size ) gate_projs = torch.empty( config.num_experts, config.moe_intermediate_size, config.hidden_size ) for expert_idx, expert in enumerate(moe_block.experts): down_projs[expert_idx].copy_(expert.down_proj.weight.data) up_projs[expert_idx].copy_(expert.up_proj.weight.data) gate_projs[expert_idx].copy_(expert.gate_proj.weight.data) return gate_projs, up_projs, down_projs @dataclass class ForwardResult: output: torch.Tensor router_logits: torch.Tensor X: torch.Tensor # When using grouped gemm MoE implementation to additional debugging / checking of intermediate results grouped_gemm_result: GroupedGEMMResult = None @dataclass class BackwardResult: X_grad: torch.Tensor gate_grad: torch.Tensor gate_proj_grad: torch.Tensor up_proj_grad: torch.Tensor down_proj_grad: torch.Tensor def check_down_proj_grad( moe_block: Qwen3MoeSparseMoeBlock, grouped_gemm_block: Qwen3MoeGroupedGEMMBlock, atol: float, rtol: float, ): for i, expert in enumerate(moe_block.experts): ref_grad = expert.down_proj.weight.grad assert ref_grad is not None test_grad = grouped_gemm_block.down_proj.grad[i] assert test_grad is not None diff = (ref_grad - test_grad).abs().max() if not torch.allclose(ref_grad, test_grad, atol = atol, rtol = rtol): print(f"expert {i} down_proj_grad_diff: {diff.detach().cpu().item():.6f}") def check_gate_up_proj_grad( moe_block: Qwen3MoeSparseMoeBlock, grouped_gemm_block: Qwen3MoeGroupedGEMMBlock, atol: float, rtol: float, ): moe_intermediate_size = grouped_gemm_block.moe_intermediate_size for i, expert in enumerate(moe_block.experts): ref_gate_proj_grad = expert.gate_proj.weight.grad ref_up_proj_grad = expert.up_proj.weight.grad assert ref_gate_proj_grad is not None assert ref_up_proj_grad is not None # Extract gradients test_gate_proj_grad = grouped_gemm_block.gate_up_proj.grad[ i, :moe_intermediate_size ] test_up_proj_grad = grouped_gemm_block.gate_up_proj.grad[ i, moe_intermediate_size: ] assert test_gate_proj_grad is not None assert test_up_proj_grad is not None # Sanity check shapes assert ( ref_gate_proj_grad.shape == test_gate_proj_grad.shape ), f"{ref_gate_proj_grad.shape} != {test_gate_proj_grad.shape}" assert ( ref_up_proj_grad.shape == test_up_proj_grad.shape ), f"{ref_up_proj_grad.shape} != {test_up_proj_grad.shape}" # Check gradients diff = (ref_gate_proj_grad - test_gate_proj_grad).abs().max() if not torch.allclose( ref_gate_proj_grad, test_gate_proj_grad, atol = atol, rtol = rtol ): print(f"expert {i} gate_proj_grad_diff: {diff.detach().cpu().item():.6f}") diff = (ref_up_proj_grad - test_up_proj_grad).abs().max() if not torch.allclose( ref_up_proj_grad, test_up_proj_grad, atol = atol, rtol = rtol ): print(f"expert {i} up_proj_grad_diff: {diff.detach().cpu().item():.6f}") def check_gate_grad( moe_block: Qwen3MoeSparseMoeBlock, grouped_gemm_block: Qwen3MoeGroupedGEMMBlock, atol: float, rtol: float, ): ref_grad = moe_block.gate.weight.grad assert ref_grad is not None test_grad = grouped_gemm_block.gate.grad assert test_grad is not None diff = (ref_grad - test_grad).abs().max() if not torch.allclose(ref_grad, test_grad, atol = atol, rtol = rtol): print(f"gate_grad_diff: {diff.detach().cpu().item():.6f}") def check_wgrad( moe_block: Qwen3MoeSparseMoeBlock, grouped_gemm_block: Qwen3MoeGroupedGEMMBlock, atol: float, rtol: float, ): check_down_proj_grad(moe_block, grouped_gemm_block, atol, rtol) check_gate_up_proj_grad(moe_block, grouped_gemm_block, atol, rtol) check_gate_grad(moe_block, grouped_gemm_block, atol, rtol) def check_tensor_allclose( X_ref: torch.Tensor, X_test: torch.Tensor, atol: float, rtol: float, name: str, verbose: bool = False, ): diff = (X_ref - X_test).abs().max() if verbose: print(f"{name} diff: {diff.detach().cpu().item():.6f}") assert torch.allclose( X_ref, X_test, atol = atol, rtol = rtol ), f"{name} diff: {diff.detach().cpu().item():.6f}" def check_expert_grads( ref_result: BackwardResult, test_result: BackwardResult, atol: float, rtol: float, verbose: bool = False, ): fields_to_check = [f.name for f in fields(BackwardResult) if "proj" in f.name] assert len(fields_to_check) == 3 for field in fields_to_check: ref_grads = getattr(ref_result, field) test_grads = getattr(test_result, field) assert ( ref_grads.shape == test_grads.shape ), f"{field}: {ref_grads.shape} != {test_grads.shape}" # Test each expert for i in range(ref_grads.shape[0]): ref_grad = ref_grads[i] test_grad = test_grads[i] diff = (ref_grad - test_grad).abs().max() assert torch.allclose( ref_grad, test_grad, atol = atol, rtol = rtol ), f"{field}[{i}] diff: {diff.detach().cpu().item():.6f}" # Test all experts diff = (ref_grads - test_grads).abs().max() if verbose: print(f"{field} diff: {diff.detach().cpu().item():.6f}") assert torch.allclose( ref_grads, test_grads, atol = atol, rtol = rtol ), f"{field} diff: {diff.detach().cpu().item():.6f}" def check_grads( ref_result: BackwardResult, test_result: BackwardResult, atol: float, rtol: float, verbose: bool = False, ): check_tensor_allclose( ref_result.X_grad, test_result.X_grad, atol, rtol, "X.grad", verbose ) check_tensor_allclose( ref_result.gate_grad, test_result.gate_grad, atol, rtol, "gate.grad", verbose ) check_expert_grads(ref_result, test_result, atol, rtol, verbose) def check_fwd( ref_result: ForwardResult, test_result: ForwardResult, atol: float, rtol: float, verbose: bool = False, ): # First check hidden states (output) ref_output = ref_result.output test_output = test_result.output diff = (ref_output - test_output).abs().max() if verbose: print(f"output diff: {diff.detach().cpu().item():.6f}") assert torch.allclose( ref_output, test_output, atol = atol, rtol = rtol ), f"output diff: {diff.detach().cpu().item():.6f}" # Check router logits ref_router_logits = ref_result.router_logits test_router_logits = test_result.router_logits diff = (ref_router_logits - test_router_logits).abs().max() if verbose: print(f"router_logits diff: {diff.detach().cpu().item():.6f}") assert torch.allclose( ref_router_logits, test_router_logits, atol = atol, rtol = rtol ), f"router_logits diff: {diff.detach().cpu().item():.6f}" def check_grouped_gemm_results( grouped_result: GroupedGEMMResult, fused_result: GroupedGEMMResult, permute_y: bool, atol: float, rtol: float, verbose: bool = False, ): for field in fields(GroupedGEMMResult): ref_value = getattr(grouped_result, field.name) test_value = getattr(fused_result, field.name) diff = (ref_value - test_value).abs().max() # second_gemm in torch grouped gemm is not yet unpermuted so comparing the fused unpermuted second_gemm will result in error # instead the hidden_states_unpermute should match since hidden_states_unpermute for the fused result is the same as second_gemm if field.name == "second_gemm" and permute_y: continue if verbose: print(f"{field.name} diff: {diff.detach().cpu().item():.6f}") assert torch.allclose( ref_value, test_value, atol = atol, rtol = rtol ), f"{field.name} diff: {diff.detach().cpu().item():.6f}" def run_forward(model: nn.Module, X: torch.Tensor, is_grouped_gemm: bool = False): X = X.detach().clone().requires_grad_(True) output, router_logits = model(X) if is_grouped_gemm: result = ForwardResult( output = output.hidden_states, router_logits = router_logits, X = X, grouped_gemm_result = output, ) else: result = ForwardResult(output = output, router_logits = router_logits, X = X) return result def run_backward( model: nn.Module, grad_output: torch.Tensor, output: torch.Tensor, X: torch.Tensor ): output.backward(grad_output) assert X.grad is not None for name, param in model.named_parameters(): assert param.grad is not None, f"{name} grad is None" if isinstance(model, Qwen3MoeSparseMoeBlock): gate_grad = model.gate.weight.grad gate_proj_grad = torch.stack( [expert.gate_proj.weight.grad for expert in model.experts] ) up_proj_grad = torch.stack( [expert.up_proj.weight.grad for expert in model.experts] ) down_proj_grad = torch.stack( [expert.down_proj.weight.grad for expert in model.experts] ) elif isinstance(model, Qwen3MoeGroupedGEMMBlock): gate_grad = model.gate.grad gate_proj_grad, up_proj_grad = model.gate_up_proj.grad.chunk(2, dim = 1) down_proj_grad = model.down_proj.grad else: raise ValueError(f"Unsupported model type: {type(model)}") return BackwardResult( X_grad = X.grad, gate_grad = gate_grad, gate_proj_grad = gate_proj_grad, up_proj_grad = up_proj_grad, down_proj_grad = down_proj_grad, ) class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock): """ Reference implementation of MoE block using grouped gemm. This is the same as the Qwen3MoeGroupedGEMMBlock but with triton grouped gemm in place of torch-native grouped gemm implementation. NOTE: This is NOT to be used for production as it contains many extra checks and saves all intermediate results for debugging. See grouped_gemm/reference/moe_block.py for a cleaner implementation. """ def __init__( self, config: Qwen3MoeConfig, gate: torch.Tensor, gate_up_proj: torch.Tensor, down_proj: torch.Tensor, permute_x: bool = False, permute_y: bool = False, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, ): super().__init__(config, gate, gate_up_proj, down_proj) self.permute_x = permute_x self.permute_y = permute_y self.autotune = autotune if not autotune: assert ( kernel_config_fwd is not None and kernel_config_bwd_dW is not None and kernel_config_bwd_dX is not None ), "Kernel configs must be provided if autotune is False" self.kernel_config_fwd = kernel_config_fwd self.kernel_config_bwd_dW = kernel_config_bwd_dW self.kernel_config_bwd_dX = kernel_config_bwd_dX @classmethod def from_hf( cls, moe_block: Qwen3MoeSparseMoeBlock, permute_x: bool = False, permute_y: bool = False, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, ): config: Qwen3MoeConfig = moe_block.experts[0].config gate, gate_up_proj, down_proj = Qwen3MoeGroupedGEMMBlock.extract_hf_weights( moe_block ) return cls( config, gate, gate_up_proj, down_proj, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, ) def forward(self, hidden_states: torch.Tensor, debug: bool = False) -> torch.Tensor: batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) # Pre-processing # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. permute_x -> permutation will be fused in prologue of first grouped gemm if not self.permute_x: hidden_states = permute(hidden_states, gather_indices, self.top_k) assert hidden_states.shape == (total_tokens, hidden_dim) # Start expert computation first_gemm = grouped_gemm( X = hidden_states, W = self.gate_up_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = self.permute_x, permute_y = False, # output of first grouped gemm should never be permuted autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = True, ) assert first_gemm.shape == (total_tokens, 2 * self.moe_intermediate_size) intermediate = self.act_and_mul(first_gemm) assert intermediate.shape == (total_tokens, self.moe_intermediate_size) second_gemm = grouped_gemm( X = intermediate, W = self.down_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = False, permute_y = self.permute_y, autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = False, ) assert second_gemm.shape == (total_tokens, hidden_dim) # Post-processing # 1. Unpermute from expert order to token order if not self.permute_y: hidden_states_unpermute = unpermute(second_gemm, gather_indices) assert hidden_states_unpermute.shape == (total_tokens, hidden_dim) else: hidden_states_unpermute = second_gemm # 2. Merge topk weights hidden_states = ( hidden_states_unpermute.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) hidden_states = hidden_states.sum(dim = 1) assert hidden_states.shape == (num_tokens, hidden_dim) hidden_states = hidden_states.view(batch_size, sequence_length, hidden_dim) return GroupedGEMMResult( token_counts_by_expert = token_counts_by_expert, gather_indices = gather_indices, topk_weights = routing_weights, first_gemm = first_gemm, intermediate = intermediate, second_gemm = second_gemm, hidden_states_unpermute = hidden_states_unpermute, hidden_states = hidden_states, ), router_logits
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/tests/common.py
unsloth/kernels/moe/tests/common.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import itertools from contextlib import contextmanager from dataclasses import dataclass, field import torch from grouped_gemm.kernels.tuning import ( KernelConfig, KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, prune_kernel_configs_backward_dW, prune_kernel_configs_backward_dX, prune_kernel_configs_fwd, ) def print_delimiter(char = "-", length = 80): print(char * length) @contextmanager def delimiter_context(): print_delimiter() yield print_delimiter() def make_inputs(M, N, K, E, topk, dtype, requires_grad = False): X1 = ( torch.randn((M, K), device = "cuda", dtype = dtype, requires_grad = requires_grad) / 10 ) X2 = ( torch.randn( (M * topk, N), device = "cuda", dtype = dtype, requires_grad = requires_grad ) / 10 ) W1 = ( torch.randn( (E, 2 * N, K), device = "cuda", dtype = dtype, requires_grad = requires_grad ) / 10 ) W2 = ( torch.randn((E, K, N), device = "cuda", dtype = dtype, requires_grad = requires_grad) / 10 ) score = torch.randn((M, E), device = "cuda", dtype = dtype, requires_grad = requires_grad) if requires_grad: X1.retain_grad() X2.retain_grad() W1.retain_grad() W2.retain_grad() score.retain_grad() return X1, X2, W1, W2, score @dataclass(kw_only = True) class DataConfig: seq_len: int dtype: torch.dtype device: str = "cuda" bs: int = 1 @dataclass(kw_only = True) class ModelConfig: hidden_size: int intermediate_size: int num_experts: int topk: int use_sigmoid: bool renormalize: bool pre_mul: bool = False post_mul: bool = field(init = False) def __post_init__(self): self.post_mul = not self.pre_mul @dataclass(kw_only = True) class GroupedGEMMTestConfig: name: str = "test" data_config: DataConfig model_config: ModelConfig TOLERANCE = { torch.bfloat16: (1e-3, 1e-3), torch.float16: (1e-4, 1e-4), torch.float32: (1e-5, 1e-5), } # from https://github.com/triton-lang/triton/blob/main/bench/triton_bench/testing.py def assert_equal(ref, tri): if isinstance(ref, torch.Tensor): assert torch.all(ref == tri), f"tensors not equal {ref} != {tri}" else: assert ref == tri, f"ref not equal to tri {ref} != {tri}" def assert_close(ref, tri, maxtol = None, rmstol = None, description = "--", verbose = True): if tri.dtype.itemsize == 1: ref_as_type = ref.to(tri.dtype) if ref.dtype == tri.dtype: assert torch.all(ref_as_type == tri) return ref = ref_as_type if maxtol is None: maxtol = 2e-2 if rmstol is None: rmstol = 4e-3 """ Compare reference values against obtained values. """ # cast to float32: ref = ref.to(torch.float32).detach() tri = tri.to(torch.float32).detach() assert ( ref.shape == tri.shape ), f"Tensors must have same size {ref.shape = } {tri.shape = }" # deal with infinite elements: inf_mask_ref = torch.isinf(ref) inf_mask_tri = torch.isinf(tri) assert torch.equal( inf_mask_ref, inf_mask_tri ), "Tensor must have same infinite elements" refn = torch.where(inf_mask_ref, 0, ref) trin = torch.where(inf_mask_tri, 0, tri) # normalise so that RMS calculation doesn't overflow: eps = 1.0e-30 multiplier = 1.0 / (torch.max(torch.abs(refn)) + eps) refn *= multiplier trin *= multiplier ref_rms = torch.sqrt(torch.square(refn).mean()) + eps rel_err = torch.abs(refn - trin) / torch.maximum(ref_rms, torch.abs(refn)) max_err = torch.max(rel_err).item() rms_err = torch.sqrt(torch.square(rel_err).mean()).item() if verbose: print( "%s maximum relative error = %s (threshold = %s)" % (description, max_err, maxtol) ) print( "%s RMS relative error = %s (threshold = %s)" % (description, rms_err, rmstol) ) if max_err > maxtol: bad_idxs = torch.nonzero(rel_err > maxtol) num_nonzero = bad_idxs.size(0) bad_idxs = bad_idxs[:1000] print( "%d / %d mismatched elements (shape = %s) at coords %s" % (num_nonzero, rel_err.numel(), tuple(rel_err.shape), bad_idxs.tolist()) ) bad_idxs = bad_idxs.unbind(-1) print("ref values: ", ref[*bad_idxs].cpu()) print("tri values: ", tri[*bad_idxs].cpu()) assert max_err <= maxtol assert rms_err <= rmstol def assert_indx_equal(ref, tri): assert_equal(ref, tri[: len(ref)]) assert torch.all(tri[len(ref) :] == -1) def get_kernel_test_configs( BLOCK_SIZE_M = 32, BLOCK_SIZE_N = 32, BLOCK_SIZE_K = 32, num_warps = 4, num_stages = 2, ) -> list[KernelConfig]: configs_fwd = [] configs_bwd_dX = [] configs_bwd_dW = [] for permute_x in [False, True]: for permute_y in [False, True]: for use_tma_load_w in [True, False]: for use_tma_load_x in [True, False]: for use_tma_store in [True, False]: configs_fwd.append( KernelConfigForward( BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, use_tma_load_w = use_tma_load_w, use_tma_load_x = use_tma_load_x, use_tma_store = use_tma_store, permute_x = permute_x, permute_y = permute_y, ) ) configs_bwd_dX.append( KernelConfigBackward_dX( BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, use_tma_load_dy = use_tma_load_x, use_tma_load_w = use_tma_load_w, permute_x = permute_x, permute_y = permute_y, use_tma_store = use_tma_store, ) ) configs_bwd_dW.append( KernelConfigBackward_dW( BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, use_tma_load_dy = use_tma_load_w, use_tma_load_x = use_tma_load_x, permute_x = permute_x, permute_y = permute_y, use_tma_store = use_tma_store, ) ) configs_fwd = prune_kernel_configs_fwd(configs_fwd) configs_bwd_dX = prune_kernel_configs_backward_dX(configs_bwd_dX) configs_bwd_dW = prune_kernel_configs_backward_dW(configs_bwd_dW) return configs_fwd, configs_bwd_dX, configs_bwd_dW def remove_feature_flags( kernel_configs: list[KernelConfig], permute_x: bool = True, permute_y: bool = True, tma_loads: bool = True, tma_store: bool = True, ): pruned_configs = [] for config in kernel_configs: # Remove permute flags first: if permute_x and config.permute_x: continue if permute_y and config.permute_y: continue if tma_loads: if isinstance(config, KernelConfigForward): if config.use_tma_load_w or config.use_tma_load_x: continue if isinstance(config, KernelConfigBackward_dX): if config.use_tma_load_dy or config.use_tma_load_w: continue if isinstance(config, KernelConfigBackward_dW): if config.use_tma_load_dy or config.use_tma_load_x: continue if tma_store: if config.use_tma_store: continue pruned_configs.append(config) return pruned_configs # Test Configs TOPK = [1, 4] NUM_EXPERTS = [4, 16] TEST_MODEL_SIZES = [ (32, 32), # Debug (128, 128), # Small (512, 512), # Medium ] SMALL_MODEL_CONFIGS = [ ModelConfig( topk = topk, num_experts = num_experts, hidden_size = model_size[0], intermediate_size = model_size[1], use_sigmoid = False, renormalize = False, ) for topk, num_experts, model_size in itertools.product( TOPK, NUM_EXPERTS, TEST_MODEL_SIZES ) ] LLAMA_MODEL_CONFIG = ModelConfig( topk = 1, num_experts = 16, hidden_size = 5120, intermediate_size = 8192, use_sigmoid = True, renormalize = False, ) QWEN_MODEL_CONFIG = ModelConfig( topk = 8, num_experts = 128, hidden_size = 2048, intermediate_size = 768, use_sigmoid = False, renormalize = False, ) SEQLENS = [128, 1024] DTYPE = [torch.bfloat16] DATA_CONFIGS = [ DataConfig(seq_len = seq_len, dtype = dtype) for seq_len, dtype in itertools.product(SEQLENS, DTYPE) ] KERNEL_CONFIGS_FWD, KERNEL_CONFIGS_BWD_dX, KERNEL_CONFIGS_BWD_dW = ( get_kernel_test_configs() ) if __name__ == "__main__": print( KERNEL_CONFIGS_BWD_dX[0].to_string( include_tuning_params = False, include_tma = False ) )
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/tests/test_llama4_moe.py
unsloth/kernels/moe/tests/test_llama4_moe.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import argparse import sys from contextlib import contextmanager from functools import partial import pytest import torch from transformers import AutoConfig from transformers.models.llama4 import Llama4Config, Llama4TextConfig from transformers.models.llama4.modeling_llama4 import Llama4TextMoe from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from grouped_gemm.reference.layers.llama4_moe import ( Llama4GroupedGemmTextMoe, Llama4TritonTextMoe, ) TOLERANCES = { torch.bfloat16: (1e-2, 1e-2), torch.float16: (1e-3, 1e-3), torch.float: (1e-5, 1e-5), } LLAMA4_SCOUT_ID = "meta-llama/Llama-4-Scout-17B-16E" SEED = 42 SEQ_LENS = [1024] DTYPES = [torch.bfloat16] # Reduce the number of autotuning configs to prevent excessive runtime NUM_AUTOTUNE_CONFIGS = 50 @contextmanager def annotated_context(prelude, epilogue = "Passed!", char = "-", num_chars = 80): print(char * num_chars) print(prelude) yield print(epilogue) print(char * num_chars) def get_text_config(model_id): config: Llama4Config = AutoConfig.from_pretrained(model_id) return config.text_config def prep_triton_kernel_traits(autotune): if not autotune: kernel_config_fwd = KernelConfigForward() kernel_config_bwd_dW = KernelConfigBackward_dW() kernel_config_bwd_dX = KernelConfigBackward_dX() else: from grouped_gemm.kernels.backward import ( _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel, ) from grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel # Hack to reduce number of autotuning configs _autotuned_grouped_gemm_forward_kernel.configs = ( _autotuned_grouped_gemm_forward_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) _autotuned_grouped_gemm_dW_kernel.configs = ( _autotuned_grouped_gemm_dW_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) _autotuned_grouped_gemm_dX_kernel.configs = ( _autotuned_grouped_gemm_dX_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) kernel_config_fwd = None kernel_config_bwd_dW = None kernel_config_bwd_dX = None return kernel_config_fwd, kernel_config_bwd_dW, kernel_config_bwd_dX def sparse_to_dense(t: torch.Tensor): t = t.sum(dim = 0).view(-1) return t @torch.no_grad() def _check_diff( t1: torch.Tensor, t2: torch.Tensor, atol, rtol, precision = ".6f", verbose = False, msg = "", ): t2 = t2.view_as(t1) diff = t1.sub(t2).abs().max().item() if verbose: if msg == "": msg = "diff" print(f"{msg}: {diff:{precision}}") assert torch.allclose(t1, t2, atol = atol, rtol = rtol) def run_backwards(y: torch.Tensor, grad_output: torch.Tensor, module: torch.nn.Module): y.backward(grad_output) for name, param in module.named_parameters(): assert param.grad is not None, f"{name} missing grad!" def _check_grads( m1: torch.nn.Module, m2: torch.nn.Module, atol, rtol, precision = ".6f", verbose = False, msg = "", ): for name, param in m1.named_parameters(): _check_diff( param.grad, m2.get_parameter(name).grad, atol = atol, rtol = rtol, precision = precision, verbose = verbose, msg = f"{msg}:{name}.grad", ) @pytest.fixture def model_config(): return AutoConfig.from_pretrained(LLAMA4_SCOUT_ID).text_config @pytest.mark.parametrize( "overlap_router_shared", [False, True], ids = lambda x: "overlap_router_shared" if x else "no_overlap", ) @pytest.mark.parametrize( "permute_y", [False, True], ids = lambda x: "permute_y" if x else "no_permute_y" ) @pytest.mark.parametrize( "permute_x", [False], ids = lambda x: "permute_x" if x else "no_permute_x" ) # Llama4 does not support permute_x @pytest.mark.parametrize( "autotune", [True], ids = lambda x: "autotune" if x else "manual" ) @pytest.mark.parametrize("seqlen", SEQ_LENS, ids = lambda x: f"seqlen={x}") @pytest.mark.parametrize("dtype", DTYPES, ids = str) def test_llama4_ref( dtype: torch.dtype, seqlen, autotune: bool, permute_x: bool, permute_y: bool, overlap_router_shared: bool, model_config: Llama4TextConfig, # test fixture bs: int = 1, device = "cuda", precision = ".6f", verbose = False, ): torch.manual_seed( SEED ) # Should not be needed when running using pytest -- autouse fixture in conftest.py device = "cuda" hidden_dim = model_config.hidden_size atol, rtol = TOLERANCES[dtype] check_diff = partial( _check_diff, atol = atol, rtol = rtol, precision = precision, verbose = verbose ) check_grads = partial( _check_grads, atol = atol, rtol = rtol, precision = precision, verbose = verbose ) # Reference op -- HF llama4_ref = Llama4TextMoe(model_config).to(dtype = dtype, device = device) # Torch grouped gemm impl llama4_gg_ref = Llama4GroupedGemmTextMoe( model_config, overlap_router_shared = overlap_router_shared ).to(dtype = dtype, device = device) llama4_gg_ref.copy_weights(llama4_ref) llama4_gg_ref.check_weights(llama4_ref) x_ref = torch.randn( bs, seqlen, hidden_dim, dtype = dtype, device = device, requires_grad = True ) x_torch_gg = x_ref.detach().clone().requires_grad_() x_triton = x_ref.detach().clone().requires_grad_() y_ref, routing_ref = llama4_ref(x_ref) y_torch_gg, routing_torch_gg = llama4_gg_ref(x_torch_gg) assert y_ref.shape == y_torch_gg.shape, f"{y_ref.shape} != {y_torch_gg.shape}" with annotated_context("Testing torch grouped gemm Llama4TextMoe"): check_diff(y_ref, y_torch_gg, msg = "y_torch_gg") check_diff( sparse_to_dense(routing_ref), routing_torch_gg, msg = "routing_torch_gg" ) kernel_config_fwd, kernel_config_bwd_dW, kernel_config_bwd_dX = ( prep_triton_kernel_traits(autotune) ) llama4_triton = Llama4TritonTextMoe( model_config, overlap_router_shared = overlap_router_shared, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, ).to(device = device, dtype = dtype) llama4_triton.copy_weights(llama4_ref) llama4_triton.check_weights(llama4_ref) y_triton, routing_triton = llama4_triton(x_triton) with annotated_context("Testing triton grouped gemm Llama4TextMoe forward"): check_diff(y_ref, y_triton, msg = "y_triton") check_diff(sparse_to_dense(routing_ref), routing_triton, msg = "routing_triton") ref_grad = torch.randn_like(y_ref) run_backwards(y_ref, ref_grad, llama4_ref) run_backwards(y_torch_gg, ref_grad, llama4_gg_ref) with annotated_context("Testing torch group gemm Llama4TextMoe backward"): check_grads(llama4_ref, llama4_gg_ref, msg = "torch_gg") run_backwards(y_triton, ref_grad, llama4_triton) with annotated_context("Testing triton group gemm Llama4TextMoe backward"): check_grads(llama4_ref, llama4_triton, msg = "triton") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--seqlen", type = int, default = 1024) parser.add_argument( "--dtype", type = str, choices = ["bfloat16", "float16"], default = "bfloat16" ) args = parser.parse_args() args.dtype = getattr(torch, args.dtype) args_dict = vars(args) model_id = LLAMA4_SCOUT_ID text_config: Llama4TextConfig = get_text_config(model_id) for overlap in [False, True]: test_llama4_ref( seqlen = args.seqlen, model_config = text_config, dtype = args.dtype, autotune = True, permute_x = False, permute_y = True, overlap_router_shared = overlap, verbose = True, )
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/tests/test_qwen3_moe.py
unsloth/kernels/moe/tests/test_qwen3_moe.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import argparse from contextlib import contextmanager import pytest import torch from transformers import AutoConfig from transformers.models.qwen3_moe import Qwen3MoeConfig from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeSparseMoeBlock from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from grouped_gemm.reference.layers.qwen3_moe import Qwen3MoeGroupedGEMMBlock from .moe_utils import ( Qwen3MoeFusedGroupedGEMMBlock, check_fwd, check_grads, check_grouped_gemm_results, run_backward, run_forward, ) """ Qwen3 MoE tests NOTE: Test this as a module and NOT with pytest as running with pytest results in random numerical errors: python -m tests.test_qwen3_moe --permute_x --permute_y --autotune NOT pytest -sv tests/test_qwen3_moe.py More specifically, all tests pass when run individually, but some will fail randomly (even with the same seed) when the entire test is run as a parametrized test suite using pytest, likely due to how pytest interacts with triton / autotuning. See tests/run_qwen3_moe_tests.sh for a script that runs all the tests The tests run the following: Huggingface's Qwen3 MoE block (Qwen3MoeSparseMoeBlock) Torch-native grouped gemm version of MoE block (Qwen3MoeGroupedGEMMBlock), which is the HF block with the expert computation replaced with a torch-native grouped gemm Triton kernel grouped gemm version of MoE block (Qwen3MoeFusedGroupedGEMMBlock), which is the HF block with the expert computation replaced with the fused triton grouped gemm kernel The tests check the following: - HF MoE block vs torch grouped gemm MoE block (sanity check) - torch grouped gemm MoE block vs fused grouped gemm MoE block -- this allows us to test each of the intermediate results for easier debugging - HF MoE block vs fused grouped gemm MoE block -- this is the actual test Both forward and backward passes are tests: - forward: output of the moe block - backwards: - X: gradient of the input to the moe block - gate.weight: gradient of the gate weights (router weights) - gate_proj: gradient of concatenated gate projections - up_proj: gradient of the concatenated up projections - down_proj: gradient of the concatenated down projections Additionally, for the torch grouped gemm and triton grouped gemm versions, the intermediate outputs of the forward pass are checked: - first_gemm: output of the first grouped gemm (X @ fused_gate_proj) - intermediate: output of silu_mul(first_gemm) - second_gemm: output of the second grouped gemm (intermediate @ down_proj) - hidden_states_unpermute: output of the second_gemm after unpermuting back to token order (from expert grouped order); in the case where the permutation is fused in the triton kernel, this is the same as second_gemm - hidden_states: output with the topk_weights applied """ TOLERANCES = { torch.bfloat16: (1e-2, 1e-2), torch.float16: (1e-3, 1e-3), torch.float: (1e-5, 1e-5), } @pytest.fixture(scope = "module") def model_id(): return "Qwen/Qwen3-30B-A3B" @pytest.fixture(scope = "module") def config(model_id: str): return AutoConfig.from_pretrained(model_id) @contextmanager def annotated_context(prelude, epilogue = "Passed!", char = "-", num_chars = 80): print(char * num_chars) print(prelude) yield print(epilogue) print(char * num_chars) SEED = 42 SEQ_LENS = [1024] DTYPES = [torch.bfloat16] # Reduce the number of autotuning configs to prevent excessive runtime NUM_AUTOTUNE_CONFIGS = 50 @pytest.mark.parametrize( "permute_y", [True], ids = lambda x: "permute_y" if x else "no_permute_y" ) @pytest.mark.parametrize( "permute_x", [True], ids = lambda x: "permute_x" if x else "no_permute_x" ) @pytest.mark.parametrize( "autotune", [True], ids = lambda x: "autotune" if x else "manual" ) @pytest.mark.parametrize("seqlen", SEQ_LENS, ids = lambda x: f"seqlen={x}") @pytest.mark.parametrize("dtype", DTYPES, ids = str) def test_qwen3_moe( config: Qwen3MoeConfig, seqlen: int, dtype: torch.dtype, permute_x: bool, permute_y: bool, autotune: bool, ): torch.manual_seed( SEED ) # Should not be needed when running using pytest -- autouse fixture in conftest.py device = "cuda" hidden_size = config.hidden_size bs = 1 atol, rtol = TOLERANCES[dtype] # Reference op -- HF moe_block = Qwen3MoeSparseMoeBlock(config).to(device, dtype) # Torch-native grouped gemm version of MoE Block -- for sanity checking grouped_gemm_block = Qwen3MoeGroupedGEMMBlock.from_hf(moe_block).to(device, dtype) grouped_gemm_block.check_weights(moe_block) if not autotune: kernel_config_fwd = KernelConfigForward() kernel_config_bwd_dW = KernelConfigBackward_dW() kernel_config_bwd_dX = KernelConfigBackward_dX() else: from grouped_gemm.kernels.backward import ( _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel, ) from grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel # Hack to reduce number of autotuning configs _autotuned_grouped_gemm_forward_kernel.configs = ( _autotuned_grouped_gemm_forward_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) _autotuned_grouped_gemm_dW_kernel.configs = ( _autotuned_grouped_gemm_dW_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) _autotuned_grouped_gemm_dX_kernel.configs = ( _autotuned_grouped_gemm_dX_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) kernel_config_fwd = None kernel_config_bwd_dW = None kernel_config_bwd_dX = None # Triton kernel grouped gemm version of MoE Block -- this is what we're testing fused_gemm_block = Qwen3MoeFusedGroupedGEMMBlock.from_hf( moe_block, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, ).to(device, dtype) fused_gemm_block.check_weights(moe_block) X = torch.randn( bs, seqlen, hidden_size, dtype = dtype, device = device, requires_grad = True ) # Forward ref_result = run_forward(moe_block, X, is_grouped_gemm = False) grouped_result = run_forward(grouped_gemm_block, X, is_grouped_gemm = True) fused_result = run_forward(fused_gemm_block, X, is_grouped_gemm = True) with annotated_context( "Testing forward pass", epilogue = "Passed forward tests!", char = "=", num_chars = 100, ): # Sanity checks with annotated_context( "Checking HF vs torch grouped gemm MoE forward outputs..." ): check_fwd(ref_result, grouped_result, atol, rtol, verbose = False) with annotated_context( "Checking torch grouped gemm MoE vs fused grouped gemm MoE forward outputs..." ): # We implement a custom check for grouped gemm results to test each of the intermediate results for easier debugging check_grouped_gemm_results( grouped_result.grouped_gemm_result, fused_result.grouped_gemm_result, permute_y = permute_y, atol = atol, rtol = rtol, verbose = False, ) # Actual test with annotated_context( "Checking HF vs fused grouped gemm MoE forward outputs..." ): check_fwd(ref_result, fused_result, atol, rtol, verbose = True) # Backward grad_output = torch.randn_like(ref_result.output) ref_backward_result = run_backward( moe_block, grad_output, output = ref_result.output, X = ref_result.X ) grouped_backward_result = run_backward( grouped_gemm_block, grad_output, output = grouped_result.output, X = grouped_result.X, ) fused_backward_result = run_backward( fused_gemm_block, grad_output, output = fused_result.output, X = fused_result.X ) with annotated_context( "Testing backward pass", epilogue = "Passed backward tests!", char = "=", num_chars = 100, ): # Sanity checks with annotated_context("Checking HF vs torch grouped gemm MoE grads..."): check_grads( ref_backward_result, grouped_backward_result, atol, rtol, verbose = False ) with annotated_context( "Checking torch grouped gemm MoE vs fused grouped gemm MoE grads..." ): check_grads( grouped_backward_result, fused_backward_result, atol, rtol, verbose = False, ) # Actual test with annotated_context("Checking HF vs fused grouped gemm MoE grads..."): check_grads( ref_backward_result, fused_backward_result, atol, rtol, verbose = True ) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--seqlen", type = int, default = 1024) parser.add_argument( "--dtype", type = str, choices = ["bfloat16", "float16"], default = "bfloat16" ) parser.add_argument("--permute_x", action = "store_true") parser.add_argument("--permute_y", action = "store_true") parser.add_argument("--autotune", action = "store_true") args = parser.parse_args() args.dtype = getattr(torch, args.dtype) args_dict = vars(args) model_id = "Qwen/Qwen3-30B-A3B" config = AutoConfig.from_pretrained(model_id) atol, rtol = TOLERANCES[args.dtype] print( f"Testing {model_id} with seqlen={args.seqlen}, dtype={args.dtype}, permute_x={args.permute_x}, permute_y={args.permute_y}, autotune={args.autotune}, atol={atol}, rtol={rtol}" ) test_qwen3_moe(config, **args_dict)
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/tests/__init__.py
unsloth/kernels/moe/tests/__init__.py
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/interface.py
unsloth/kernels/moe/grouped_gemm/interface.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import logging import warnings from dataclasses import asdict import torch import triton from grouped_gemm.kernels.backward import ( _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel, _grouped_gemm_dW_kernel, _grouped_gemm_dX_kernel, ) from grouped_gemm.kernels.forward import ( _autotuned_grouped_gemm_forward_kernel, _grouped_gemm_forward_kernel, ) from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) logger = logging.getLogger(__name__) # Set formatter to include timestamp, pathname and lineno formatter = logging.Formatter( "%(asctime)s::%(levelname)s,%(pathname)s:%(lineno)d:: %(message)s" ) # Add console handler ch = logging.StreamHandler() ch.setFormatter(formatter) logger.addHandler(ch) _FUSED_MUL_WARN = False _SUPPORTS_TMA = None def supports_tma(): global _SUPPORTS_TMA if _SUPPORTS_TMA is None: _SUPPORTS_TMA = torch.cuda.get_device_capability()[0] >= 9 return _SUPPORTS_TMA _per_device_alloc_fns = {} def get_per_device_per_stream_alloc_fn(device): if device not in _per_device_alloc_fns: _per_stream_tensors = {} def alloc_fn(size: int, alignment: int, stream): assert alignment == 128 if ( stream not in _per_stream_tensors or _per_stream_tensors[stream].numel() < size ): _per_stream_tensors[stream] = torch.empty( size, device = device, dtype = torch.int8 ) _per_stream_tensors[stream].__hibernate__ = {"type": "ignore"} return _per_stream_tensors[stream] _per_device_alloc_fns[device] = alloc_fn return _per_device_alloc_fns[device] def log_kernel_info( compiled_kernel: triton.compiler.CompiledKernel, best_config: triton.Config = None ): kernel_name = compiled_kernel.name nregs = compiled_kernel.n_regs nspills = compiled_kernel.n_spills metadata = compiled_kernel.metadata logger.debug( f"{kernel_name}: n_regs={nregs} n_spills={nspills} metadata={metadata}" ) if best_config is not None: logger.debug(f"{kernel_name} autotuned best_config: {best_config}") def grouped_gemm_forward( X: torch.Tensor, W: torch.Tensor, topk: int, m_sizes: torch.Tensor, gather_indices: torch.Tensor = None, topk_weights: torch.Tensor = None, # Fusions permute_x: bool = False, permute_y: bool = False, fuse_mul_post: bool = False, # Autotuning - manual kernel params will be ignored if autotune is True autotune: bool = False, # Kernel tuning params if not autotuning -- NOTE: these params need to be tuned, otherwise performance will be poor BLOCK_SIZE_M: int = 32, BLOCK_SIZE_N: int = 32, BLOCK_SIZE_K: int = 32, num_warps: int = 4, num_stages: int = 2, use_tma_load_w: bool = False, use_tma_load_x: bool = False, use_tma_store: bool = False, # software pipelining -- set to True for now, won't impact until loop is re-written flatten: bool = True, # debugging debug: bool = False, ) -> torch.Tensor: """ Grouped GEMM forward pass for MoE MLPs. The implementation offers a number of fusions specific to MoE: - `permute_x`: fuse the permutation of hidden states from token order (original order) to grouped expert order, typically only needed for the first grouped GEMM in an MoE MLP. - When `permute_x` is True, `X` is expected to be of shape (num_tokens, K). - When `permute_x` is False, `X` is expected to be of shape (total_tokens, K) where `total_tokens = num_tokens * topk` AND already permuted to grouped expert order, i.e., hidden states are sorted such that tokens assigned to each expert are contiguous. - `permute_y`: fused the permutation of the output from expert grouped order back to original token order, typically only needed for the second grouped GEMM in an MoE MLP. - `fuse_mul_pre`: fuse the multiplication of the routed input with topk_weights, only done in the first grouped GEMM in an MoE MLP as for Llama4. Do not use, since results in performance regression as it interrupts the GEMM mainloop. - `fuse_mul_post`: fuse the multiplication of the routed output with topk_weights, used only when `permute_y` is True. NOTE: this should only be used when using this kernel for inference, not for training. X: (M, K) hidden states where M is the num_tokens if `permute_x` is True, otherwise `total_tokens` where `total_tokens = num_tokens * topk`. W: (E, N, K) expert weights, where E is number of experts, N in the intermediate (output) dim, and K is the reduction dim m_sizes: tokens assigned to each expert which correspond to the size of M in the respective GEMMs in the grouped GEMM. gather_indices: (total_tokens,) indices of tokens assigned to each expert. E.g., slicing gather_indices by cumsum of m_sizes gives the indices of tokens assigned to each expert. topk_weights: (total_tokens,) weights to multiply routed output by in expert MLP calculation, used only when `fuse_mul_post` is True (see note on `fuse_mul_post`). use_fast_accum: currently unused; trade off faster accumulation dtype in GEMM for less precision. use_tma_load_x: use TMA for loading activations, incompatible with permute_x. TODO: add TMA gather / scatter support for Blackwell+. use_tma_load_w: use TMA for loading weights. If TMA supported, this should always be enabled as it is faster than global memory load. use_tma_store: use TMA for storing output, incompatible with permute_y. TODO: add TMA scatter support for Blackwell+. Returns: y: (total_tokens, N) output of grouped GEMM """ assert X.device.type == "cuda", "X and W must be on CUDA" assert m_sizes.device.type == "cuda", "m_sizes must be on CUDA" X = X.contiguous() W = W.contiguous() m_sizes = m_sizes.contiguous() # Preconditions assert not (permute_x and permute_y), "Cannot permute both X and Y" assert not (permute_y and use_tma_store), "Cannot use both TMA store and permute_y" if use_tma_load_x: # TMA load for activations, TMA gather only supported on Blackwell+ assert not permute_x, "Cannot use both use_tma_load_x and permute_x" use_tma = use_tma_load_w or use_tma_load_x or use_tma_store if not supports_tma() and use_tma: warnings.warn("TMA not supported, tma_load will be set to False") use_tma_load_w = False use_tma_load_x = False use_tma_store = False if use_tma or autotune: def alloc_fn(size: int, alignment: int, stream: int): return torch.empty(size, device = "cuda", dtype = torch.int8) triton.set_allocator(alloc_fn) X = X.view(-1, X.shape[-1]) W = W.view(-1, W.shape[-1]) if permute_x or permute_y: assert ( gather_indices is not None ), "gather_indices must be provided when permute_x or permute_y is True" assert gather_indices.is_contiguous() assert gather_indices.device.type == "cuda" assert gather_indices.ndim == 1 total_tokens = gather_indices.shape[0] num_tokens = total_tokens // topk if permute_x: assert ( X.shape[0] == num_tokens ), f"X.shape[0] ({X.shape[0]}) must match num_tokens ({num_tokens})" else: assert ( X.shape[0] == total_tokens ), f"X.shape[0] ({X.shape[0]}) must match total_tokens ({total_tokens})" else: total_tokens = X.shape[0] num_tokens = total_tokens // topk num_experts = m_sizes.shape[0] _, K = X.shape N = W.shape[0] // num_experts assert K == W.shape[1], f"K ({K}) must match W.shape[1] ({W.shape[1]})" if fuse_mul_post: global _FUSED_MUL_WARN if not _FUSED_MUL_WARN: warnings.warn( "fused_mul should only be used for inference, not for training" ) _FUSED_MUL_WARN = True assert permute_y, "FUSE_MUL requires PERMUTE_Y" assert topk_weights is not None assert topk_weights.numel() == total_tokens assert topk_weights.device.type == "cuda" assert topk_weights.is_contiguous() topk_weights = topk_weights.view(-1) if debug: print( f"DEBUG::GROUPED_GEMM {topk_weights.tolist()} {gather_indices.tolist()}" ) y = torch.empty((total_tokens, N), device = X.device, dtype = X.dtype) if total_tokens == 0 or N == 0: return y NUM_SMS = torch.cuda.get_device_properties("cuda").multi_processor_count def grid(META): return (NUM_SMS,) if not autotune: BLOCK_SIZE_K = min(K, BLOCK_SIZE_K) BLOCK_SIZE_N = min(N, BLOCK_SIZE_N) BLOCK_SIZE_M = min(total_tokens, BLOCK_SIZE_M) if debug: print( f"DEBUG::GROUPED_GEMM {num_tokens = } {topk = } {num_experts = } {N = } {K = } {BLOCK_SIZE_M = } {BLOCK_SIZE_N = } {BLOCK_SIZE_K = } {permute_x = }" ) print( f"DEBUG::GROUPED_GEMM {m_sizes.tolist()} {(gather_indices // topk).tolist()}" ) kernel_args = { # Inputs "x_ptr": X, "w_ptr": W, "m_sizes_ptr": m_sizes, "gather_indices_ptr": gather_indices, "topk_weights_ptr": topk_weights, # Output "y_ptr": y, # Problem shapes "NUM_TOKENS": num_tokens, "NUM_EXPERTS": num_experts, "TOPK": topk, "N": N, "K": K, "NUM_SMS": NUM_SMS, # Gather / Scatter "PERMUTE_X": permute_x, "PERMUTE_Y": permute_y, # TopK weight merging "FUSE_MUL_POST": fuse_mul_post, # Loop pipelining "FLATTEN": flatten, } if not autotune: kernel_args.update( { "USE_TMA_LOAD_W": use_tma_load_w, "USE_TMA_LOAD_X": use_tma_load_x, "USE_TMA_STORE": use_tma_store, "BLOCK_SIZE_M": BLOCK_SIZE_M, "BLOCK_SIZE_N": BLOCK_SIZE_N, "BLOCK_SIZE_K": BLOCK_SIZE_K, "num_warps": num_warps, "num_stages": num_stages, } ) kernel = ( _autotuned_grouped_gemm_forward_kernel if autotune else _grouped_gemm_forward_kernel ) compiled_kernel: triton.compiler.CompiledKernel = kernel[grid](**kernel_args) if autotune: log_kernel_info(compiled_kernel, kernel.best_config) else: log_kernel_info(compiled_kernel) return y def grouped_gemm_dX( dY: torch.Tensor, W: torch.Tensor, gather_indices: torch.Tensor, m_sizes: torch.Tensor, topk: int, BLOCK_SIZE_M: int = 32, BLOCK_SIZE_N: int = 32, BLOCK_SIZE_K: int = 32, debug: bool = False, permute_x: bool = False, permute_y: bool = False, use_tma_load_w: bool = False, use_tma_load_dy: bool = False, use_tma_store: bool = False, num_warps: int = 4, num_stages: int = 2, flatten: bool = True, fuse_mul_pre: bool = False, fuse_mul_post: bool = False, autotune: bool = False, ) -> torch.Tensor: """ dX backward kernel grad_output: (M, N) gather_indices: (total_tokens,), indices of tokens assigned to each expert. E.g., slicing gather_indices by cumsum of m_sizes gives the indices of tokens assigned to each expert. m_sizes: tokens assigned to each expert which correspond to the size of M in the respective GEMMs in the grouped GEMM. topk: number of experts chosen per token. `permute_x`: whether X was permuted on load in the forward pass, typically only used for the first grouped GEMM in an MoE MLP to group tokens by expert. - In the forward pass, if we permuted X on load, we need to permute store in the backward pass - Shapes - the forward pass input X shape is [NUM_TOKENS, K], reduce across K, output y is [NUM_TOKENS * TOPK, K] - the backward pass input dy shape is [NUM_TOKENS * TOPK, N], reduce across N, output dX is [NUM_TOKENS * TOPK, K] - Note that in the backward pass, the output size is still [NUM_TOKENS * TOPK, K] since we still need to accumulate gradients for each expert chosen by the token in a post-processing step. `permute_y`: whether the output was permuted on store in the forward pass, typically only used for the second grouped GEMM in an MoE MLP to restore to the original token order. - In the forward pass, if we permuted output on store (e.g., in the second grouped GEMM in fused MoE MLP), we need to permute on load to get from token order to expert grouped order - We still store in contiguous order since we are writing out dX which will be the input to the backwards pass of the first grouped GEMM `fuse_mul_{pre,post}`: always set to False since this should only be used for inference. use_tma_load_dy: use TMA for loading dy. use_tma_load_dy is incompatible with permute_y. TODO: add TMA gather / scatter support for Blackwell+ which will enable permute_y and use_tma_load_dy. use_tma_load_w: use TMA for loading weights. If TMA supported, this should always be enabled as it is faster than global memory load. use_tma_store: use TMA for storing dX. Incompatible with permute_x. TODO: add TMA gather / scatter support for Blackwell+ which will enable permute_x and use_tma_store. """ assert ( not fuse_mul_pre ), "fuse_mul_pre should only be used for inference, not for training" assert ( not fuse_mul_post ), "fuse_mul_post should only be used for inference, not for training" assert dY.is_contiguous() assert W.is_contiguous() assert m_sizes.is_contiguous() assert m_sizes.ndim == 1 # Preconditions assert not (permute_x and permute_y), "Cannot permute both X and Y" # Note that this is flipped from the forward pass # If we permuted y in the forward, we need to permute on load in the backward assert not (permute_y and use_tma_load_dy), "Cannot use both TMA load and permute_y" assert not (permute_x and use_tma_store), "Cannot use both TMA store and permute_x" use_tma = use_tma_load_dy or use_tma_load_w or use_tma_store if not supports_tma() and use_tma: warnings.warn("TMA not supported, tma_load will be set to False") use_tma_load_w = False use_tma_load_dy = False use_tma_store = False if use_tma or autotune: def alloc_fn(size: int, alignment: int, stream: int): # print(f"DEBUG::GROUPED_GEMM alloc_fn {size=} {alignment=} {stream=}") return torch.empty(size, device = "cuda", dtype = torch.int8) triton.set_allocator(alloc_fn) num_experts = m_sizes.shape[0] dY = dY.view(-1, dY.shape[-1]) W = W.view(-1, W.shape[-1]) M_total, N_grad = dY.shape N_total, K = W.shape N = N_total // num_experts assert N_grad == N, f"Grad_output N ({N_grad}) must match weight N ({N})" assert ( M_total % topk == 0 ), f"M_total ({M_total}) must be divisible by topk ({topk})" num_tokens = M_total // topk total_tokens = gather_indices.shape[0] assert ( total_tokens == M_total ), f"Total tokens ({total_tokens}) must match M_total ({M_total})" # Note that the output shape is [NUM_TOKENS * TOPK, K] even when `permute_x` is True since we need to accumulate gradients across all experts chosen by the token. # This will be done in a post-processing step reduction step. output_shape = (total_tokens, K) dX = torch.zeros(output_shape, device = dY.device, dtype = dY.dtype) NUM_SMS = torch.cuda.get_device_properties( "cuda" ).multi_processor_count # if not debug else 1 def grid(META): return (NUM_SMS,) if not autotune: BLOCK_SIZE_M = min(M_total, BLOCK_SIZE_M) BLOCK_SIZE_N = min(N_grad, BLOCK_SIZE_N) BLOCK_SIZE_K = min(K, BLOCK_SIZE_K) if debug: print( f"DEBUG::GROUPED_GEMM {num_tokens = } {topk = } {output_shape = } {num_experts = } {N = } {K = } {BLOCK_SIZE_M = } {BLOCK_SIZE_N = } {BLOCK_SIZE_K = } {NUM_SMS = }" ) print(f"DEBUG::GROUPED_GEMM {m_sizes.tolist()}") kernel_args = { # Inputs "dY_ptr": dY, "w_ptr": W, "gather_indices_ptr": gather_indices, "m_sizes_ptr": m_sizes, # Output "dX_ptr": dX, # Problem sizes "NUM_EXPERTS": num_experts, "NUM_TOKENS": num_tokens, "TOPK": topk, "N": N, "K": K, "NUM_SMS": NUM_SMS, # Gather / Scatter "PERMUTE_X": permute_x, "PERMUTE_Y": permute_y, "FLATTEN": flatten, } if not autotune: kernel_args.update( { "BLOCK_SIZE_M": BLOCK_SIZE_M, "BLOCK_SIZE_N": BLOCK_SIZE_N, "BLOCK_SIZE_K": BLOCK_SIZE_K, "num_warps": num_warps, "num_stages": num_stages, "USE_TMA_LOAD_dY": use_tma_load_dy, "USE_TMA_LOAD_W": use_tma_load_w, "USE_TMA_STORE": use_tma_store, } ) kernel = _autotuned_grouped_gemm_dX_kernel if autotune else _grouped_gemm_dX_kernel compiled_kernel: triton.compiler.CompiledKernel = kernel[grid](**kernel_args) if autotune: log_kernel_info(compiled_kernel, kernel.best_config) else: log_kernel_info(compiled_kernel) return dX def grouped_gemm_dW( X: torch.Tensor, dY: torch.Tensor, m_sizes: torch.Tensor, gather_indices: torch.Tensor, topk: int, BLOCK_SIZE_M: int = 32, BLOCK_SIZE_N: int = 32, BLOCK_SIZE_K: int = 32, permute_x: bool = False, permute_y: bool = False, use_tma_load_dy: bool = False, use_tma_load_x: bool = False, use_tma_store: bool = False, fuse_mul_pre: bool = False, fuse_mul_post: bool = False, num_warps: int = 4, num_stages: int = 2, flatten: bool = True, autotune: bool = False, debug: bool = False, ) -> torch.Tensor: """ X: (M, K) hidden states where M is the num_tokens if `permute_x` is True, otherwise `total_tokens` where `total_tokens = num_tokens * topk`. dY: (M, N) topk: number of experts to choose per token. m_sizes: tokens assigned to each expert which correspond to the size of M in the respective GEMMs in the grouped GEMM. gather_indices: (total_tokens,) indices of tokens assigned to each expert. E.g., slicing gather_indices by cumsum of m_sizes gives the indices of tokens assigned to each expert. permute_x: whether X was permuted on load in the forward pass, typically only used for the first grouped GEMM in an MoE MLP to group tokens by expert. - for the first grouped GEMM, we permuted on load -> X was [num_tokens, K] and stored y in expert grouped order [num_tokens * topk, K] - in the backwards pass, we need to permute on load of X while loading dy in contiguous (expert grouped) order - since we are writing out dW, there is no need to permute on store permute_y: whether the output was permuted on store in the forward pass, typically only used for the second grouped GEMM in an MoE MLP to restore to the original token order. - for the second grouped GEMM, we permuted on store -> y was permuted from expert grouped order to token order while X was loaded in expert grouped order since it was the output of the first grouped GEMM - in the backwards pass, we need to permute on load of dy to get from token order to expert grouped order to match the order of X - since we are writing out dW, there is no need to permute on store use_tma_load_dy: use TMA for loading dy. use_tma_load_dy is incompatible with permute_y. TODO: add TMA gather / scatter support for Blackwell+ which will enable permute_y and use_tma_load_dy. use_tma_load_x: use TMA for loading x. use_tma_load_x is incompatible with permute_x. TODO: add TMA gather / scatter support for Blackwell+ which will enable permute_x and use_tma_load_x. use_tma_store: use TMA for storing dW. If TMA supported, this should always be enabled as it is faster than global memory store. """ assert not fuse_mul_pre, "fuse_mul_pre not supported" assert not fuse_mul_post, "fuse_mul_post not supported" NUM_SMS = ( torch.cuda.get_device_properties("cuda").multi_processor_count if not debug else 1 ) X = X.view(-1, X.shape[-1]).contiguous() dY = dY.contiguous() m_sizes = m_sizes.contiguous() # Preconditions assert not (permute_x and permute_y), "Cannot permute both X and Y" assert not (permute_y and use_tma_load_dy), "Cannot use both TMA load and permute_y" assert not (permute_x and use_tma_load_x), "Cannot use both TMA load and permute_x" use_tma = use_tma_load_dy or use_tma_load_x or use_tma_store if not supports_tma() and use_tma: warnings.warn("TMA not supported, tma_load will be set to False") use_tma_load_x = False use_tma_load_dy = False use_tma_store = False if use_tma or autotune: def alloc_fn(size: int, alignment: int, stream: int): return torch.empty(size, device = "cuda", dtype = torch.int8) triton.set_allocator(alloc_fn) if permute_x or permute_y: assert gather_indices is not None assert gather_indices.is_contiguous() assert gather_indices.device.type == "cuda" assert gather_indices.ndim == 1 total_tokens = gather_indices.shape[0] num_tokens = total_tokens // topk if permute_x: assert X.shape[0] == num_tokens else: assert X.shape[0] == total_tokens else: total_tokens = X.shape[0] num_tokens = total_tokens // topk num_experts = m_sizes.shape[0] # Get dimensions _, K = X.shape M_grad, N = dY.shape assert M_grad == total_tokens, f"dY M ({M_grad}) != total_tokens ({total_tokens})" dW = torch.zeros((num_experts, N, K), device = X.device, dtype = X.dtype) if not autotune: BLOCK_SIZE_M = min(total_tokens, BLOCK_SIZE_M) BLOCK_SIZE_N = min(N, BLOCK_SIZE_N) BLOCK_SIZE_K = min(K, BLOCK_SIZE_K) def grid(META): return (NUM_SMS,) if debug: print( f"DEBUG::GROUPED_GEMM_DW_TMA {num_experts = } {N = } {K = } {BLOCK_SIZE_M = } {BLOCK_SIZE_N = } {BLOCK_SIZE_K = } {NUM_SMS = }" ) print(f"DEBUG::GROUPED_GEMM_DW_TMA {m_sizes.tolist() = }") print(f"DEBUG::GROUPED_GEMM_DW_TMA {gather_indices.tolist() = }") m_start = 0 for i in range(num_experts): expert_token_idx = gather_indices[m_start : m_start + m_sizes[i]] t_start = 0 while t_start < m_sizes[i]: token_idx = expert_token_idx[t_start : t_start + BLOCK_SIZE_M] if permute_x: token_idx = token_idx // topk print( f"DEBUG::GROUPED_GEMM_DW_TMA Token expert {i} indices: {token_idx.tolist()}" ) t_start += BLOCK_SIZE_M m_start += m_sizes[i] kernel_args = { # Inputs "x_ptr": X, "dY_ptr": dY, "m_sizes_ptr": m_sizes, "gather_indices_ptr": gather_indices, # Output "dW_ptr": dW, # Problem sizes "NUM_TOKENS": num_tokens, "TOPK": topk, "NUM_EXPERTS": num_experts, "N": N, "K": K, "NUM_SMS": NUM_SMS, # Gather / Scatter "PERMUTE_X": permute_x, "PERMUTE_Y": permute_y, # Loop pipelining "FLATTEN": flatten, } if not autotune: kernel_args.update( { "BLOCK_SIZE_M": BLOCK_SIZE_M, "BLOCK_SIZE_N": BLOCK_SIZE_N, "BLOCK_SIZE_K": BLOCK_SIZE_K, "USE_TMA_LOAD_dY": use_tma_load_dy, "USE_TMA_LOAD_X": use_tma_load_x, "USE_TMA_STORE": use_tma_store, "num_warps": num_warps, "num_stages": num_stages, } ) kernel = _autotuned_grouped_gemm_dW_kernel if autotune else _grouped_gemm_dW_kernel compiled_kernel: triton.compiler.CompiledKernel = kernel[grid](**kernel_args) if autotune: log_kernel_info(compiled_kernel, kernel.best_config) else: log_kernel_info(compiled_kernel) return dW class GroupedGemm(torch.autograd.Function): @staticmethod def forward( ctx, X, W, m_sizes, topk, gather_indices, permute_x, permute_y, topk_weights, fuse_mul_post, kernel_config_fwd, kernel_config_bwd_dX, kernel_config_bwd_dW, autotune, dX_only, dW_only, ): ctx.topk = topk ctx.permute_x = permute_x ctx.permute_y = permute_y ctx.fuse_mul_post = fuse_mul_post ctx.kernel_config_fwd = kernel_config_fwd ctx.kernel_config_bwd_dX = kernel_config_bwd_dX ctx.kernel_config_bwd_dW = kernel_config_bwd_dW ctx.autotune = autotune ctx.dX_only = dX_only ctx.dW_only = dW_only # NOTE: we don't save topk_weights for backward since we do not support training with fused_mul ctx.save_for_backward(X, W, m_sizes, gather_indices) fwd_config = {} if kernel_config_fwd is not None: fwd_config["BLOCK_SIZE_M"] = kernel_config_fwd.BLOCK_SIZE_M fwd_config["BLOCK_SIZE_N"] = kernel_config_fwd.BLOCK_SIZE_N fwd_config["BLOCK_SIZE_K"] = kernel_config_fwd.BLOCK_SIZE_K fwd_config["num_warps"] = kernel_config_fwd.num_warps fwd_config["num_stages"] = kernel_config_fwd.num_stages fwd_config["use_tma_load_x"] = kernel_config_fwd.use_tma_load_x fwd_config["use_tma_load_w"] = kernel_config_fwd.use_tma_load_w fwd_config["use_tma_store"] = kernel_config_fwd.use_tma_store return grouped_gemm_forward( X = X, W = W, topk = topk, m_sizes = m_sizes, gather_indices = gather_indices, topk_weights = topk_weights, permute_x = permute_x, permute_y = permute_y, fuse_mul_post = fuse_mul_post, # Autotune -- this will override the manual kernel config if true autotune = autotune, # Manual kernel config **fwd_config, ) @staticmethod def backward(ctx, dY): X, W, m_sizes, gather_indices = ctx.saved_tensors topk = ctx.topk permute_x = ctx.permute_x permute_y = ctx.permute_y fuse_mul_post = ctx.fuse_mul_post kernel_config_bwd_dX = ctx.kernel_config_bwd_dX kernel_config_bwd_dW = ctx.kernel_config_bwd_dW autotune = ctx.autotune dX_only = ctx.dX_only dW_only = ctx.dW_only if not autotune: if not dW_only: assert ( kernel_config_bwd_dX is not None ), "kernel_config_bwd_dX must be provided if autotune is False" if not dX_only: assert ( kernel_config_bwd_dW is not None ), "kernel_config_bwd_dW must be provided if autotune is False" assert ( not fuse_mul_post ), "fused_mul should only be used for inference, not for training" if not dX_only: bwd_dW_config = {} if kernel_config_bwd_dW is not None: bwd_dW_config["use_tma_load_dy"] = kernel_config_bwd_dW.use_tma_load_dy bwd_dW_config["use_tma_load_x"] = kernel_config_bwd_dW.use_tma_load_x bwd_dW_config["use_tma_store"] = kernel_config_bwd_dW.use_tma_store bwd_dW_config["BLOCK_SIZE_M"] = kernel_config_bwd_dW.BLOCK_SIZE_M bwd_dW_config["BLOCK_SIZE_N"] = kernel_config_bwd_dW.BLOCK_SIZE_N bwd_dW_config["BLOCK_SIZE_K"] = kernel_config_bwd_dW.BLOCK_SIZE_K bwd_dW_config["num_warps"] = kernel_config_bwd_dW.num_warps bwd_dW_config["num_stages"] = kernel_config_bwd_dW.num_stages dW = grouped_gemm_dW( X = X, dY = dY, m_sizes = m_sizes, gather_indices = gather_indices, topk = topk, permute_x = permute_x, permute_y = permute_y, # Autotune -- this will override the manual kernel config if true autotune = autotune, # Manual kernel config **bwd_dW_config, ) else: dW = None if not dW_only: bwd_dX_config = {} if kernel_config_bwd_dX is not None: bwd_dX_config["use_tma_load_dy"] = kernel_config_bwd_dX.use_tma_load_dy bwd_dX_config["use_tma_load_w"] = kernel_config_bwd_dX.use_tma_load_w bwd_dX_config["use_tma_store"] = kernel_config_bwd_dX.use_tma_store bwd_dX_config["BLOCK_SIZE_M"] = kernel_config_bwd_dX.BLOCK_SIZE_M bwd_dX_config["BLOCK_SIZE_N"] = kernel_config_bwd_dX.BLOCK_SIZE_N bwd_dX_config["BLOCK_SIZE_K"] = kernel_config_bwd_dX.BLOCK_SIZE_K bwd_dX_config["num_warps"] = kernel_config_bwd_dX.num_warps bwd_dX_config["num_stages"] = kernel_config_bwd_dX.num_stages dX = grouped_gemm_dX( dY = dY, W = W, m_sizes = m_sizes, gather_indices = gather_indices, topk = topk, permute_x = permute_x, permute_y = permute_y, # Autotune -- this will override the manual kernel config if true autotune = autotune, # Manual kernel config **bwd_dX_config, ) if topk > 1 and permute_x: dX = dX.view(X.shape[0], topk, -1).sum(dim = 1) else: dX = None return ( dX, dW, None, # m_sizes None, # gather_indices None, # topk None, # permute_x None, # permute_y None, # topk_weights None, # fuse_mul_post None, # kernel_config_fwd None, # kernel_config_bwd_dX None, # kernel_config_bwd_dW None, # autotune None, # dX_only None, # dW_only ) def check_valid_config_fwd( permute_x, permute_y, use_tma_load_x, use_tma_load_w, use_tma_store, fuse_mul_post, is_first_gemm, ): """ Check if the configuration is valid for the forward pass. """ is_second_gemm = not is_first_gemm assert not (permute_x and permute_y), "Cannot permute both X and Y" assert not ( is_second_gemm and permute_x ), "Cannot permute X for the second grouped GEMM" assert not ( is_first_gemm and permute_y ), "Cannot permute Y for the first grouped GEMM" assert not ( fuse_mul_post and is_first_gemm ), "Cannot fuse mul for the first grouped GEMM" assert not ( use_tma_load_x and permute_x ), "Cannot use TMA load and permute X unless on sm100+ (Blackwell+)" assert not ( use_tma_store and permute_y and is_second_gemm ), "Cannot use TMA store and permute Y for the second grouped GEMM unless on sm100+ (Blackwell+)" def check_valid_config_bwd_dW( permute_x, permute_y, use_tma_load_dY, use_tma_load_x, use_tma_store, fuse_mul_post, is_first_gemm, ): """ Check if the configuration is valid for the backward pass of dW. """ is_second_gemm = not is_first_gemm if fuse_mul_post: assert False, "Cannot fuse_mul is not supported for backward pass" if is_second_gemm and permute_y and use_tma_load_dY: assert False, "Cannot use TMA load and permute Y for the second grouped GEMM" if is_first_gemm and permute_x and use_tma_load_x: assert False, "Cannot use TMA load and permute X for the first grouped GEMM" def check_valid_config_bwd_dX( permute_x, permute_y, use_tma_load_dY, use_tma_load_w,
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
true
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/__init__.py
unsloth/kernels/moe/grouped_gemm/__init__.py
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/reference/moe_ops.py
unsloth/kernels/moe/grouped_gemm/reference/moe_ops.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import torch import torch.nn.functional as F def permute(X: torch.Tensor, gather_indices: torch.Tensor, topk: int): """ Scatters X to a new tensor with shape [total_tokens, hidden_dim] where total_tokens is num_tokens * topk, permuting the tokens according to sorted_token_idx. Helper for grouped gemm where hidden states need be ordered by expert. X: [num_tokens, hidden_dim] sorted_token_idx: [num_tokens * topk] topk: int Returns: [total_tokens, hidden_dim] """ assert gather_indices.ndim == 1 X = X.view(-1, X.shape[-1]) # Shortcut for topk == 1 if topk == 1: return X[gather_indices] return X[gather_indices // topk] def unpermute(X: torch.Tensor, gather_indices: torch.Tensor): X = X.view(-1, X.shape[-1]) if X.ndim > 2 else X unpermuted = torch.empty_like(X) unpermuted.index_copy_(0, gather_indices, X) return unpermuted.view_as(X) def calculate_topk( gating_output: torch.Tensor, top_k: int, use_sigmoid: bool, renormalize: bool, pre_act: bool = True, post_act: bool = False, ): """ If post_act is True, then activation function is run AFTER topk If post_act is False, then activation function is run BEFORE topk This is to align with triton_bench implementation (post_act) whereas most models use pre_act (e.g. llama4, deepseek) """ assert pre_act ^ post_act, "only one of pre_act or post_act can be True" def _activation(gating_output: torch.Tensor): if use_sigmoid: scores = torch.sigmoid(gating_output.to(torch.float32)).to( gating_output.dtype ) else: scores = F.softmax(gating_output.to(torch.float32), dim = 1).to( gating_output.dtype ) return scores if pre_act: scores = _activation(gating_output) else: scores = gating_output topk_weights, topk_ids = torch.topk(scores, k = top_k, dim = 1) if post_act: topk_weights = _activation(topk_weights) if renormalize: topk_weights /= torch.sum(topk_weights, dim = -1, keepdim = True).to( gating_output.dtype ) return topk_weights, topk_ids @torch.no_grad() def get_routing_indices( selected_experts, num_experts, return_scatter_indices: bool = False ): """ Returns: token_counts_by_expert: [num_experts] gather_indices: [num_tokens] scatter_indices [Optional] (torch.Tensor): Indices for unpermuting gathered inputs back to token order, shape ``(bs * seqlen * top_k,)``. """ # group tokens together by expert indices from 0 to num_experts and pass that to experts forward token_counts_by_expert = torch.histc( selected_experts.view(-1), bins = num_experts, min = 0, max = num_experts, ) # token_indices_experts_sorted shape (bs*slen*top_k,) gather_indices = torch.argsort(selected_experts.view(-1), stable = True) if return_scatter_indices: scatter_indices = gather_indices.argsort() return token_counts_by_expert, gather_indices, scatter_indices else: return token_counts_by_expert, gather_indices def torch_grouped_gemm(X, W, m_sizes, transpose = True): """ X: [M, K] if forward, else [M, N] W: [E, N, K] m_sizes: [E] Returns: Y: [M, N] if forward, else [M, K] """ X = X.view(-1, X.shape[-1]) M, K = X.shape assert m_sizes.ndim == 1 E = m_sizes.shape[0] assert W.ndim == 3 assert W.shape[0] == E N = W.shape[1] result = torch.zeros((M, N), dtype = X.dtype, device = X.device) m_start = 0 for g in range(E): m_size = m_sizes[g] if m_size > 0: m_end = m_start + m_size # Extract group input # m_size x K X_g = X[m_start:m_end] # N x K W_g = W[g] # Y_g = X_g @ W_g.T -> [m_size, N] W_g = W_g.T if transpose else W_g Y_g = X_g @ W_g result[m_start:m_end] = Y_g m_start = m_end return result
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/reference/moe_block.py
unsloth/kernels/moe/grouped_gemm/reference/moe_block.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import torch from transformers.models.qwen3_moe.configuration_qwen3_moe import Qwen3MoeConfig from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeSparseMoeBlock from grouped_gemm.interface import grouped_gemm from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from grouped_gemm.reference.moe_ops import ( Qwen3MoeGroupedGEMMBlock, permute, unpermute, ) """ Reference implementation of MoE block using grouped gemm. This is the same as the Qwen3MoeGroupedGEMMBlock but with triton grouped gemm in place of torch-native grouped gemm implementation. NOTE: This is NOT to be used for production as it contains many extra checks and saves all intermediate results for debugging. """ class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock): def __init__( self, config: Qwen3MoeConfig, gate: torch.Tensor, gate_up_proj: torch.Tensor, down_proj: torch.Tensor, permute_x: bool = True, permute_y: bool = True, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, dW_only: bool = False, dX_only: bool = False, ): super().__init__(config, gate, gate_up_proj, down_proj) self.permute_x = permute_x self.permute_y = permute_y self.autotune = autotune if not autotune: assert ( kernel_config_fwd is not None and kernel_config_bwd_dW is not None and kernel_config_bwd_dX is not None ), "Kernel configs must be provided if autotune is False" self.kernel_config_fwd = kernel_config_fwd self.kernel_config_bwd_dW = kernel_config_bwd_dW self.kernel_config_bwd_dX = kernel_config_bwd_dX self.dW_only = dW_only self.dX_only = dX_only @classmethod def from_hf( cls, moe_block: Qwen3MoeSparseMoeBlock, permute_x: bool = True, permute_y: bool = True, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, dW_only: bool = False, dX_only: bool = False, ): config: Qwen3MoeConfig = moe_block.experts[0].config gate, gate_up_proj, down_proj = Qwen3MoeGroupedGEMMBlock.extract_hf_weights( moe_block ) return cls( config, gate, gate_up_proj, down_proj, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, dW_only = dW_only, dX_only = dX_only, ) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) # Pre-processing # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. permute_x -> permutation will be fused in prologue of first grouped gemm if not self.permute_x: hidden_states = permute(hidden_states, gather_indices, self.top_k) # Start expert computation hidden_states = grouped_gemm( X = hidden_states, W = self.gate_up_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = self.permute_x, permute_y = False, # output of first grouped gemm should never be permuted autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = True, dW_only = self.dW_only, dX_only = self.dX_only, ) hidden_states = self.act_and_mul(hidden_states) hidden_states = grouped_gemm( X = hidden_states, W = self.down_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = False, permute_y = self.permute_y, autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = False, dW_only = self.dW_only, dX_only = self.dX_only, ) # Post-processing # 1. Unpermute from expert order to token order if not self.permute_y: hidden_states = unpermute(hidden_states, gather_indices) # 2. Merge topk weights hidden_states = ( hidden_states.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) hidden_states = hidden_states.sum(dim = 1) hidden_states = hidden_states.view(batch_size, sequence_length, hidden_dim) return hidden_states, router_logits
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/reference/__init__.py
unsloth/kernels/moe/grouped_gemm/reference/__init__.py
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.py
unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. from dataclasses import dataclass from typing import Tuple import torch import torch.nn.functional as F from transformers.models.qwen3_moe.configuration_qwen3_moe import Qwen3MoeConfig from transformers.models.qwen3_moe.modeling_qwen3_moe import ( ACT2FN, Qwen3MoeSparseMoeBlock, ) from grouped_gemm.interface import grouped_gemm from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from grouped_gemm.reference.moe_ops import ( get_routing_indices, permute, torch_grouped_gemm, unpermute, ) """ Reference implementation of HF Qwen3 MoE block using grouped gemm. The Qwen3MoeGroupedGEMMBlock is a reference torch-native implementation. Qwen3MoeFusedGroupedGEMMBlock is a version using the triton grouped gemm kernel. NOTE: This is NOT to be used for production as it contains many extra checks and saves all intermediate results for debugging. """ @dataclass class GroupedGEMMResult: token_counts_by_expert: torch.Tensor gather_indices: torch.Tensor topk_weights: torch.Tensor first_gemm: torch.Tensor intermediate: torch.Tensor second_gemm: torch.Tensor hidden_states_unpermute: torch.Tensor hidden_states: torch.Tensor # final output class Qwen3MoeGroupedGEMMBlock(torch.nn.Module): def __init__( self, config, gate: torch.Tensor, gate_up_proj: torch.Tensor, down_proj: torch.Tensor, ): super().__init__() self.num_experts = config.num_experts self.top_k = config.num_experts_per_tok self.norm_topk_prob = config.norm_topk_prob self.hidden_size = config.hidden_size self.moe_intermediate_size = config.moe_intermediate_size assert gate.shape == (config.num_experts, config.hidden_size) assert gate_up_proj.shape == ( config.num_experts, 2 * config.moe_intermediate_size, config.hidden_size, ) assert down_proj.shape == ( config.num_experts, config.hidden_size, config.moe_intermediate_size, ) # gating self.gate = torch.nn.Parameter(gate) # experts self.gate_up_proj = torch.nn.Parameter(gate_up_proj, requires_grad = True) self.down_proj = torch.nn.Parameter(down_proj, requires_grad = True) self.act_fn = ACT2FN[config.hidden_act] @staticmethod def extract_hf_weights(moe_block: Qwen3MoeSparseMoeBlock): config: Qwen3MoeConfig = moe_block.experts[0].config num_experts = config.num_experts gate = moe_block.gate.weight.data gate_proj = torch.stack( [moe_block.experts[i].gate_proj.weight.data for i in range(num_experts)], dim = 0, ) up_proj = torch.stack( [moe_block.experts[i].up_proj.weight.data for i in range(num_experts)], dim = 0, ) down_proj = torch.stack( [moe_block.experts[i].down_proj.weight.data for i in range(num_experts)], dim = 0, ) gate_up_proj = torch.cat([gate_proj, up_proj], dim = 1) return gate, gate_up_proj, down_proj @classmethod def from_hf(cls, moe_block: Qwen3MoeSparseMoeBlock): config: Qwen3MoeConfig = moe_block.experts[0].config gate, gate_up_proj, down_proj = cls.extract_hf_weights(moe_block) return cls(config, gate, gate_up_proj, down_proj) def check_weights(self, moe_block: Qwen3MoeSparseMoeBlock): for i in range(self.num_experts): assert self.gate_up_proj[i].equal( torch.cat( [ moe_block.experts[i].gate_proj.weight.data, moe_block.experts[i].up_proj.weight.data, ], dim = 0, ) ) assert self.down_proj[i].equal(moe_block.experts[i].down_proj.weight.data) def act_and_mul(self, x: torch.Tensor) -> torch.Tensor: assert x.shape[-1] == 2 * self.moe_intermediate_size gate_proj = x[..., : self.moe_intermediate_size] up_proj = x[..., self.moe_intermediate_size :] return self.act_fn(gate_proj) * up_proj def run_router(self, hidden_states: torch.Tensor) -> torch.Tensor: # router_logits: (batch * sequence_length, n_experts) router_logits = torch.nn.functional.linear(hidden_states, self.gate) routing_weights = F.softmax(router_logits, dim = 1, dtype = torch.float) routing_weights, selected_experts = torch.topk( routing_weights, self.top_k, dim = -1 ) if self.norm_topk_prob: # only diff with mixtral sparse moe block! routing_weights /= routing_weights.sum(dim = -1, keepdim = True) # we cast back to the input dtype routing_weights = routing_weights.to(hidden_states.dtype) return router_logits, routing_weights, selected_experts def get_token_counts_and_gather_indices( self, selected_experts: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: token_counts_by_expert, gather_indices = get_routing_indices( selected_experts, self.num_experts ) assert not token_counts_by_expert.requires_grad assert not gather_indices.requires_grad return token_counts_by_expert, gather_indices def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: """ """ batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. Permute tokens from token order to expert order hidden_states = permute(hidden_states, gather_indices, self.top_k) assert hidden_states.shape == (total_tokens, hidden_dim) # Start expert computation first_gemm = torch_grouped_gemm( X = hidden_states, W = self.gate_up_proj, m_sizes = token_counts_by_expert ) assert first_gemm.shape == (total_tokens, 2 * self.moe_intermediate_size) intermediate = self.act_and_mul(first_gemm) assert intermediate.shape == (total_tokens, self.moe_intermediate_size) second_gemm = torch_grouped_gemm( X = intermediate, W = self.down_proj, m_sizes = token_counts_by_expert ) assert second_gemm.shape == (total_tokens, hidden_dim) # Post-processing # 1. Unpermute from expert order to token order hidden_states_unpermute = unpermute(second_gemm, gather_indices) assert hidden_states_unpermute.shape == (total_tokens, hidden_dim) # 2. Merge topk weights hidden_states = ( hidden_states_unpermute.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) hidden_states = hidden_states.sum(dim = 1) assert hidden_states.shape == (num_tokens, hidden_dim) hidden_states = hidden_states.view(batch_size, sequence_length, hidden_dim) return GroupedGEMMResult( token_counts_by_expert = token_counts_by_expert, gather_indices = gather_indices, topk_weights = routing_weights, first_gemm = first_gemm, intermediate = intermediate, second_gemm = second_gemm, hidden_states_unpermute = hidden_states_unpermute, hidden_states = hidden_states, ), router_logits class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock): def __init__( self, config: Qwen3MoeConfig, gate: torch.Tensor, gate_up_proj: torch.Tensor, down_proj: torch.Tensor, permute_x: bool = True, permute_y: bool = True, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, dW_only: bool = False, dX_only: bool = False, ): super().__init__(config, gate, gate_up_proj, down_proj) self.permute_x = permute_x self.permute_y = permute_y self.autotune = autotune if not autotune: assert ( kernel_config_fwd is not None and kernel_config_bwd_dW is not None and kernel_config_bwd_dX is not None ), "Kernel configs must be provided if autotune is False" self.kernel_config_fwd = kernel_config_fwd self.kernel_config_bwd_dW = kernel_config_bwd_dW self.kernel_config_bwd_dX = kernel_config_bwd_dX self.dW_only = dW_only self.dX_only = dX_only @classmethod def from_hf( cls, moe_block: Qwen3MoeSparseMoeBlock, permute_x: bool = True, permute_y: bool = True, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, dW_only: bool = False, dX_only: bool = False, ): config: Qwen3MoeConfig = moe_block.experts[0].config gate, gate_up_proj, down_proj = Qwen3MoeGroupedGEMMBlock.extract_hf_weights( moe_block ) return cls( config, gate, gate_up_proj, down_proj, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, dW_only = dW_only, dX_only = dX_only, ) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) # Pre-processing # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. permute_x -> permutation will be fused in prologue of first grouped gemm if not self.permute_x: hidden_states = permute(hidden_states, gather_indices, self.top_k) # Start expert computation hidden_states = grouped_gemm( X = hidden_states, W = self.gate_up_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = self.permute_x, permute_y = False, # output of first grouped gemm should never be permuted autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = True, dW_only = self.dW_only, dX_only = self.dX_only, ) hidden_states = self.act_and_mul(hidden_states) hidden_states = grouped_gemm( X = hidden_states, W = self.down_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = False, permute_y = self.permute_y, autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = False, dW_only = self.dW_only, dX_only = self.dX_only, ) # Post-processing # 1. Unpermute from expert order to token order if not self.permute_y: hidden_states = unpermute(hidden_states, gather_indices) # 2. Merge topk weights hidden_states = ( hidden_states.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) hidden_states = hidden_states.sum(dim = 1) hidden_states = hidden_states.view(batch_size, sequence_length, hidden_dim) return hidden_states, router_logits
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.py
unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. from dataclasses import dataclass from typing import Tuple import torch import torch.nn.functional as F from transformers.models.llama4 import Llama4TextConfig from transformers.models.llama4.modeling_llama4 import Llama4TextMoe from grouped_gemm.interface import grouped_gemm from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from grouped_gemm.reference.moe_ops import ( get_routing_indices, permute, torch_grouped_gemm, unpermute, ) """ Reference implementation of Llama4 MoE block using triton grouped gemm. `Llama4GroupedGemmTextMoe` is the HF `Llama4TextMoe` block implemented with a torch-native grouped gemm. `Llama4TritonTextMoe` is the HF `Llama4TextMoe` implemented with triton grouped gemm. """ @dataclass class Llama4MoeResult: token_counts_by_expert: torch.Tensor gather_indices: torch.Tensor topk_weights: torch.Tensor hidden_states_after_weight_merge: torch.Tensor first_gemm: torch.Tensor intermediate: torch.Tensor second_gemm: torch.Tensor hidden_states_unpermute: torch.Tensor shared_expert_out: torch.Tensor final_out: torch.Tensor router_logits: torch.Tensor = None class Llama4GroupedGemmTextMoe(Llama4TextMoe): EXPERT_WEIGHT_NAMES = ["experts.gate_up_proj", "experts.down_proj"] def __init__( self, config: Llama4TextConfig, overlap_router_shared = False, verbose = False, debug = False, ): super().__init__(config) self.overlap_router_shared = overlap_router_shared self.verbose = verbose self.debug = debug # Permute in-place expert weights E, K, N = self.num_experts, self.hidden_dim, self.experts.expert_dim assert self.experts.gate_up_proj.shape == torch.Size( [E, K, 2 * N] ), f"{self.experts.gate_up_proj.shape} != {[E, K, 2 * N]}" permuted_shape = [E, 2 * N, K] permuted_stride = [2 * N * K, K, 1] if verbose: print( f"Changing gate_up_proj from {self.experts.gate_up_proj.size()}:{self.experts.gate_up_proj.stride()} to {permuted_shape}:{permuted_stride}" ) with torch.no_grad(): self.experts.gate_up_proj.as_strided_(permuted_shape, permuted_stride) if verbose: print( f"{self.experts.gate_up_proj.shape}:{self.experts.gate_up_proj.stride()}" ) assert self.experts.down_proj.shape == torch.Size( [E, N, K] ), f"{self.experts.down_proj.shape} != {[E, N, K]}" permuted_shape = [E, K, N] permuted_stride = [K * N, N, 1] if verbose: print( f"Changing down_proj from {self.experts.down_proj.size()}:{self.experts.down_proj.stride()} to {permuted_shape}:{permuted_stride}" ) with torch.no_grad(): self.experts.down_proj.as_strided_(permuted_shape, permuted_stride) if verbose: print(f"{self.experts.down_proj.shape}:{self.experts.down_proj.stride()}") if overlap_router_shared: self.shared_expert_stream = torch.cuda.Stream() self.default_event = torch.cuda.Event() self.shared_expert_end_event = torch.cuda.Event() @torch.no_grad def copy_weights(self, other: Llama4TextMoe): for name, param_to_copy in other.named_parameters(): if self.verbose: print(f"Copying {name} with shape {param_to_copy.shape}") param = self.get_parameter(name) if any(n in name for n in self.EXPERT_WEIGHT_NAMES): param_to_copy = param_to_copy.permute(0, 2, 1) assert ( param.shape == param_to_copy.shape ), f"{param.shape} != {param_to_copy.shape}" param.copy_(param_to_copy) return self def check_weights(self, other: Llama4TextMoe): for name, other_param in other.named_parameters(): if any(n in name for n in self.EXPERT_WEIGHT_NAMES): other_param = other_param.permute(0, 2, 1) param = self.get_parameter(name) assert param.equal(other_param), f"Param {name} not equal!" assert param.is_contiguous(), f"{name} not contiguous!" def act_and_mul(self, x: torch.Tensor) -> torch.Tensor: assert x.shape[-1] == 2 * self.experts.expert_dim gate_proj = x[..., : self.experts.expert_dim] up_proj = x[..., self.experts.expert_dim :] return self.experts.act_fn(gate_proj) * up_proj def run_router(self, hidden_states: torch.Tensor) -> torch.Tensor: # router_logits: (batch * sequence_length, n_experts) hidden_states = hidden_states.view(-1, self.hidden_dim) router_logits = self.router(hidden_states) routing_weights, selected_experts = torch.topk( router_logits, self.top_k, dim = -1 ) routing_weights = F.sigmoid(routing_weights.float()).to(hidden_states.dtype) return router_logits, routing_weights, selected_experts def get_token_counts_and_gather_indices( self, selected_experts: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: token_counts_by_expert, gather_indices = get_routing_indices( selected_experts, self.num_experts ) assert not token_counts_by_expert.requires_grad assert not gather_indices.requires_grad return token_counts_by_expert, gather_indices def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: """ """ batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) if self.overlap_router_shared: # Marker for all prior ops on default stream self.default_event.record() router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) assert routing_weights.shape == ( num_tokens, self.top_k, ), f"{routing_weights.shape} != {(num_tokens, self.top_k)}" if self.overlap_router_shared: with torch.cuda.stream(self.shared_expert_stream): # Ensure prior kernels on default stream complete self.default_event.wait() shared_expert_out = self.shared_expert(hidden_states) # Ensure hidden states remains valid on this stream hidden_states.record_stream(self.shared_expert_stream) self.shared_expert_end_event.record() # Ensure shared expert still valid on default stream shared_expert_out.record_stream(torch.cuda.current_stream()) self.shared_expert_end_event.wait() else: shared_expert_out = self.shared_expert(hidden_states) hidden_states = ( hidden_states.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) if self.top_k > 1: hidden_states = hidden_states.sum(dim = 1) hidden_states_after_weight_merge = hidden_states.view(-1, hidden_dim) # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. Permute tokens from token order to expert order hidden_states = permute( hidden_states_after_weight_merge, gather_indices, self.top_k ) assert hidden_states.shape == (total_tokens, hidden_dim) # Start expert computation first_gemm = torch_grouped_gemm( X = hidden_states, W = self.experts.gate_up_proj, m_sizes = token_counts_by_expert ) assert first_gemm.shape == (total_tokens, 2 * self.experts.expert_dim) intermediate = self.act_and_mul(first_gemm) assert intermediate.shape == (total_tokens, self.experts.expert_dim) # See comment above second_gemm = torch_grouped_gemm( X = intermediate, W = self.experts.down_proj, m_sizes = token_counts_by_expert ) assert second_gemm.shape == (total_tokens, hidden_dim) # Post-processing hidden_states_unpermute = unpermute(second_gemm, gather_indices) assert hidden_states_unpermute.shape == (total_tokens, hidden_dim) # grouped_gemm_out = hidden_states.view(batch_size, sequence_length, hidden_dim) final_out = hidden_states_unpermute + shared_expert_out result = ( Llama4MoeResult( token_counts_by_expert = token_counts_by_expert, gather_indices = gather_indices, topk_weights = routing_weights, hidden_states_after_weight_merge = hidden_states_after_weight_merge, first_gemm = first_gemm, intermediate = intermediate, second_gemm = second_gemm, hidden_states_unpermute = hidden_states_unpermute, shared_expert_out = shared_expert_out, final_out = final_out, router_logits = router_logits, ) if self.debug else (final_out, routing_weights) ) return result class Llama4TritonTextMoe(Llama4GroupedGemmTextMoe): def __init__( self, config: Llama4TextConfig, overlap_router_shared = False, permute_x: bool = False, permute_y: bool = True, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, dW_only: bool = False, dX_only: bool = False, verbose = False, ): super().__init__(config, overlap_router_shared = overlap_router_shared) assert not permute_x, "Llama4 triton grouped gemm does not support permute x due to pre-multiplication of router weights" self.permute_x = permute_x self.permute_y = permute_y self.autotune = autotune if not autotune: assert ( kernel_config_fwd is not None and kernel_config_bwd_dW is not None and kernel_config_bwd_dX is not None ), "Kernel configs must be provided if autotune is False" self.kernel_config_fwd = kernel_config_fwd self.kernel_config_bwd_dW = kernel_config_bwd_dW self.kernel_config_bwd_dX = kernel_config_bwd_dX self.dW_only = dW_only self.dX_only = dX_only @torch.no_grad def copy_weights(self, other: Llama4TextMoe): for name, param_to_copy in other.named_parameters(): if self.verbose: print(f"Copying {name} with shape {param_to_copy.shape}") param = self.get_parameter(name) if any(n in name for n in self.EXPERT_WEIGHT_NAMES): param_to_copy = param_to_copy.permute(0, 2, 1) assert ( param.shape == param_to_copy.shape ), f"{param.shape} != {param_to_copy.shape}" param.copy_(param_to_copy) return self def check_weights(self, other: Llama4TextMoe): for name, other_param in other.named_parameters(): if any(n in name for n in self.EXPERT_WEIGHT_NAMES): other_param = other_param.permute(0, 2, 1) param = self.get_parameter(name) assert param.equal(other_param), f"Param {name} not equal!" assert param.is_contiguous(), f"{name} not contiguous!" def act_and_mul(self, x: torch.Tensor) -> torch.Tensor: assert x.shape[-1] == 2 * self.experts.expert_dim gate_proj = x[..., : self.experts.expert_dim] up_proj = x[..., self.experts.expert_dim :] return self.experts.act_fn(gate_proj) * up_proj def run_router(self, hidden_states: torch.Tensor) -> torch.Tensor: # router_logits: (batch * sequence_length, n_experts) hidden_states = hidden_states.view(-1, self.hidden_dim) router_logits = self.router(hidden_states) routing_weights, selected_experts = torch.topk( router_logits, self.top_k, dim = -1 ) routing_weights = F.sigmoid(routing_weights.float()).to(hidden_states.dtype) return router_logits, routing_weights, selected_experts def get_token_counts_and_gather_indices( self, selected_experts: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: token_counts_by_expert, gather_indices = get_routing_indices( selected_experts, self.num_experts ) assert not token_counts_by_expert.requires_grad assert not gather_indices.requires_grad return token_counts_by_expert, gather_indices def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: """ """ batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) if self.overlap_router_shared: # Marker for all prior ops on default stream self.default_event.record() router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) assert routing_weights.shape == ( num_tokens, self.top_k, ), f"{routing_weights.shape} != {(num_tokens, self.top_k)}" if self.overlap_router_shared: with torch.cuda.stream(self.shared_expert_stream): # Ensure prior kernels on default stream complete self.default_event.wait() shared_expert_out = self.shared_expert(hidden_states) # Ensure hidden states remains valid on this stream hidden_states.record_stream(self.shared_expert_stream) self.shared_expert_end_event.record() # Ensure shared expert still valid on default stream shared_expert_out.record_stream(torch.cuda.current_stream()) self.shared_expert_end_event.wait() else: shared_expert_out = self.shared_expert(hidden_states) hidden_states = ( hidden_states.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) if self.top_k > 1: hidden_states = hidden_states.sum(dim = 1) hidden_states = hidden_states.view(-1, hidden_dim) # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. Permute tokens from token order to expert order hidden_states = permute(hidden_states, gather_indices, self.top_k) assert hidden_states.shape == (total_tokens, hidden_dim) # Start expert computation hidden_states = grouped_gemm( X = hidden_states, W = self.experts.gate_up_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = self.permute_x, permute_y = False, # output of first grouped gemm should never be permuted autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = True, dW_only = self.dW_only, dX_only = self.dX_only, ) hidden_states = self.act_and_mul(hidden_states) hidden_states = grouped_gemm( X = hidden_states, W = self.experts.down_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = False, permute_y = self.permute_y, autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = False, dW_only = self.dW_only, dX_only = self.dX_only, ) # Post-processing # 1. Unpermute from expert order to token order if not self.permute_y: hidden_states = unpermute(hidden_states, gather_indices) hidden_states += shared_expert_out return hidden_states, routing_weights
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/kernels/tuning.py
unsloth/kernels/moe/grouped_gemm/kernels/tuning.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. """ Manual tuning utils """ from collections import OrderedDict from dataclasses import asdict, dataclass, fields from itertools import product from typing import Optional import pandas as pd import torch import triton from triton.runtime.errors import OutOfResources from grouped_gemm.kernels.autotuning import ( BOOLS, DEFAULT_K_BLOCK_SIZES, DEFAULT_M_BLOCK_SIZES, DEFAULT_N_BLOCK_SIZES, DEFAULT_NUM_STAGES, DEFAULT_NUM_WARPS, ) @dataclass class DeviceProperties: NUM_SM: int NUM_REGS: int SIZE_SMEM: int WARP_SIZE: int _DEVICE_PROPERTIES: Optional[DeviceProperties] = None def get_device_properties(): global _DEVICE_PROPERTIES if _DEVICE_PROPERTIES is None: properties = triton.runtime.driver.active.utils.get_device_properties( torch.cuda.current_device() ) NUM_SM = properties["multiprocessor_count"] NUM_REGS = properties["max_num_regs"] SIZE_SMEM = properties["max_shared_mem"] WARP_SIZE = properties["warpSize"] _DEVICE_PROPERTIES = DeviceProperties(NUM_SM, NUM_REGS, SIZE_SMEM, WARP_SIZE) return _DEVICE_PROPERTIES @dataclass class KernelConfig: BLOCK_SIZE_M: int = 32 BLOCK_SIZE_N: int = 32 BLOCK_SIZE_K: int = 32 num_warps: int = 4 num_stages: int = 2 flatten: bool = True permute_x: bool = False permute_y: bool = False fuse_mul_post: bool = False use_tma_store: bool = False def to_string(self, include_tuning_params: bool = False, include_tma: bool = False): s = [] if self.permute_x: s.append("permute_x") if self.permute_y: s.append("permute_y") if include_tuning_params: s.append( f"BLOCK_SIZE_M={self.BLOCK_SIZE_M},BLOCK_SIZE_N={self.BLOCK_SIZE_N},BLOCK_SIZE_K={self.BLOCK_SIZE_K},num_warps={self.num_warps},num_stages={self.num_stages},flatten={self.flatten}" ) if include_tma: for f in fields(self): if f.name.startswith("use_tma_"): if getattr(self, f.name): s.append(f.name) return ",".join(s) @dataclass class KernelConfigForward(KernelConfig): use_tma_load_w: bool = False use_tma_load_x: bool = False @dataclass class KernelConfigBackward_dW(KernelConfig): use_tma_load_dy: bool = False use_tma_load_x: bool = False @dataclass class KernelConfigBackward_dX(KernelConfig): use_tma_load_dy: bool = False use_tma_load_w: bool = False @dataclass class KernelResult: torch_time: float triton_time: float speedup: float kernel_config: KernelConfig def to_dict(self): return OrderedDict( **asdict(self.kernel_config), torch_time = self.torch_time, triton_time = self.triton_time, speedup = self.speedup, ) @staticmethod def to_dataframe( results: list["KernelResult"], sort_by: str = "speedup", ascending: bool = False ): df = pd.DataFrame([result.to_dict() for result in results]) df = df.sort_values(by = sort_by, ascending = ascending) return df @staticmethod def to_csv( results: list["KernelResult"], sort_by: str = "speedup", ascending: bool = False, filename: str = "results.csv", ): df = KernelResult.to_dataframe(results, sort_by, ascending) df.to_csv(filename, index = False) @staticmethod def print_table( results: list["KernelResult"], sort_by: str = "speedup", ascending: bool = False, num_results: int = 10, ): df = KernelResult.to_dataframe(results, sort_by, ascending) print(df.head(num_results).to_string(index = False)) def get_kernel_configs( BLOCK_M = DEFAULT_M_BLOCK_SIZES, BLOCK_N = DEFAULT_N_BLOCK_SIZES, BLOCK_K = DEFAULT_K_BLOCK_SIZES, num_warps = DEFAULT_NUM_WARPS, num_stages = DEFAULT_NUM_STAGES, use_tma_loads = BOOLS, fuse_permute = BOOLS, ): kernel_configs_fwd = [] kernel_configs_backward_dW = [] kernel_configs_backward_dX = [] for block_m, block_n, block_k, w, s, use_tma_load, permute in product( BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, use_tma_loads, fuse_permute ): kernel_configs_fwd.append( KernelConfigForward( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = w, num_stages = s, use_tma_load_x = use_tma_load, use_tma_load_w = use_tma_load, use_tma_store = False, permute_x = permute, permute_y = permute, ) ) kernel_configs_backward_dW.append( KernelConfigBackward_dW( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = w, num_stages = s, use_tma_load_dy = use_tma_load, use_tma_load_x = use_tma_load, use_tma_store = False, permute_x = permute, permute_y = permute, ) ) kernel_configs_backward_dX.append( KernelConfigBackward_dX( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = w, num_stages = s, use_tma_load_dy = use_tma_load, use_tma_load_w = use_tma_load, use_tma_store = False, permute_x = permute, permute_y = permute, ) ) kernel_configs_fwd = prune_kernel_configs_fwd(kernel_configs_fwd) kernel_configs_backward_dW = prune_kernel_configs_backward_dW( kernel_configs_backward_dW ) kernel_configs_backward_dX = prune_kernel_configs_backward_dX( kernel_configs_backward_dX ) return kernel_configs_fwd, kernel_configs_backward_dW, kernel_configs_backward_dX def prune_kernel_configs_fwd(configs: list[KernelConfigForward]): pruned_configs = [] for config in configs: if config.use_tma_load_x and config.permute_x: continue if config.permute_x and config.permute_y: continue if config.use_tma_store and config.permute_y: continue pruned_configs.append(config) return pruned_configs def prune_kernel_configs_backward_dX(configs: list[KernelConfigBackward_dX]): pruned_configs = [] for config in configs: if config.use_tma_load_dy and config.permute_y: continue if config.permute_x and config.permute_y: continue if config.use_tma_store and config.permute_x: continue pruned_configs.append(config) return pruned_configs def prune_kernel_configs_backward_dW(configs: list[KernelConfigBackward_dW]): pruned_configs = [] for config in configs: if config.use_tma_load_dy and config.permute_y: continue if config.use_tma_load_x and config.permute_x: continue if config.permute_x and config.permute_y: continue pruned_configs.append(config) return pruned_configs class TritonTuningContext: def __init__(self, kernel_config: KernelConfig): self.kernel_config = kernel_config self.success = True def __enter__(self): # Setup code can be added here if needed return self def __exit__(self, exc_type, exc_value, traceback): if exc_type is OutOfResources: name = exc_value.name required = exc_value.required limit = exc_value.limit print( f"Kernel config {self.kernel_config} failed: {name}, required: {required}, limit: {limit}" ) self.success = False elif exc_type is not None: print( f"Error running Triton grouped GEMM for kernel config: {self.kernel_config}: {exc_value}" ) self.success = False # Return False to propagate exceptions, True to suppress them return True
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/kernels/backward.py
unsloth/kernels/moe/grouped_gemm/kernels/backward.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import torch import triton import triton.language as tl from grouped_gemm.kernels.autotuning import ( get_dW_kernel_configs, get_dX_kernel_configs, prune_dX_configs, prune_kernel_configs_backward_dW, ) """ dX backward kernel - Shapes - the forward pass input X shape is [NUM_TOKENS, K] if permute_x else [NUM_TOKENS * TOPK, K]; output y is [NUM_TOKENS * TOPK, N] - the backward pass input dy shape is [NUM_TOKENS * TOPK, N], reduce across N, output dX is [NUM_TOKENS * TOPK, K] - Note that in the backward pass, the output size is still [NUM_TOKENS * TOPK, K] since we still need to accumulate gradients for each expert chosen by the token in a post-processing step. `permute_x` notes: - In the forward pass, if we permute X on load, we need to permute on store in the backward pass to restore to original token order - the output dX with have shape [NUM_TOKENS * TOPK, K] and we need to perform an additional reduction across topk to accumulate gradients - This is done as a post-processing step in autograd.Function. - If not `permute_x`, this postprocessing step should take place outside autograd.Function such that the gradient shape matches the input X shape. `permute_y` notes: - In the forward pass, if we permuted output on store (e.g., in the second grouped GEMM in fused MoE MLP), we need to permute on load to get from token order to expert grouped order - We still store in contiguous order since we are writing out dX which will be the input to the backwards pass of the first grouped GEMM `fused_mul` notes: - In the forward pass, if we used the multiplication of topk weights (e.g., in the second grouped GEMM in fused MoE MLP), we need to make a few additional changes: 1) We load topk_weights in natural (token) order. Since we only enable `fuse_mul` when permuting on store (`permute_y`), we multiply grad_output by topk_weights before backpropagating 2) We need to calculate the gradient of the topk_weights. This gets messy since we need do an additional elementwise multiplication in the GEMM main loop and then write out in unpermuted order. For now, we do not fuse this step but calculate as a simple Invalid combinations: - permute_y and use_tma_load: permuting y on store in forward -> load in permuted order in backward, therefore can't use TMA load (unless Blackwell which supports gather / scatter TMA) - permute_x and use_tma_store: permuting x on load in forward -> store in permuted order in backward, therefore can't use TMA store (unless Blackwell which supports gather / scatter TMA) TODO: - We define indices for all conditions and expect that unused indices will be DCE'd during compilation. Check that this is the case otherwise will result in unnecessary register usage. """ @triton.jit def _grouped_gemm_dX_kernel( dY_ptr, # [M_total, N] w_ptr, # [E, N, K] dX_ptr, # [M_total, K] gather_indices_ptr, m_sizes_ptr, # problem sizes NUM_EXPERTS: tl.constexpr, NUM_TOKENS: tl.constexpr, TOPK: tl.constexpr, N: tl.constexpr, K: tl.constexpr, NUM_SMS: tl.constexpr, # Tuning parameters BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, PERMUTE_X: tl.constexpr = False, PERMUTE_Y: tl.constexpr = False, USE_TMA_LOAD_W: tl.constexpr = False, USE_TMA_LOAD_dY: tl.constexpr = False, USE_TMA_STORE: tl.constexpr = False, FLATTEN: tl.constexpr = True, ) -> None: TOTAL_TOKENS: tl.constexpr = NUM_TOKENS * TOPK output_dtype = dX_ptr.dtype.element_ty tidx = tl.program_id(0) # This removes the need for predication along N in the GEMM main loop tl.static_assert(N % BLOCK_SIZE_N == 0, "N must be divisible by BLOCK_SIZE_N") tl.static_assert(K % BLOCK_SIZE_K == 0, "K must be divisible by BLOCK_SIZE_K") # Create TMA descriptors for loading sorted tokens # When using TMA load, we don't permute_x, so shape should be [TOTAL_TOKENS, K] # Also, we are defining a single global descriptor with single block shape # Need to check that this does not result in errors when crossing expert boundaries if USE_TMA_LOAD_dY: dY_desc = tl._experimental_make_tensor_descriptor( dY_ptr, shape = [TOTAL_TOKENS, N], strides = [N, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_N], ) if USE_TMA_LOAD_W: expert_stride = N * K w_desc = tl._experimental_make_tensor_descriptor( w_ptr, shape = [NUM_EXPERTS, N, K], strides = [expert_stride, K, 1], block_shape = [1, BLOCK_SIZE_N, BLOCK_SIZE_K], ) m_end = 0 processed_tiles = 0 m_block_range = tl.arange(0, BLOCK_SIZE_M) n_block_range = tl.arange(0, BLOCK_SIZE_N) k_block_range = tl.arange(0, BLOCK_SIZE_K) for expert_idx in range(NUM_EXPERTS, flatten = FLATTEN): m_start = m_end m_size = tl.load(m_sizes_ptr + expert_idx).to(tl.int32) m_end = m_start + m_size if m_size > 0: # Advance n offset to the weights for that respective expert n_start = expert_idx * N # N_start_offset = g.to(tl.int64) * N # tiles for this group's GEMM num_m_tiles = tl.cdiv(m_size, BLOCK_SIZE_M) num_k_tiles = tl.cdiv(K, BLOCK_SIZE_K) num_tiles_per_expert = num_m_tiles * num_k_tiles if USE_TMA_STORE: # Need to define descript within loop to predicate store along M tl.static_assert( K % BLOCK_SIZE_K == 0, "K must be divisible by BLOCK_SIZE_K" ) dX_desc = tl._experimental_make_tensor_descriptor( dX_ptr, shape = [m_end, K], strides = [K, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_K], ) # Lower bound and upper bound are defined relative to the total tiles processed so far # This ensures that we are only processing tiles for the current expert group AND # we never exceed the total number of tiles for all expert groups while tidx >= processed_tiles and tidx < ( processed_tiles + num_tiles_per_expert ): group_index = tidx - processed_tiles # Output tile for this thread block for this expert group tile_m_idx = group_index % num_m_tiles tile_k_idx = group_index // num_m_tiles if PERMUTE_X or PERMUTE_Y: # These will be used for loading and storing in permuted order gather_offsets = tile_m_idx * BLOCK_SIZE_M + m_block_range # indices_to_gather = m_start + gather_offsets indices_to_gather = m_start + tl.max_contiguous( tl.multiple_of(gather_offsets % m_size, BLOCK_SIZE_M), BLOCK_SIZE_M, ) expert_token_idx = tl.load( gather_indices_ptr + indices_to_gather, mask = indices_to_gather < TOTAL_TOKENS, ) expert_token_offsets = expert_token_idx[:, None] # Masks for permuted load and store row_mask = gather_offsets < m_size row_mask = row_mask[:, None] # We only take into account the following two cases: (PERMUTE_X and NOT PERMUTE_Y) and (NOT PERMUTE_X and PERMUTE_Y) # Hence, we can make the following simplifying assumptions when loading and storing # Note the different strides between the two cases: the offsets for loading and storing are flipped and the strides must also be adjusted if PERMUTE_X: # Case where we permuted on load in the forward pass (typically first grouped GEMM in MoE MLP) load_a_idx = ( indices_to_gather[:, None] * N ) # Load in contiguous (expert grouped) order store_idx = ( expert_token_offsets * K ) # Permute on store from expert -> token order else: # Case where we permuted on store in the forward pass (typically second grouped GEMM in MoE MLP) load_a_idx = ( expert_token_offsets * N ) # Permute on load from token -> expert order store_idx = ( indices_to_gather[:, None] * K ) # Store in contiguous order else: # # Position in full matrix - needed for TMA # m_offset = (M_start + (tile_m_idx * BLOCK_SIZE_M)).to(tl.int32) # k_offset = (tile_k_idx * BLOCK_SIZE_K).to(tl.int32) # Offsets *relative* to the *current* expert -- m_start will then advance to this expert's start token offs_am = tile_m_idx * BLOCK_SIZE_M + m_block_range # [M, N] @ [N, K] -> [M, K] => Stride for A is N, stride for B is K # We need two additional offsets: # 1. For A, m_start to advance to this expert's start token # 2. For B, n_start to advance to this expert's weights since we are passing in an [E, N, K] weight matrix row_offsets_a = m_start + offs_am[:, None] load_a_idx = row_offsets_a * N store_idx = row_offsets_a * K row_mask = offs_am[:, None] < m_size if not USE_TMA_LOAD_dY: dY_ptrs = dY_ptr + load_a_idx + n_block_range[None, :] offs_bk = tile_k_idx * BLOCK_SIZE_K + k_block_range if not USE_TMA_LOAD_W: row_offsets_b = n_start + n_block_range # offs_bn = n_start + n_block_range # row_offsets_b = tl.max_contiguous(tl.multiple_of(offs_bn, BLOCK_SIZE_N), BLOCK_SIZE_N) w_ptrs = w_ptr + row_offsets_b[:, None] * K + offs_bk[None, :] # TODO: check whether predication along K is needed since we checked that K is divisible by BLOCK_SIZE_K in the forward kernel # col_mask = offs_bk[None, :] < K store_mask = row_mask # & col_mask accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_K), dtype = tl.float32) # GEMM main loop for n_offset in range(0, N, BLOCK_SIZE_N): # dY block [M, N] if not USE_TMA_LOAD_dY: dY = tl.load(dY_ptrs, mask = row_mask) else: dY = dY_desc.load( [m_start + tile_m_idx * BLOCK_SIZE_M, n_offset] ) if not USE_TMA_LOAD_W: w = tl.load(w_ptrs) # , mask=col_mask) else: w = w_desc.load( [expert_idx, n_offset, tile_k_idx * BLOCK_SIZE_K] ) w = tl.reshape(w, (BLOCK_SIZE_N, BLOCK_SIZE_K)) # TODO: check if predication along K is needed since we checked that K is divisible by BLOCK_SIZE_K in the forward kernel # [M, N] @ [N, K] -> [M, K] accumulator += tl.dot(dY, w) # NOTE: no transpose of b # Advance A along contiguous dimension if not USE_TMA_LOAD_dY: dY_ptrs += BLOCK_SIZE_N # Note we are no longer advancing B along contiguous dimension since weights are arranged as [N, K] # Instead, we need to stride by K to advance to the [N_BLOCK_SIZE, K_BLOCK_SIZE] tile if not USE_TMA_LOAD_W: w_ptrs += BLOCK_SIZE_N * K dX = accumulator.to(output_dtype) # Writing out a BLOCK_M x BLOCK_K tile, so we need to stride by K if USE_TMA_STORE: offset_m = tile_m_idx * BLOCK_SIZE_M # .to(tl.int32) offset_k = tile_k_idx * BLOCK_SIZE_K # .to(tl.int32) dX_desc.store([m_start + offset_m, offset_k], dX) else: tl.store( dX_ptr + store_idx + offs_bk[None, :], dX, mask = store_mask, ) # Move to the next tile within this expert group tidx += NUM_SMS # Update the total tiles count for the next expert group processed_tiles += num_tiles_per_expert _autotuned_grouped_gemm_dX_kernel = triton.autotune( configs = get_dX_kernel_configs(), prune_configs_by = {"early_config_prune": prune_dX_configs}, key = ["NUM_EXPERTS", "NUM_TOKENS", "N", "K", "PERMUTE_X", "PERMUTE_Y"], )(_grouped_gemm_dX_kernel) """ notes on permute_x: - for the first grouped GEMM, we permuted on load -> X was [num_tokens, K] and stored y in expert grouped order [num_tokens * topk, K] - in the backwards pass, we need to permute on load of X while loading dy in contiguous (expert grouped) order - since we are writing out dW, there is no need to permute on store notes on permute_y: - for the second grouped GEMM, we permuted on store -> y was permuted from expert grouped order to token order, x was loaded in expert grouped order since it was the output of the first grouped GEMM - in the backwards pass, we need to permute on load of dy to get from token order to expert grouped order to match the order of X - since we are writing out dW, there is no need to permute on store notes on TMA loading: - if we're TMA loading both X and dY, then we need to mask along the M dimension to account for expert boundaries - we can either - define TMA descriptors within the outer for loop to predicate loads or - mask along M after loading """ @triton.jit def _grouped_gemm_dW_kernel( x_ptr, dY_ptr, dW_ptr, m_sizes_ptr, gather_indices_ptr, # problem sizes NUM_TOKENS: tl.constexpr, TOPK: tl.constexpr, NUM_EXPERTS: tl.constexpr, N: tl.constexpr, K: tl.constexpr, NUM_SMS: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, BLOCK_SIZE_M: tl.constexpr, PERMUTE_X: tl.constexpr = False, PERMUTE_Y: tl.constexpr = False, USE_TMA_LOAD_dY: tl.constexpr = False, USE_TMA_LOAD_X: tl.constexpr = False, USE_TMA_STORE: tl.constexpr = False, FLATTEN: tl.constexpr = True, acc_dtype: tl.constexpr = tl.float32, ) -> None: TOTAL_TOKENS: tl.constexpr = NUM_TOKENS * TOPK TMA_LOAD_BOTH: tl.constexpr = USE_TMA_LOAD_X and USE_TMA_LOAD_dY tidx = tl.program_id(0) output_dtype = dW_ptr.dtype.element_ty if USE_TMA_LOAD_dY and not TMA_LOAD_BOTH: dY_desc = tl._experimental_make_tensor_descriptor( dY_ptr, shape = [TOTAL_TOKENS, N], strides = [N, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_N], ) if USE_TMA_LOAD_X and not TMA_LOAD_BOTH: x_desc = tl._experimental_make_tensor_descriptor( x_ptr, shape = [TOTAL_TOKENS, K], strides = [K, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_K], ) # Output tiles per expert, since each expert weight matrix is [N, K] num_n_tiles = tl.cdiv(N, BLOCK_SIZE_N) num_k_tiles = tl.cdiv(K, BLOCK_SIZE_K) output_tiles_per_expert = num_n_tiles * num_k_tiles block_range_m = tl.arange(0, BLOCK_SIZE_M) block_range_n = tl.arange(0, BLOCK_SIZE_N) block_range_k = tl.arange(0, BLOCK_SIZE_K) # NOTE: Important that N % BLOCK_SIZE_N == 0 and K % BLOCK_SIZE_K == 0 when using TMA store if USE_TMA_STORE: tl.static_assert(N % BLOCK_SIZE_N == 0, "N must be divisible by BLOCK_SIZE_N") tl.static_assert(K % BLOCK_SIZE_K == 0, "K must be divisible by BLOCK_SIZE_K") dW_desc = tl._experimental_make_tensor_descriptor( dW_ptr, shape = [NUM_EXPERTS, N, K], strides = [N * K, K, 1], block_shape = [1, BLOCK_SIZE_N, BLOCK_SIZE_K], ) for tile_idx in range( tidx, output_tiles_per_expert, NUM_SMS ): # , flatten=FLATTEN): # Output tile index tile_n_idx = tile_idx % num_n_tiles tile_k_idx = tile_idx // num_n_tiles # Output tile offsets n_offset = tile_n_idx * BLOCK_SIZE_N k_offset = tile_k_idx * BLOCK_SIZE_K # For storing # TODO: Check whether the k mask is needed since we statically check that K is divisible by BLOCK_SIZE_K in the forward kernel # ditto for n_mask n_mask = block_range_n + n_offset < N k_mask = block_range_k + k_offset < K nk_mask = n_mask[:, None] & k_mask[None, :] m_end = 0 for expert_idx in range(NUM_EXPERTS): # We need to instantiate a fresh accumulator for each expert accumulator = tl.zeros((BLOCK_SIZE_N, BLOCK_SIZE_K), dtype = acc_dtype) m_start = m_end # Need to figure out why this cast is needed, otherwise compiler complains about mismatching types m_size = tl.load(m_sizes_ptr + expert_idx).to(tl.int32) m_end = m_start + m_size # NOTE: when storing the result, we need to offset by n_start since we are storing the result for this expert to the global [E, N, K] weight matrix n_start = expert_idx * N store_row_offs = n_start + n_offset + block_range_n if m_size > 0: if TMA_LOAD_BOTH: dY_desc = tl._experimental_make_tensor_descriptor( dY_ptr, shape = [m_end, N], strides = [N, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_N], ) x_desc = tl._experimental_make_tensor_descriptor( x_ptr, shape = [m_end, K], strides = [K, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_K], ) for tile_m_idx in range(0, m_size, BLOCK_SIZE_M): m_block_size = tl.minimum(BLOCK_SIZE_M, m_size - tile_m_idx) if m_block_size > 0: # Global offset for this chunk m_global_offset = m_start + tile_m_idx m_offsets = m_global_offset + block_range_m if PERMUTE_X or PERMUTE_Y: # These will be used for loading and storing in permuted order gather_offsets = ( tile_m_idx + block_range_m ) # NOTE: tile_m_idx is already strided by BLOCK_SIZE_M indices_to_gather = m_start + tl.max_contiguous( tl.multiple_of(gather_offsets % m_size, BLOCK_SIZE_M), BLOCK_SIZE_M, ) # indices_to_gather = m_start + gather_offsets expert_token_idx = tl.load( gather_indices_ptr + indices_to_gather, mask = indices_to_gather < TOTAL_TOKENS, ) expert_token_offsets = expert_token_idx[:, None] # Masks for permuted load and store row_load_mask = gather_offsets < m_size # We only take into account the following two cases: (PERMUTE_X and NOT PERMUTE_Y) and (NOT PERMUTE_X and PERMUTE_Y) # Hence, we can make the following simplifying assumptions when loading and storing # Note the different strides between the two cases: the offsets for loading and storing are flipped and the strides must also be adjusted if PERMUTE_X: x_row_load_idx = ( (expert_token_offsets // TOPK) * K ) # Permute on load from token -> expert order, divide by TOPK to index from original number of tokens dY_row_load_idx = m_offsets[:, None] * N else: x_row_load_idx = ( indices_to_gather[:, None] * K ) # Load in contiguous order (no permutation on load) dY_row_load_idx = expert_token_offsets * N else: x_row_load_idx = m_offsets[:, None] * K dY_row_load_idx = m_offsets[:, None] * N row_load_mask = block_range_m < m_block_size mk_mask = row_load_mask[:, None] & k_mask[None, :] mn_mask = row_load_mask[:, None] & n_mask[None, :] if USE_TMA_LOAD_X: x = x_desc.load([m_global_offset, k_offset]) else: x = tl.load( x_ptr + x_row_load_idx + (k_offset + block_range_k)[None, :], mask = mk_mask, ) if USE_TMA_LOAD_dY: dY = dY_desc.load([m_global_offset, n_offset]) else: dY = tl.load( dY_ptr + dY_row_load_idx + (n_offset + block_range_n)[None, :], mask = mn_mask, ) accumulator += tl.dot( dY.T, # [BLOCK_N, BLOCK_M] x, # [BLOCK_M, BLOCK_K] ) y = accumulator.to(output_dtype) if USE_TMA_STORE: # Need to expand dims to match [E, N, K] shape y = tl.expand_dims(y, 0) dW_desc.store([expert_idx, n_offset, k_offset], y) else: tl.store( dW_ptr # + (n_offset + offs_n)[:, None] * K + store_row_offs[:, None] * K + (k_offset + block_range_k)[None, :], y, mask = nk_mask, ) _autotuned_grouped_gemm_dW_kernel = triton.autotune( configs = get_dW_kernel_configs(), prune_configs_by = {"early_config_prune": prune_kernel_configs_backward_dW}, key = ["NUM_EXPERTS", "NUM_TOKENS", "N", "K", "PERMUTE_X", "PERMUTE_Y"], )(_grouped_gemm_dW_kernel)
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/kernels/forward.py
unsloth/kernels/moe/grouped_gemm/kernels/forward.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import torch import triton import triton.language as tl from grouped_gemm.kernels.autotuning import ( get_forward_configs, prune_kernel_configs_fwd, ) # # PERMUTE_X -> permute tokens so that they are ordered by expert # PERMUTE_Y -> permute output so that they are ordered by token # These are effectively the same thing: the former loads in permuted order, the latter stores in permuted order => we only need to define the permutation indices once # In the former, we use these row indices when loading X # For the latter, we use these row indices when storing Y # FUSE_MUL -> multiply routed outputs by their respective weights # topk_weights are in token order # Only account for the case when X is in expert order and we are permuting Y when fusing mul -- this precondition is checked in the interface @triton.jit def _grouped_gemm_forward_kernel( x_ptr, w_ptr, y_ptr, # Variable depending on routed probs m_sizes_ptr, gather_indices_ptr, topk_weights_ptr, # Constant problem shapes NUM_EXPERTS: tl.constexpr, NUM_TOKENS: tl.constexpr, TOPK: tl.constexpr, N: tl.constexpr, K: tl.constexpr, NUM_SMS: tl.constexpr, # Tuning params BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, PERMUTE_X: tl.constexpr = False, PERMUTE_Y: tl.constexpr = False, FUSE_MUL_PRE: tl.constexpr = False, FUSE_MUL_POST: tl.constexpr = False, USE_FAST_ACCUM: tl.constexpr = False, USE_TMA_LOAD_W: tl.constexpr = False, USE_TMA_LOAD_X: tl.constexpr = False, USE_TMA_STORE: tl.constexpr = False, acc_dtype: tl.constexpr = tl.float32, FLATTEN: tl.constexpr = True, ) -> None: tl.static_assert(K % BLOCK_SIZE_K == 0) TOTAL_TOKENS: tl.constexpr = NUM_TOKENS * TOPK SHOULD_PERMUTE: tl.constexpr = PERMUTE_X or PERMUTE_Y SHOULD_FUSE_MUL: tl.constexpr = FUSE_MUL_PRE or FUSE_MUL_POST SHOULD_PERMUTE_OR_FUSE: tl.constexpr = SHOULD_PERMUTE or SHOULD_FUSE_MUL # tl.static_print("SHOULD_PERMUTE", PERMUTE_X, PERMUTE_Y, FUSE_MUL_PRE, FUSE_MUL_POST, SHOULD_PERMUTE, SHOULD_FUSE, SHOULD_PERMUTE_OR_FUSE) tidx = tl.program_id(0) output_dtype: tl.dtype = y_ptr.dtype.element_ty # Create TMA descriptors for loading sorted tokens # When using TMA load, we don't permute_x, so shape should be [TOTAL_TOKENS, K] # Also, we are defining a single global descriptor with single block shape # Need to check that this does not result in errors when crossing expert boundaries if USE_TMA_LOAD_X: x_desc = tl._experimental_make_tensor_descriptor( x_ptr, shape = [TOTAL_TOKENS, K], strides = [K, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_K], ) if USE_TMA_LOAD_W: expert_stride = N * K w_desc = tl._experimental_make_tensor_descriptor( w_ptr, shape = [NUM_EXPERTS, N, K], strides = [expert_stride, K, 1], block_shape = [1, BLOCK_SIZE_N, BLOCK_SIZE_K], ) m_end = 0 processed_tiles = 0 m_block_range = tl.arange(0, BLOCK_SIZE_M) for expert_idx in tl.range(NUM_EXPERTS, flatten = FLATTEN): m_start = m_end m_size = tl.load(m_sizes_ptr + expert_idx).to(tl.int32) m_end = m_start + m_size if m_size > 0: n_start = expert_idx * N num_m_tiles = tl.cdiv(m_size, BLOCK_SIZE_M) num_n_tiles = tl.cdiv(N, BLOCK_SIZE_N) num_tiles_per_expert = num_m_tiles * num_n_tiles # Need to create tma_store within loop since we need to predicate stores based on m_size if USE_TMA_STORE: y_desc = tl._experimental_make_tensor_descriptor( y_ptr, # + m_start * N, shape = [m_end, N], strides = [N, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_N], ) # Process tiles for this expert while ( tidx >= processed_tiles and tidx < processed_tiles + num_tiles_per_expert ): tile_idx = tidx - processed_tiles # Check if L2 cache re-use for this order is optimal tile_m_idx = tile_idx % num_m_tiles tile_n_idx = tile_idx // num_m_tiles if SHOULD_PERMUTE_OR_FUSE: # These will be used for loading and storing in permuted order gather_offsets = tile_m_idx * BLOCK_SIZE_M + m_block_range indices_to_gather = m_start + tl.max_contiguous( tl.multiple_of(gather_offsets % m_size, BLOCK_SIZE_M), BLOCK_SIZE_M, ) expert_token_idx = tl.load( gather_indices_ptr + indices_to_gather, mask = indices_to_gather < TOTAL_TOKENS, ) expert_token_offsets = expert_token_idx[:, None] # Masks for permuted load and store row_mask = gather_offsets < m_size row_mask = row_mask[:, None] # row_mask = indices_to_gather < m_end # row_mask = row_mask[:, None] # We only take into account the following two cases: (PERMUTE_X and NOT PERMUTE_Y) and (NOT PERMUTE_X and PERMUTE_Y) # Hence, we can make the following simplifying assumptions when loading and storing # Note the different strides between the two cases: the offsets for loading and storing are flipped and the strides must also be adjusted if PERMUTE_X: load_idx = ( (expert_token_offsets // TOPK) * K ) # Permute on load from token -> expert order, divide by TOPK to index from original number of tokens store_idx = ( indices_to_gather[:, None] * N ) # Store in contiguous order else: off_am = tile_m_idx * BLOCK_SIZE_M if not PERMUTE_Y: # These will already be computed if permuting y offs_am = off_am + m_block_range row_mask = offs_am[:, None] < m_size row_idx = m_start + offs_am[:, None] store_idx = row_idx * N if not USE_TMA_LOAD_X: load_idx = row_idx * K if PERMUTE_Y: if not USE_TMA_LOAD_X: load_idx = ( indices_to_gather[:, None] * K ) # Load in contiguous order (no permutation on load) # offs_am = off_am + m_block_range # row_mask = offs_am[:, None] < m_size store_idx = ( expert_token_offsets * N ) # Permute on store from expert -> token order # We always load topk weights in expert order # In the pre-multiplication case, we multiply permuted hidden states by weights before the first gemm # In the post-multiplication case, we multiply permuted hidden states by weights after the second gemm # In either case, the hidden states are grouped by expert, so we always permute on load of topk weights if SHOULD_FUSE_MUL: topk_load_idx = expert_token_offsets accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype = acc_dtype) offs_k = tl.arange(0, BLOCK_SIZE_K) if not USE_TMA_LOAD_X: x_ptrs = x_ptr + load_idx + offs_k[None, :] if not USE_TMA_LOAD_W: offs_bn = tile_n_idx * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) offs_bn = tl.max_contiguous( tl.multiple_of(offs_bn % N, BLOCK_SIZE_N), BLOCK_SIZE_N ) w_ptrs = w_ptr + (n_start + offs_bn[:, None]) * K + offs_k[None, :] for k_offset in range(0, K, BLOCK_SIZE_K): if not USE_TMA_LOAD_X: x = tl.load(x_ptrs, mask = row_mask) else: x = x_desc.load([m_start + off_am, k_offset]) if FUSE_MUL_PRE: # Check for correct broadcasting topk_weights = tl.load( topk_weights_ptr + topk_load_idx, mask = row_mask ) x *= topk_weights.to(x.dtype) if not USE_TMA_LOAD_W: w = tl.load(w_ptrs, mask = offs_bn[:, None] < N) else: w = w_desc.load( [expert_idx, tile_n_idx * BLOCK_SIZE_N, k_offset] ) w = tl.reshape(w, (BLOCK_SIZE_N, BLOCK_SIZE_K)) accumulator += tl.dot(x, w.T) if not USE_TMA_LOAD_X: x_ptrs += BLOCK_SIZE_K if not USE_TMA_LOAD_W: w_ptrs += BLOCK_SIZE_K y = accumulator.to(output_dtype) # NOTE: order of fusing multiplication is important # Fusing before accumulator dtype conversion results in numerical diffs if FUSE_MUL_POST: # Check for correct broadcasting topk_weights = tl.load( topk_weights_ptr + topk_load_idx, mask = row_mask ) y *= topk_weights.to(output_dtype) offs_bn = tile_n_idx * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) store_mask = row_mask & (offs_bn[None, :] < N) if USE_TMA_STORE: offset_m = tile_m_idx * BLOCK_SIZE_M # .to(tl.int32) offset_n = tile_n_idx * BLOCK_SIZE_N # .to(tl.int32) y_desc.store([m_start + offset_m, offset_n], y) else: tl.store( y_ptr + store_idx + offs_bn[None, :], y, mask = store_mask, ) tidx += NUM_SMS processed_tiles += num_tiles_per_expert _autotuned_grouped_gemm_forward_kernel = triton.autotune( configs = get_forward_configs(), prune_configs_by = {"early_config_prune": prune_kernel_configs_fwd}, key = [ "NUM_EXPERTS", "NUM_TOKENS", "N", "K", "PERMUTE_X", "PERMUTE_Y", "FUSE_MUL_POST", ], )(_grouped_gemm_forward_kernel)
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/kernels/__init__.py
unsloth/kernels/moe/grouped_gemm/kernels/__init__.py
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
unslothai/unsloth
https://github.com/unslothai/unsloth/blob/85bfdaf7ab3c32f95f98f3e3927164797fcc6d46/unsloth/kernels/moe/grouped_gemm/kernels/autotuning.py
unsloth/kernels/moe/grouped_gemm/kernels/autotuning.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. """ Autotuning utils """ import logging from itertools import product from typing import List import torch import triton logger = logging.getLogger(__name__) DEFAULT_M_BLOCK_SIZES = [64, 128] DEFAULT_N_BLOCK_SIZES = [64, 128, 256] DEFAULT_K_BLOCK_SIZES = [64, 128, 256] DEFAULT_NUM_CTAS = 1 DEFAULT_NUM_WARPS = [4, 8] DEFAULT_NUM_STAGES = [3, 4, 5] BOOLS = [True, False] def val_to_list(val): if val is None: return None elif isinstance(val, list): return val else: return [val] def convert_args_to_list(args): return [val_to_list(arg) for arg in args] def get_forward_configs( BLOCK_M = DEFAULT_M_BLOCK_SIZES, BLOCK_N = DEFAULT_N_BLOCK_SIZES, BLOCK_K = DEFAULT_K_BLOCK_SIZES, TMA_LOAD_X = True, TMA_LOAD_W = True, TMA_STORE = False, # NOTE: TMA_STORE is disabled for now num_warps = DEFAULT_NUM_WARPS, num_stages = DEFAULT_NUM_STAGES, num_ctas = DEFAULT_NUM_CTAS, ): ( BLOCK_M, BLOCK_N, BLOCK_K, TMA_LOAD_X, TMA_LOAD_W, TMA_STORE, num_warps, num_stages, num_ctas, ) = convert_args_to_list( [ BLOCK_M, BLOCK_N, BLOCK_K, TMA_LOAD_X, TMA_LOAD_W, TMA_STORE, num_warps, num_stages, num_ctas, ] ) kernel_configs = [] for ( block_m, block_n, block_k, w, s, tma_load_x, tma_load_w, tma_store, num_ctas, ) in product( BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, TMA_LOAD_X, TMA_LOAD_W, TMA_STORE, num_ctas, ): kernel_configs.append( triton.Config( dict( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, USE_TMA_LOAD_X = tma_load_x, USE_TMA_LOAD_W = tma_load_w, USE_TMA_STORE = tma_store, ), num_warps = w, num_stages = s, num_ctas = num_ctas, ) ) return kernel_configs def get_dX_kernel_configs( BLOCK_M = DEFAULT_M_BLOCK_SIZES, BLOCK_N = DEFAULT_N_BLOCK_SIZES, BLOCK_K = DEFAULT_K_BLOCK_SIZES, TMA_LOAD_dY = True, TMA_LOAD_W = True, TMA_STORE = False, # NOTE: TMA_STORE is disabled for now num_warps = DEFAULT_NUM_WARPS, num_stages = DEFAULT_NUM_STAGES, num_ctas = DEFAULT_NUM_CTAS, ): ( BLOCK_M, BLOCK_N, BLOCK_K, TMA_LOAD_dY, TMA_LOAD_W, TMA_STORE, num_warps, num_stages, num_ctas, ) = convert_args_to_list( [ BLOCK_M, BLOCK_N, BLOCK_K, TMA_LOAD_dY, TMA_LOAD_W, TMA_STORE, num_warps, num_stages, num_ctas, ] ) kernel_configs = [] for ( block_m, block_n, block_k, w, s, tma_load_dy, tma_load_w, tma_store, num_ctas, ) in product( BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, TMA_LOAD_dY, TMA_LOAD_W, TMA_STORE, num_ctas, ): kernel_configs.append( triton.Config( dict( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, USE_TMA_LOAD_dY = tma_load_dy, USE_TMA_LOAD_W = tma_load_w, USE_TMA_STORE = tma_store, ), num_warps = w, num_stages = s, num_ctas = num_ctas, ) ) return kernel_configs def get_dW_kernel_configs( BLOCK_M = DEFAULT_M_BLOCK_SIZES, BLOCK_N = DEFAULT_N_BLOCK_SIZES, BLOCK_K = DEFAULT_K_BLOCK_SIZES, num_warps = DEFAULT_NUM_WARPS, num_stages = DEFAULT_NUM_STAGES, num_ctas = DEFAULT_NUM_CTAS, TMA_LOAD_dY = True, TMA_LOAD_X = True, TMA_STORE = False, ): ( BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, num_ctas, TMA_LOAD_dY, TMA_LOAD_X, TMA_STORE, ) = convert_args_to_list( [ BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, num_ctas, TMA_LOAD_dY, TMA_LOAD_X, TMA_STORE, ] ) kernel_configs = [] for ( block_m, block_n, block_k, w, s, tma_load_dy, tma_load_x, tma_store, num_ctas, ) in product( BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, TMA_LOAD_dY, TMA_LOAD_X, TMA_STORE, num_ctas, ): kernel_configs.append( triton.Config( dict( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, USE_TMA_LOAD_dY = tma_load_dy, USE_TMA_LOAD_X = tma_load_x, USE_TMA_STORE = tma_store, ), num_warps = w, num_stages = s, num_ctas = num_ctas, ) ) return kernel_configs def estimate_smem_reqs( num_stages: int, BLOCK_SIZE_M: int, BLOCK_SIZE_N: int, BLOCK_SIZE_K: int, dtype: torch.dtype, ): num_bytes = dtype.itemsize return ( num_stages * BLOCK_SIZE_K * (BLOCK_SIZE_M + BLOCK_SIZE_N) + BLOCK_SIZE_M * BLOCK_SIZE_N ) * num_bytes def exceeds_smem_capacity( num_stages: int, BLOCK_SIZE_M: int, BLOCK_SIZE_N: int, BLOCK_SIZE_K: int, dtype: torch.dtype, smem_size: int, slack: float = 50000, ): smem_reqs = estimate_smem_reqs( num_stages, BLOCK_SIZE_M, BLOCK_SIZE_N, BLOCK_SIZE_K, dtype ) return smem_reqs > smem_size + slack def common_prune_criteria(config: triton.Config, kwargs: dict, dtype): from grouped_gemm.interface import supports_tma from grouped_gemm.kernels.tuning import get_device_properties smem_size = get_device_properties().SIZE_SMEM num_stages = config.num_stages BLOCK_SIZE_M = config.kwargs["BLOCK_SIZE_M"] BLOCK_SIZE_N = config.kwargs["BLOCK_SIZE_N"] BLOCK_SIZE_K = config.kwargs["BLOCK_SIZE_K"] num_tokens = kwargs["NUM_TOKENS"] num_experts = kwargs["NUM_EXPERTS"] permute_x = kwargs["PERMUTE_X"] permute_y = kwargs["PERMUTE_Y"] tokens_per_expert = num_tokens // num_experts # use_tma = [k for k in config.kwargs.keys() if k.startswith("USE_TMA_")] MIN_BLOCK_SIZE_M = DEFAULT_M_BLOCK_SIZES[0] if exceeds_smem_capacity( num_stages, BLOCK_SIZE_M, BLOCK_SIZE_N, BLOCK_SIZE_K, dtype, smem_size ): return True if BLOCK_SIZE_M > tokens_per_expert * 2 and tokens_per_expert > MIN_BLOCK_SIZE_M: return True if permute_x and permute_y: return True # if not supports_tma() and any(use_tma): # return True return False def maybe_disable_tma(config: triton.Config): from grouped_gemm.interface import supports_tma tma_keys = [k for k in config.kwargs.keys() if k.startswith("USE_TMA_")] if not supports_tma(): logger.info("Disabling TMA") for k in tma_keys: config.kwargs[k] = False def prune_kernel_configs_fwd(configs: list[triton.Config], args, **kwargs): x = kwargs["x_ptr"] dtype = x.dtype logger.debug(f"Pruning configs: {len(configs)}") pruned_configs = [] for config in configs: # disable TMA if gpu does not support it maybe_disable_tma(config) if common_prune_criteria(config, kwargs, dtype): continue if config.kwargs["USE_TMA_LOAD_X"] and kwargs["PERMUTE_X"]: # Dynamically disable TMA_LOAD_X for permuted X config.kwargs["USE_TMA_LOAD_X"] = False if config.kwargs["USE_TMA_STORE"] and kwargs["PERMUTE_Y"]: continue pruned_configs.append(config) logger.debug(f"Pruned configs: {len(pruned_configs)}") return pruned_configs def prune_dX_configs(configs: List[triton.Config], args, **kwargs): dtype = kwargs["w_ptr"].dtype logger.debug(f"Pruning configs: {len(configs)}") pruned_configs = [] for config in configs: if common_prune_criteria(config, kwargs, dtype): continue if config.kwargs["USE_TMA_LOAD_dY"] and kwargs["PERMUTE_Y"]: # dynamically disable TMA_LOAD_dY for permuted Y config.kwargs["USE_TMA_LOAD_dY"] = False if config.kwargs["USE_TMA_STORE"] and kwargs["PERMUTE_X"]: continue pruned_configs.append(config) logger.debug(f"Pruned configs: {len(pruned_configs)}") return pruned_configs def prune_kernel_configs_backward_dW(configs: list[triton.Config], args, **kwargs): dtype = kwargs["x_ptr"].dtype pruned_configs = [] logger.debug(f"Pruning configs: {len(configs)}") for config in configs: if common_prune_criteria(config, kwargs, dtype): continue if config.kwargs["USE_TMA_LOAD_dY"] and kwargs["PERMUTE_Y"]: config.kwargs["USE_TMA_LOAD_dY"] = False if config.kwargs["USE_TMA_LOAD_X"] and kwargs["PERMUTE_X"]: config.kwargs["USE_TMA_LOAD_X"] = False pruned_configs.append(config) logger.debug(f"Pruned configs: {len(pruned_configs)}") return pruned_configs
python
Apache-2.0
85bfdaf7ab3c32f95f98f3e3927164797fcc6d46
2026-01-04T14:39:29.397284Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/setup.py
setup.py
#!/usr/bin/env python # This is a shim to hopefully allow Github to detect the package, build is done with poetry import setuptools if __name__ == "__main__": setuptools.setup(name="rich")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/benchmarks/benchmarks.py
benchmarks/benchmarks.py
from io import StringIO from benchmarks import snippets from rich.color import Color, ColorSystem from rich.console import Console from rich.pretty import Pretty from rich.segment import Segment from rich.style import Style from rich.syntax import Syntax from rich.table import Table from rich.text import Text class TextSuite: def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False ) self.len_lorem_ipsum = len(snippets.LOREM_IPSUM) self.text = Text.from_markup(snippets.MARKUP) def time_wrapping(self): self.text.wrap(self.console, 12, overflow="fold") def time_indent_guides(self): Text(snippets.PYTHON_SNIPPET).with_indent_guides() def time_fit(self): Text(snippets.LOREM_IPSUM).fit(12) def time_split(self): self.text.split() def time_divide(self): Text(snippets.LOREM_IPSUM).divide(range(20, 100, 4)) def time_align_center(self): Text(snippets.LOREM_IPSUM).align("center", width=self.len_lorem_ipsum * 3) def time_render(self): list(self.text.render(self.console)) def time_wrapping_unicode_heavy(self): Text(snippets.UNICODE_HEAVY_TEXT).wrap(self.console, 12, overflow="fold") def time_fit_unicode_heavy(self): Text(snippets.UNICODE_HEAVY_TEXT).fit(12) def time_split_unicode_heavy(self): Text(snippets.UNICODE_HEAVY_TEXT).split() def time_divide_unicode_heavy(self): self.text.divide(range(20, 100, 4)) def time_align_center_unicode_heavy(self): Text(snippets.UNICODE_HEAVY_TEXT).align( "center", width=self.len_lorem_ipsum * 3 ) def time_render_unicode_heavy(self): list(Text(snippets.UNICODE_HEAVY_TEXT).render(self.console)) class TextHotCacheSuite: def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False ) def time_wrapping_unicode_heavy_warm_cache(self): for _ in range(20): Text(snippets.UNICODE_HEAVY_TEXT).wrap(self.console, 12, overflow="fold") class SyntaxWrappingSuite: def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False ) self.syntax = Syntax( code=snippets.PYTHON_SNIPPET, lexer="python", word_wrap=True ) def time_text_thin_terminal_heavy_wrapping(self): self._print_with_width(20) def time_text_thin_terminal_medium_wrapping(self): self._print_with_width(60) def time_text_wide_terminal_no_wrapping(self): self._print_with_width(100) def _print_with_width(self, width): self.console.print(self.syntax, width) class TableSuite: def time_table_no_wrapping(self): self._print_table(width=100) def time_table_heavy_wrapping(self): self._print_table(width=30) def _print_table(self, width): table = Table(title="Star Wars Movies") console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False, width=width ) table.add_column("Released", justify="right", style="cyan", no_wrap=True) table.add_column("Title", style="magenta") table.add_column("Box Office", justify="right", style="green") table.add_row( "Dec 20, 2019", "[b]Star Wars[/]: The Rise of Skywalker", "$952,110,690" ) table.add_row( "May 25, 2018", "Solo: A [red][b]Star Wars[/] Story[/]", "$393,151,347" ) table.add_row( "Dec 15, 2017", "[b red]Star Wars[/] Ep. V111: The Last Jedi", "$1,332,539,889", ) table.add_row( "Dec 16, 2016", "Rogue One: A [blue]Star Wars[/] Story", "$1,332,439,889" ) console.print(table) class PrettySuite: def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False, width=100 ) def time_pretty(self): pretty = Pretty(snippets.PYTHON_DICT) self.console.print(pretty) def time_pretty_indent_guides(self): pretty = Pretty(snippets.PYTHON_DICT, indent_guides=True) self.console.print(pretty) def time_pretty_justify_center(self): pretty = Pretty(snippets.PYTHON_DICT, justify="center") self.console.print(pretty) class StyleSuite: def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False, width=100 ) self.style1 = Style.parse("blue on red") self.style2 = Style.parse("green italic bold") def time_parse_ansi(self): Style.parse("red on blue") def time_parse_hex(self): Style.parse("#f0f0f0 on #e2e28a") def time_parse_mixed_complex_style(self): Style.parse("dim bold reverse #00ee00 on rgb(123,12,50)") def time_style_add(self): self.style1 + self.style2 class ColorSuite: def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False, width=100 ) self.color = Color.parse("#0d1da0") def time_downgrade_to_eight_bit(self): self.color.downgrade(ColorSystem.EIGHT_BIT) def time_downgrade_to_standard(self): self.color.downgrade(ColorSystem.STANDARD) def time_downgrade_to_windows(self): self.color.downgrade(ColorSystem.WINDOWS) class ColorSuiteCached: def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False, width=100 ) self.color = Color.parse("#0d1da0") # Warm cache self.color.downgrade(ColorSystem.EIGHT_BIT) self.color.downgrade(ColorSystem.STANDARD) self.color.downgrade(ColorSystem.WINDOWS) def time_downgrade_to_eight_bit(self): self.color.downgrade(ColorSystem.EIGHT_BIT) def time_downgrade_to_standard(self): self.color.downgrade(ColorSystem.STANDARD) def time_downgrade_to_windows(self): self.color.downgrade(ColorSystem.WINDOWS) class SegmentSuite: def setup(self): self.line = [ Segment("foo"), Segment("bar"), Segment("egg"), Segment("Where there is a Will"), Segment("There is a way"), ] * 2 def test_divide_complex(self): list(Segment.divide(self.line, [5, 10, 20, 50, 108, 110, 118]))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/benchmarks/__init__.py
benchmarks/__init__.py
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/benchmarks/snippets.py
benchmarks/snippets.py
PYTHON_SNIPPET = ''' def layout_resolve(total: int, edges: Sequence[EdgeProtocol]) -> List[int]: """Divide total space to satisfy size, fraction, and min_size, constraints. The returned list of integers should add up to total in most cases, unless it is impossible to satisfy all the constraints. For instance, if there are two edges with a minimum size of 20 each and `total` is 30 then the returned list will be greater than total. In practice, this would mean that a Layout object would clip the rows that would overflow the screen height. Args: total (int): Total number of characters. edges (Sequence[Edge]): Edges within total space. Returns: list[int]: Number of characters for each edge. """ # Size of edge or None for yet to be determined sizes = [(edge.size or None) for edge in edges] if None not in sizes: # No flexible edges return cast("list[int]", sizes) # Get flexible edges and index to map these back on to sizes list flexible_edges = [ (index, edge) for index, (size, edge) in enumerate(zip(sizes, edges)) if size is None ] # Remaining space in total remaining = total - sum([size or 0 for size in sizes]) if remaining <= 0: # No room for flexible edges return [ ((edge.min_size or 1) if size is None else size) for size, edge in zip(sizes, edges) ] # Get the total fraction value for all flexible edges total_flexible = sum([(edge.fraction or 1) for _, edge in flexible_edges]) while flexible_edges: # Calculate number of characters in a ratio portion portion = Fraction(remaining, total_flexible) # If any edges will be less than their minimum, replace size with the minimum for flexible_index, (index, edge) in enumerate(flexible_edges): if portion * edge.fraction < edge.min_size: # This flexible edge will be smaller than its minimum size # We need to fix the size and redistribute the outstanding space sizes[index] = edge.min_size remaining -= edge.min_size total_flexible -= edge.fraction or 1 del flexible_edges[flexible_index] # New fixed size will invalidate calculations, so we need to repeat the process break else: # Distribute flexible space and compensate for rounding error # Since edge sizes can only be integers we need to add the remainder # to the following line remainder = Fraction(0) for index, edge in flexible_edges: sizes[index], remainder = divmod(portion * edge.fraction + remainder, 1) break # Sizes now contains integers only return cast("list[int]", sizes) ''' PYTHON_DICT = { "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"], }, "GlossSee": "markup", } }, }, } } LOREM_IPSUM = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Laoreet id donec ultrices tincidunt arcu. Eu facilisis sed odio morbi quis commodo odio aenean sed. Amet cursus sit amet dictum. Gravida rutrum quisque non tellus. Semper auctor neque vitae tempus quam pellentesque nec nam. Mauris sit amet massa vitae tortor condimentum lacinia quis. Adipiscing elit ut aliquam purus sit amet luctus venenatis lectus. Consectetur adipiscing elit ut aliquam purus sit amet. Sit amet mauris commodo quis imperdiet massa tincidunt nunc pulvinar. Dui faucibus in ornare quam viverra. Et netus et malesuada fames ac turpis. A lacus vestibulum sed arcu non odio euismod. In massa tempor nec feugiat nisl pretium fusce. Tellus in hac habitasse platea dictumst vestibulum. Feugiat nibh sed pulvinar proin. In cursus turpis massa tincidunt dui ut. Fermentum posuere urna nec tincidunt praesent semper feugiat. Interdum consectetur libero id faucibus. Habitant morbi tristique senectus et netus et malesuada fames ac. Facilisis leo vel fringilla est ullamcorper eget nulla facilisi. Aliquam faucibus purus in massa tempor. Tellus pellentesque eu tincidunt tortor aliquam nulla. Sem et tortor consequat id porta nibh. Massa id neque aliquam vestibulum morbi blandit cursus risus. Ut placerat orci nulla pellentesque dignissim enim. Nibh tellus molestie nunc non blandit massa enim nec dui. Ipsum a arcu cursus vitae congue mauris rhoncus aenean vel. Egestas congue quisque egestas diam in. Pulvinar mattis nunc sed blandit libero volutpat sed. Accumsan in nisl nisi scelerisque eu. Eget aliquet nibh praesent tristique. Ipsum suspendisse ultrices gravida dictum fusce ut. Non sodales neque sodales ut etiam sit amet. Velit egestas dui id ornare. Massa ultricies mi quis hendrerit dolor magna. Id volutpat lacus laoreet non curabitur gravida arcu. Nulla facilisi cras fermentum odio eu feugiat pretium. Sed vulputate odio ut enim blandit volutpat. Amet massa vitae tortor condimentum lacinia. Tellus integer feugiat scelerisque varius. Quam nulla porttitor massa id. Facilisi cras fermentum odio eu feugiat pretium nibh ipsum. Eget nunc scelerisque viverra mauris in aliquam sem fringilla. Amet nulla facilisi morbi tempus iaculis urna id volutpat lacus. Facilisi etiam dignissim diam quis enim lobortis. Nullam vehicula ipsum a arcu cursus vitae congue mauris rhoncus. Ullamcorper a lacus vestibulum sed arcu non. Suscipit adipiscing bibendum est ultricies integer quis auctor elit. Integer feugiat scelerisque varius morbi enim. Posuere urna nec tincidunt praesent semper feugiat nibh sed pulvinar. Lobortis feugiat vivamus at augue eget. Rhoncus dolor purus non enim praesent. Mi in nulla posuere sollicitudin aliquam ultrices sagittis orci. Mollis aliquam ut porttitor leo. Id cursus metus aliquam eleifend mi in nulla. Integer eget aliquet nibh praesent tristique magna sit amet. Egestas maecenas pharetra convallis posuere morbi. Blandit massa enim nec dui. Suscipit tellus mauris a diam maecenas. Sed id semper risus in. Purus faucibus ornare suspendisse sed nisi lacus. At in tellus integer feugiat. Egestas diam in arcu cursus euismod quis viverra nibh cras. Enim tortor at auctor urna nunc id. Tristique nulla aliquet enim tortor at auctor urna nunc id. Purus gravida quis blandit turpis cursus in hac habitasse platea. Ac turpis egestas integer eget. Tortor at auctor urna nunc. Neque aliquam vestibulum morbi blandit cursus. Massa tempor nec feugiat nisl pretium fusce id velit. Interdum consectetur libero id faucibus nisl tincidunt. Adipiscing diam donec adipiscing tristique risus nec feugiat in. Egestas integer eget aliquet nibh praesent tristique magna sit. """ UNICODE_HEAVY_TEXT = """ Richは、 _リッチ_ なテキストや美しい書式設定をターミナルで行うためのPythonライブラリです。 [Rich API](https://rich.readthedocs.io/en/latest/)を使用すると、ターミナルの出力に色やスタイルを簡単に追加することができます。 Richはきれいなテーブル、プログレスバー、マークダウン、シンタックスハイライトされたソースコード、トレースバックなどをすぐに生成・表示することもできます。 ![機能](https://github.com/textualize/rich/raw/master/imgs/features.png) Richの紹介動画はこちらをご覧ください。 [calmcode.io](https://calmcode.io/rich/introduction.html) by [@fishnets88](https://twitter.com/fishnets88). [Richについての人々の感想を見る。](https://www.willmcgugan.com/blog/pages/post/rich-tweets/) ## 互換性 RichはLinux、OSX、Windowsに対応しています。True colorと絵文字は新しい Windows ターミナルで動作しますが、古いターミナルでは8色に制限されています。Richを使用するにはPythonのバージョンは3.6.3以降が必要です。 Richは追加の設定を行わずとも、[Jupyter notebooks](https://jupyter.org/)で動作します。 ## インストール `pip` や、あなたのお気に入りのPyPIパッケージマネージャを使ってインストールしてください。 ```sh python -m pip install rich ``` 以下のコマンドを実行して、ターミナルでリッチの出力をテストできます: ```sh python -m rich ``` ## Richのprint関数 簡単にリッチな出力をアプリケーションに追加するには、Pythonの組み込み関数と同じ名前を持つ [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start) メソッドをインポートすることで実現できます。こちらを試してみてください: ```python from rich import print print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals()) ``` ![Hello World](https://github.com/textualize/rich/raw/master/imgs/print.png) ## Rich REPL RichはPythonのREPLでインストールすることができ、データ構造がきれいに表示され、ハイライトされます。 ```python >>> from rich import pretty >>> pretty.install() ``` ![REPL](https://github.com/textualize/rich/raw/master/imgs/repl.png) ## Rich Inspect RichにはPythonオブジェクトやクラス、インスタンス、組み込み関数などに関するレポートを作成することができる、[inspect関数](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect)があります。 の使い方 リッチなターミナルコンテンツをより制御していくには、[Console](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console) オブジェクトをインポートして構築していきます。 Console オブジェクトには `print` メソッドがあり、これは組み込み関数の `print` と意図的に似たインターフェイスを持っています。 以下に使用例を示します: あなたが予想した通り、これは `"Hello World!"` をターミナルに表示します。組み込み関数の `print` とは異なり、Rich はターミナルの幅に合わせてテキストをワードラップすることに注意してください。 出力結果に色やスタイルを追加する方法はいくつかあります。キーワード引数に `style` を追加することで、出力結果全体のスタイルを設定することができます。以下に例を示します: """ MARKUP = "\n".join( """[bold]Hello [i]World[/i] [bold magenta]foo [i]bar[/i] baz[/] [blue u]https://textualize.io[/]""" for _ in range(20) )
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tools/profile_divide.py
tools/profile_divide.py
from rich.segment import Segment text = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.""" segments = [Segment(text[n : n + 7]) for n in range(0, len(text), 7)] from time import perf_counter start = perf_counter() for _ in range(10000): list(Segment.divide(segments, [0, 1, 20, 24, 65, len(text)])) print(perf_counter() - start)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tools/profile_pretty.py
tools/profile_pretty.py
import json import io from time import time from rich.console import Console from rich.pretty import Pretty console = Console(file=io.StringIO(), color_system="truecolor", width=100) with open("cats.json") as fh: cats = json.load(fh) console.begin_capture() start = time() pretty = Pretty(cats) console.print(pretty, overflow="ignore", crop=False) result = console.end_capture() taken = (time() - start) * 1000 print(result) print(console.file.getvalue()) print(f"{taken:.1f}")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tools/make_emoji.py
tools/make_emoji.py
try: import emoji except ImportError: print("pip install emoji") raise from emoji.unicode_codes import EMOJI_ALIAS_UNICODE emoji = {k.lower().strip(":"): v for k, v in EMOJI_ALIAS_UNICODE.items()} with open("_emoji_codes.py", "wt") as f: f.write("EMOJI=" + str(emoji))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tools/make_terminal_widths.py
tools/make_terminal_widths.py
import subprocess from typing import List, Tuple import sys from rich.progress import Progress from wcwidth import wcwidth progress = Progress() def make_widths_table() -> List[Tuple[int, int, int]]: table: List[Tuple[int, int, int]] = [] append = table.append make_table_task = progress.add_task("Calculating table...") widths = ( (codepoint, wcwidth(chr(codepoint))) for codepoint in range(0, sys.maxunicode + 1) ) _widths = [(codepoint, width) for codepoint, width in widths if width != 1] iter_widths = iter(_widths) endpoint, group_cell_size = next(iter_widths) start_codepoint = end_codepoint = endpoint for codepoint, cell_size in progress.track( iter_widths, task_id=make_table_task, total=len(_widths) - 1 ): if cell_size != group_cell_size or codepoint != end_codepoint + 1: append((start_codepoint, end_codepoint, group_cell_size)) start_codepoint = end_codepoint = codepoint group_cell_size = cell_size else: end_codepoint = codepoint append((start_codepoint, end_codepoint, group_cell_size)) return table def get_cell_size(table: List[Tuple[int, int, int]], character: str) -> int: codepoint = ord(character) lower_bound = 0 upper_bound = len(table) - 1 index = (lower_bound + upper_bound) // 2 while True: start, end, width = table[index] if codepoint < start: upper_bound = index - 1 elif codepoint > end: lower_bound = index + 1 else: return width if upper_bound < lower_bound: break index = (lower_bound + upper_bound) // 2 return 1 def test(widths_table): for codepoint in progress.track( range(0, sys.maxunicode + 1), description="Testing..." ): character = chr(codepoint) width1 = get_cell_size(widths_table, character) width2 = wcwidth(character) if width1 != width2: print(f"{width1} != {width2}") break def run(): with progress: widths_table = make_widths_table() test(widths_table) table_file = f"""# Auto generated by make_terminal_widths.py CELL_WIDTHS = {widths_table!r} """ with open("../rich/_cell_widths.py", "wt") as fh: fh.write(table_file) subprocess.run("black ../rich/_cell_widths.py", shell=True) if __name__ == "__main__": run()
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tools/stress_test_pretty.py
tools/stress_test_pretty.py
from rich.console import Console from rich.panel import Panel from rich.pretty import Pretty from rich._timer import timer DATA = { "foo": [1, 2, 3, (), {}, (1, 2, 3), {4, 5, 6, (7, 8, 9)}, "Hello, World"], "bar": [None, (False, True)] * 2, "Dune": { "names": { "Paul Atreides", "Vladimir Harkonnen", "Thufir Hawat", "Duncan Idaho", } }, } console = Console() with timer("Stress test"): for w in range(130): console.print(Panel(Pretty(DATA, indent_guides=True), width=w))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/columns.py
rich/columns.py
from collections import defaultdict from itertools import chain from operator import itemgetter from typing import Dict, Iterable, List, Optional, Tuple from .align import Align, AlignMethod from .console import Console, ConsoleOptions, RenderableType, RenderResult from .constrain import Constrain from .measure import Measurement from .padding import Padding, PaddingDimensions from .table import Table from .text import TextType from .jupyter import JupyterMixin class Columns(JupyterMixin): """Display renderables in neat columns. Args: renderables (Iterable[RenderableType]): Any number of Rich renderables (including str). width (int, optional): The desired width of the columns, or None to auto detect. Defaults to None. padding (PaddingDimensions, optional): Optional padding around cells. Defaults to (0, 1). expand (bool, optional): Expand columns to full width. Defaults to False. equal (bool, optional): Arrange in to equal sized columns. Defaults to False. column_first (bool, optional): Align items from top to bottom (rather than left to right). Defaults to False. right_to_left (bool, optional): Start column from right hand side. Defaults to False. align (str, optional): Align value ("left", "right", or "center") or None for default. Defaults to None. title (TextType, optional): Optional title for Columns. """ def __init__( self, renderables: Optional[Iterable[RenderableType]] = None, padding: PaddingDimensions = (0, 1), *, width: Optional[int] = None, expand: bool = False, equal: bool = False, column_first: bool = False, right_to_left: bool = False, align: Optional[AlignMethod] = None, title: Optional[TextType] = None, ) -> None: self.renderables = list(renderables or []) self.width = width self.padding = padding self.expand = expand self.equal = equal self.column_first = column_first self.right_to_left = right_to_left self.align: Optional[AlignMethod] = align self.title = title def add_renderable(self, renderable: RenderableType) -> None: """Add a renderable to the columns. Args: renderable (RenderableType): Any renderable object. """ self.renderables.append(renderable) def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: render_str = console.render_str renderables = [ render_str(renderable) if isinstance(renderable, str) else renderable for renderable in self.renderables ] if not renderables: return _top, right, _bottom, left = Padding.unpack(self.padding) width_padding = max(left, right) max_width = options.max_width widths: Dict[int, int] = defaultdict(int) column_count = len(renderables) get_measurement = Measurement.get renderable_widths = [ get_measurement(console, options, renderable).maximum for renderable in renderables ] if self.equal: renderable_widths = [max(renderable_widths)] * len(renderable_widths) def iter_renderables( column_count: int, ) -> Iterable[Tuple[int, Optional[RenderableType]]]: item_count = len(renderables) if self.column_first: width_renderables = list(zip(renderable_widths, renderables)) column_lengths: List[int] = [item_count // column_count] * column_count for col_no in range(item_count % column_count): column_lengths[col_no] += 1 row_count = (item_count + column_count - 1) // column_count cells = [[-1] * column_count for _ in range(row_count)] row = col = 0 for index in range(item_count): cells[row][col] = index column_lengths[col] -= 1 if column_lengths[col]: row += 1 else: col += 1 row = 0 for index in chain.from_iterable(cells): if index == -1: break yield width_renderables[index] else: yield from zip(renderable_widths, renderables) # Pad odd elements with spaces if item_count % column_count: for _ in range(column_count - (item_count % column_count)): yield 0, None table = Table.grid(padding=self.padding, collapse_padding=True, pad_edge=False) table.expand = self.expand table.title = self.title if self.width is not None: column_count = (max_width) // (self.width + width_padding) for _ in range(column_count): table.add_column(width=self.width) else: while column_count > 1: widths.clear() column_no = 0 for renderable_width, _ in iter_renderables(column_count): widths[column_no] = max(widths[column_no], renderable_width) total_width = sum(widths.values()) + width_padding * ( len(widths) - 1 ) if total_width > max_width: column_count = len(widths) - 1 break else: column_no = (column_no + 1) % column_count else: break get_renderable = itemgetter(1) _renderables = [ get_renderable(_renderable) for _renderable in iter_renderables(column_count) ] if self.equal: _renderables = [ None if renderable is None else Constrain(renderable, renderable_widths[0]) for renderable in _renderables ] if self.align: align = self.align _Align = Align _renderables = [ None if renderable is None else _Align(renderable, align) for renderable in _renderables ] right_to_left = self.right_to_left add_row = table.add_row for start in range(0, len(_renderables), column_count): row = _renderables[start : start + column_count] if right_to_left: row = row[::-1] add_row(*row) yield table if __name__ == "__main__": # pragma: no cover import os console = Console() files = [f"{i} {s}" for i, s in enumerate(sorted(os.listdir()))] columns = Columns(files, padding=(0, 1), expand=False, equal=False) console.print(columns) console.rule() columns.column_first = True console.print(columns) columns.right_to_left = True console.rule() console.print(columns)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/default_styles.py
rich/default_styles.py
from typing import Dict from .style import Style DEFAULT_STYLES: Dict[str, Style] = { "none": Style.null(), "reset": Style( color="default", bgcolor="default", dim=False, bold=False, italic=False, underline=False, blink=False, blink2=False, reverse=False, conceal=False, strike=False, ), "dim": Style(dim=True), "bright": Style(dim=False), "bold": Style(bold=True), "strong": Style(bold=True), "code": Style(reverse=True, bold=True), "italic": Style(italic=True), "emphasize": Style(italic=True), "underline": Style(underline=True), "blink": Style(blink=True), "blink2": Style(blink2=True), "reverse": Style(reverse=True), "strike": Style(strike=True), "black": Style(color="black"), "red": Style(color="red"), "green": Style(color="green"), "yellow": Style(color="yellow"), "magenta": Style(color="magenta"), "cyan": Style(color="cyan"), "white": Style(color="white"), "inspect.attr": Style(color="yellow", italic=True), "inspect.attr.dunder": Style(color="yellow", italic=True, dim=True), "inspect.callable": Style(bold=True, color="red"), "inspect.async_def": Style(italic=True, color="bright_cyan"), "inspect.def": Style(italic=True, color="bright_cyan"), "inspect.class": Style(italic=True, color="bright_cyan"), "inspect.error": Style(bold=True, color="red"), "inspect.equals": Style(), "inspect.help": Style(color="cyan"), "inspect.doc": Style(dim=True), "inspect.value.border": Style(color="green"), "live.ellipsis": Style(bold=True, color="red"), "layout.tree.row": Style(dim=False, color="red"), "layout.tree.column": Style(dim=False, color="blue"), "logging.keyword": Style(bold=True, color="yellow"), "logging.level.notset": Style(dim=True), "logging.level.debug": Style(color="green"), "logging.level.info": Style(color="blue"), "logging.level.warning": Style(color="yellow"), "logging.level.error": Style(color="red", bold=True), "logging.level.critical": Style(color="red", bold=True, reverse=True), "log.level": Style.null(), "log.time": Style(color="cyan", dim=True), "log.message": Style.null(), "log.path": Style(dim=True), "repr.ellipsis": Style(color="yellow"), "repr.indent": Style(color="green", dim=True), "repr.error": Style(color="red", bold=True), "repr.str": Style(color="green", italic=False, bold=False), "repr.brace": Style(bold=True), "repr.comma": Style(bold=True), "repr.ipv4": Style(bold=True, color="bright_green"), "repr.ipv6": Style(bold=True, color="bright_green"), "repr.eui48": Style(bold=True, color="bright_green"), "repr.eui64": Style(bold=True, color="bright_green"), "repr.tag_start": Style(bold=True), "repr.tag_name": Style(color="bright_magenta", bold=True), "repr.tag_contents": Style(color="default"), "repr.tag_end": Style(bold=True), "repr.attrib_name": Style(color="yellow", italic=False), "repr.attrib_equal": Style(bold=True), "repr.attrib_value": Style(color="magenta", italic=False), "repr.number": Style(color="cyan", bold=True, italic=False), "repr.number_complex": Style(color="cyan", bold=True, italic=False), # same "repr.bool_true": Style(color="bright_green", italic=True), "repr.bool_false": Style(color="bright_red", italic=True), "repr.none": Style(color="magenta", italic=True), "repr.url": Style(underline=True, color="bright_blue", italic=False, bold=False), "repr.uuid": Style(color="bright_yellow", bold=False), "repr.call": Style(color="magenta", bold=True), "repr.path": Style(color="magenta"), "repr.filename": Style(color="bright_magenta"), "rule.line": Style(color="bright_green"), "rule.text": Style.null(), "json.brace": Style(bold=True), "json.bool_true": Style(color="bright_green", italic=True), "json.bool_false": Style(color="bright_red", italic=True), "json.null": Style(color="magenta", italic=True), "json.number": Style(color="cyan", bold=True, italic=False), "json.str": Style(color="green", italic=False, bold=False), "json.key": Style(color="blue", bold=True), "prompt": Style.null(), "prompt.choices": Style(color="magenta", bold=True), "prompt.default": Style(color="cyan", bold=True), "prompt.invalid": Style(color="red"), "prompt.invalid.choice": Style(color="red"), "pretty": Style.null(), "scope.border": Style(color="blue"), "scope.key": Style(color="yellow", italic=True), "scope.key.special": Style(color="yellow", italic=True, dim=True), "scope.equals": Style(color="red"), "table.header": Style(bold=True), "table.footer": Style(bold=True), "table.cell": Style.null(), "table.title": Style(italic=True), "table.caption": Style(italic=True, dim=True), "traceback.error": Style(color="red", italic=True), "traceback.border.syntax_error": Style(color="bright_red"), "traceback.border": Style(color="red"), "traceback.text": Style.null(), "traceback.title": Style(color="red", bold=True), "traceback.exc_type": Style(color="bright_red", bold=True), "traceback.exc_value": Style.null(), "traceback.offset": Style(color="bright_red", bold=True), "traceback.error_range": Style(underline=True, bold=True), "traceback.note": Style(color="green", bold=True), "traceback.group.border": Style(color="magenta"), "bar.back": Style(color="grey23"), "bar.complete": Style(color="rgb(249,38,114)"), "bar.finished": Style(color="rgb(114,156,31)"), "bar.pulse": Style(color="rgb(249,38,114)"), "progress.description": Style.null(), "progress.filesize": Style(color="green"), "progress.filesize.total": Style(color="green"), "progress.download": Style(color="green"), "progress.elapsed": Style(color="yellow"), "progress.percentage": Style(color="magenta"), "progress.remaining": Style(color="cyan"), "progress.data.speed": Style(color="red"), "progress.spinner": Style(color="green"), "status.spinner": Style(color="green"), "tree": Style(), "tree.line": Style(), "markdown.paragraph": Style(), "markdown.text": Style(), "markdown.em": Style(italic=True), "markdown.emph": Style(italic=True), # For commonmark backwards compatibility "markdown.strong": Style(bold=True), "markdown.code": Style(bold=True, color="cyan", bgcolor="black"), "markdown.code_block": Style(color="cyan", bgcolor="black"), "markdown.block_quote": Style(color="magenta"), "markdown.list": Style(color="cyan"), "markdown.item": Style(), "markdown.item.bullet": Style(color="yellow", bold=True), "markdown.item.number": Style(color="yellow", bold=True), "markdown.hr": Style(color="yellow"), "markdown.h1.border": Style(), "markdown.h1": Style(bold=True), "markdown.h2": Style(bold=True, underline=True), "markdown.h3": Style(bold=True), "markdown.h4": Style(bold=True, dim=True), "markdown.h5": Style(underline=True), "markdown.h6": Style(italic=True), "markdown.h7": Style(italic=True, dim=True), "markdown.link": Style(color="bright_blue"), "markdown.link_url": Style(color="blue", underline=True), "markdown.s": Style(strike=True), "iso8601.date": Style(color="blue"), "iso8601.time": Style(color="magenta"), "iso8601.timezone": Style(color="yellow"), } if __name__ == "__main__": # pragma: no cover import argparse import io from rich.console import Console from rich.table import Table from rich.text import Text parser = argparse.ArgumentParser() parser.add_argument("--html", action="store_true", help="Export as HTML table") args = parser.parse_args() html: bool = args.html console = Console(record=True, width=70, file=io.StringIO()) if html else Console() table = Table("Name", "Styling") for style_name, style in DEFAULT_STYLES.items(): table.add_row(Text(style_name, style=style), str(style)) console.print(table) if html: print(console.export_html(inline_styles=True))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/spinner.py
rich/spinner.py
from typing import TYPE_CHECKING, List, Optional, Union, cast from ._spinners import SPINNERS from .measure import Measurement from .table import Table from .text import Text if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderableType, RenderResult from .style import StyleType class Spinner: """A spinner animation. Args: name (str): Name of spinner (run python -m rich.spinner). text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "". style (StyleType, optional): Style for spinner animation. Defaults to None. speed (float, optional): Speed factor for animation. Defaults to 1.0. Raises: KeyError: If name isn't one of the supported spinner animations. """ def __init__( self, name: str, text: "RenderableType" = "", *, style: Optional["StyleType"] = None, speed: float = 1.0, ) -> None: try: spinner = SPINNERS[name] except KeyError: raise KeyError(f"no spinner called {name!r}") self.text: "Union[RenderableType, Text]" = ( Text.from_markup(text) if isinstance(text, str) else text ) self.name = name self.frames = cast(List[str], spinner["frames"])[:] self.interval = cast(float, spinner["interval"]) self.start_time: Optional[float] = None self.style = style self.speed = speed self.frame_no_offset: float = 0.0 self._update_speed = 0.0 def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": yield self.render(console.get_time()) def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> Measurement: text = self.render(0) return Measurement.get(console, options, text) def render(self, time: float) -> "RenderableType": """Render the spinner for a given time. Args: time (float): Time in seconds. Returns: RenderableType: A renderable containing animation frame. """ if self.start_time is None: self.start_time = time frame_no = ((time - self.start_time) * self.speed) / ( self.interval / 1000.0 ) + self.frame_no_offset frame = Text( self.frames[int(frame_no) % len(self.frames)], style=self.style or "" ) if self._update_speed: self.frame_no_offset = frame_no self.start_time = time self.speed = self._update_speed self._update_speed = 0.0 if not self.text: return frame elif isinstance(self.text, (str, Text)): return Text.assemble(frame, " ", self.text) else: table = Table.grid(padding=1) table.add_row(frame, self.text) return table def update( self, *, text: "RenderableType" = "", style: Optional["StyleType"] = None, speed: Optional[float] = None, ) -> None: """Updates attributes of a spinner after it has been started. Args: text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "". style (StyleType, optional): Style for spinner animation. Defaults to None. speed (float, optional): Speed factor for animation. Defaults to None. """ if text: self.text = Text.from_markup(text) if isinstance(text, str) else text if style: self.style = style if speed: self._update_speed = speed if __name__ == "__main__": # pragma: no cover from time import sleep from .console import Group from .live import Live all_spinners = Group( *[ Spinner(spinner_name, text=Text(repr(spinner_name), style="green")) for spinner_name in sorted(SPINNERS.keys()) ] ) with Live(all_spinners, refresh_per_second=20) as live: while True: sleep(0.1)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_inspect.py
rich/_inspect.py
import inspect from inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature from typing import Any, Collection, Iterable, Optional, Tuple, Type, Union from .console import Group, RenderableType from .control import escape_control_codes from .highlighter import ReprHighlighter from .jupyter import JupyterMixin from .panel import Panel from .pretty import Pretty from .table import Table from .text import Text, TextType def _first_paragraph(doc: str) -> str: """Get the first paragraph from a docstring.""" paragraph, _, _ = doc.partition("\n\n") return paragraph class Inspect(JupyterMixin): """A renderable to inspect any Python Object. Args: obj (Any): An object to inspect. title (str, optional): Title to display over inspect result, or None use type. Defaults to None. help (bool, optional): Show full help text rather than just first paragraph. Defaults to False. methods (bool, optional): Enable inspection of callables. Defaults to False. docs (bool, optional): Also render doc strings. Defaults to True. private (bool, optional): Show private attributes (beginning with underscore). Defaults to False. dunder (bool, optional): Show attributes starting with double underscore. Defaults to False. sort (bool, optional): Sort attributes alphabetically. Defaults to True. all (bool, optional): Show all attributes. Defaults to False. value (bool, optional): Pretty print value of object. Defaults to True. """ def __init__( self, obj: Any, *, title: Optional[TextType] = None, help: bool = False, methods: bool = False, docs: bool = True, private: bool = False, dunder: bool = False, sort: bool = True, all: bool = True, value: bool = True, ) -> None: self.highlighter = ReprHighlighter() self.obj = obj self.title = title or self._make_title(obj) if all: methods = private = dunder = True self.help = help self.methods = methods self.docs = docs or help self.private = private or dunder self.dunder = dunder self.sort = sort self.value = value def _make_title(self, obj: Any) -> Text: """Make a default title.""" title_str = ( str(obj) if (isclass(obj) or callable(obj) or ismodule(obj)) else str(type(obj)) ) title_text = self.highlighter(title_str) return title_text def __rich__(self) -> Panel: return Panel.fit( Group(*self._render()), title=self.title, border_style="scope.border", padding=(0, 1), ) def _get_signature(self, name: str, obj: Any) -> Optional[Text]: """Get a signature for a callable.""" try: _signature = str(signature(obj)) + ":" except ValueError: _signature = "(...)" except TypeError: return None source_filename: Optional[str] = None try: source_filename = getfile(obj) except (OSError, TypeError): # OSError is raised if obj has no source file, e.g. when defined in REPL. pass callable_name = Text(name, style="inspect.callable") if source_filename: callable_name.stylize(f"link file://{source_filename}") signature_text = self.highlighter(_signature) qualname = name or getattr(obj, "__qualname__", name) # If obj is a module, there may be classes (which are callable) to display if inspect.isclass(obj): prefix = "class" elif inspect.iscoroutinefunction(obj): prefix = "async def" else: prefix = "def" qual_signature = Text.assemble( (f"{prefix} ", f"inspect.{prefix.replace(' ', '_')}"), (qualname, "inspect.callable"), signature_text, ) return qual_signature def _render(self) -> Iterable[RenderableType]: """Render object.""" def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]: key, (_error, value) = item return (callable(value), key.strip("_").lower()) def safe_getattr(attr_name: str) -> Tuple[Any, Any]: """Get attribute or any exception.""" try: return (None, getattr(obj, attr_name)) except Exception as error: return (error, None) obj = self.obj keys = dir(obj) total_items = len(keys) if not self.dunder: keys = [key for key in keys if not key.startswith("__")] if not self.private: keys = [key for key in keys if not key.startswith("_")] not_shown_count = total_items - len(keys) items = [(key, safe_getattr(key)) for key in keys] if self.sort: items.sort(key=sort_items) items_table = Table.grid(padding=(0, 1), expand=False) items_table.add_column(justify="right") add_row = items_table.add_row highlighter = self.highlighter if callable(obj): signature = self._get_signature("", obj) if signature is not None: yield signature yield "" if self.docs: _doc = self._get_formatted_doc(obj) if _doc is not None: doc_text = Text(_doc, style="inspect.help") doc_text = highlighter(doc_text) yield doc_text yield "" if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)): yield Panel( Pretty(obj, indent_guides=True, max_length=10, max_string=60), border_style="inspect.value.border", ) yield "" for key, (error, value) in items: key_text = Text.assemble( ( key, "inspect.attr.dunder" if key.startswith("__") else "inspect.attr", ), (" =", "inspect.equals"), ) if error is not None: warning = key_text.copy() warning.stylize("inspect.error") add_row(warning, highlighter(repr(error))) continue if callable(value): if not self.methods: continue _signature_text = self._get_signature(key, value) if _signature_text is None: add_row(key_text, Pretty(value, highlighter=highlighter)) else: if self.docs: docs = self._get_formatted_doc(value) if docs is not None: _signature_text.append("\n" if "\n" in docs else " ") doc = highlighter(docs) doc.stylize("inspect.doc") _signature_text.append(doc) add_row(key_text, _signature_text) else: add_row(key_text, Pretty(value, highlighter=highlighter)) if items_table.row_count: yield items_table elif not_shown_count: yield Text.from_markup( f"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] " f"Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options." ) def _get_formatted_doc(self, object_: Any) -> Optional[str]: """ Extract the docstring of an object, process it and returns it. The processing consists in cleaning up the docstring's indentation, taking only its 1st paragraph if `self.help` is not True, and escape its control codes. Args: object_ (Any): the object to get the docstring from. Returns: Optional[str]: the processed docstring, or None if no docstring was found. """ docs = getdoc(object_) if docs is None: return None docs = cleandoc(docs).strip() if not self.help: docs = _first_paragraph(docs) return escape_control_codes(docs) def get_object_types_mro(obj: Union[object, Type[Any]]) -> Tuple[type, ...]: """Returns the MRO of an object's class, or of the object itself if it's a class.""" if not hasattr(obj, "__mro__"): # N.B. we cannot use `if type(obj) is type` here because it doesn't work with # some types of classes, such as the ones that use abc.ABCMeta. obj = type(obj) return getattr(obj, "__mro__", ()) def get_object_types_mro_as_strings(obj: object) -> Collection[str]: """ Returns the MRO of an object's class as full qualified names, or of the object itself if it's a class. Examples: `object_types_mro_as_strings(JSONDecoder)` will return `['json.decoder.JSONDecoder', 'builtins.object']` """ return [ f'{getattr(type_, "__module__", "")}.{getattr(type_, "__qualname__", "")}' for type_ in get_object_types_mro(obj) ] def is_object_one_of_types( obj: object, fully_qualified_types_names: Collection[str] ) -> bool: """ Returns `True` if the given object's class (or the object itself, if it's a class) has one of the fully qualified names in its MRO. """ for type_name in get_object_types_mro_as_strings(obj): if type_name in fully_qualified_types_names: return True return False
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/box.py
rich/box.py
from typing import TYPE_CHECKING, Iterable, List, Literal from ._loop import loop_last if TYPE_CHECKING: from rich.console import ConsoleOptions class Box: """Defines characters to render boxes. ┌─┬┐ top │ ││ head ├─┼┤ head_row │ ││ mid ├─┼┤ row ├─┼┤ foot_row │ ││ foot └─┴┘ bottom Args: box (str): Characters making up box. ascii (bool, optional): True if this box uses ascii characters only. Default is False. """ def __init__(self, box: str, *, ascii: bool = False) -> None: self._box = box self.ascii = ascii line1, line2, line3, line4, line5, line6, line7, line8 = box.splitlines() # top self.top_left, self.top, self.top_divider, self.top_right = iter(line1) # head self.head_left, _, self.head_vertical, self.head_right = iter(line2) # head_row ( self.head_row_left, self.head_row_horizontal, self.head_row_cross, self.head_row_right, ) = iter(line3) # mid self.mid_left, _, self.mid_vertical, self.mid_right = iter(line4) # row self.row_left, self.row_horizontal, self.row_cross, self.row_right = iter(line5) # foot_row ( self.foot_row_left, self.foot_row_horizontal, self.foot_row_cross, self.foot_row_right, ) = iter(line6) # foot self.foot_left, _, self.foot_vertical, self.foot_right = iter(line7) # bottom self.bottom_left, self.bottom, self.bottom_divider, self.bottom_right = iter( line8 ) def __repr__(self) -> str: return "Box(...)" def __str__(self) -> str: return self._box def substitute(self, options: "ConsoleOptions", safe: bool = True) -> "Box": """Substitute this box for another if it won't render due to platform issues. Args: options (ConsoleOptions): Console options used in rendering. safe (bool, optional): Substitute this for another Box if there are known problems displaying on the platform (currently only relevant on Windows). Default is True. Returns: Box: A different Box or the same Box. """ box = self if options.legacy_windows and safe: box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box) if options.ascii_only and not box.ascii: box = ASCII return box def get_plain_headed_box(self) -> "Box": """If this box uses special characters for the borders of the header, then return the equivalent box that does not. Returns: Box: The most similar Box that doesn't use header-specific box characters. If the current Box already satisfies this criterion, then it's returned. """ return PLAIN_HEADED_SUBSTITUTIONS.get(self, self) def get_top(self, widths: Iterable[int]) -> str: """Get the top of a simple box. Args: widths (List[int]): Widths of columns. Returns: str: A string of box characters. """ parts: List[str] = [] append = parts.append append(self.top_left) for last, width in loop_last(widths): append(self.top * width) if not last: append(self.top_divider) append(self.top_right) return "".join(parts) def get_row( self, widths: Iterable[int], level: Literal["head", "row", "foot", "mid"] = "row", edge: bool = True, ) -> str: """Get the top of a simple box. Args: width (List[int]): Widths of columns. Returns: str: A string of box characters. """ if level == "head": left = self.head_row_left horizontal = self.head_row_horizontal cross = self.head_row_cross right = self.head_row_right elif level == "row": left = self.row_left horizontal = self.row_horizontal cross = self.row_cross right = self.row_right elif level == "mid": left = self.mid_left horizontal = " " cross = self.mid_vertical right = self.mid_right elif level == "foot": left = self.foot_row_left horizontal = self.foot_row_horizontal cross = self.foot_row_cross right = self.foot_row_right else: raise ValueError("level must be 'head', 'row' or 'foot'") parts: List[str] = [] append = parts.append if edge: append(left) for last, width in loop_last(widths): append(horizontal * width) if not last: append(cross) if edge: append(right) return "".join(parts) def get_bottom(self, widths: Iterable[int]) -> str: """Get the bottom of a simple box. Args: widths (List[int]): Widths of columns. Returns: str: A string of box characters. """ parts: List[str] = [] append = parts.append append(self.bottom_left) for last, width in loop_last(widths): append(self.bottom * width) if not last: append(self.bottom_divider) append(self.bottom_right) return "".join(parts) # fmt: off ASCII: Box = Box( "+--+\n" "| ||\n" "|-+|\n" "| ||\n" "|-+|\n" "|-+|\n" "| ||\n" "+--+\n", ascii=True, ) ASCII2: Box = Box( "+-++\n" "| ||\n" "+-++\n" "| ||\n" "+-++\n" "+-++\n" "| ||\n" "+-++\n", ascii=True, ) ASCII_DOUBLE_HEAD: Box = Box( "+-++\n" "| ||\n" "+=++\n" "| ||\n" "+-++\n" "+-++\n" "| ||\n" "+-++\n", ascii=True, ) SQUARE: Box = Box( "┌─┬┐\n" "│ ││\n" "├─┼┤\n" "│ ││\n" "├─┼┤\n" "├─┼┤\n" "│ ││\n" "└─┴┘\n" ) SQUARE_DOUBLE_HEAD: Box = Box( "┌─┬┐\n" "│ ││\n" "╞═╪╡\n" "│ ││\n" "├─┼┤\n" "├─┼┤\n" "│ ││\n" "└─┴┘\n" ) MINIMAL: Box = Box( " ╷ \n" " │ \n" "╶─┼╴\n" " │ \n" "╶─┼╴\n" "╶─┼╴\n" " │ \n" " ╵ \n" ) MINIMAL_HEAVY_HEAD: Box = Box( " ╷ \n" " │ \n" "╺━┿╸\n" " │ \n" "╶─┼╴\n" "╶─┼╴\n" " │ \n" " ╵ \n" ) MINIMAL_DOUBLE_HEAD: Box = Box( " ╷ \n" " │ \n" " ═╪ \n" " │ \n" " ─┼ \n" " ─┼ \n" " │ \n" " ╵ \n" ) SIMPLE: Box = Box( " \n" " \n" " ── \n" " \n" " \n" " ── \n" " \n" " \n" ) SIMPLE_HEAD: Box = Box( " \n" " \n" " ── \n" " \n" " \n" " \n" " \n" " \n" ) SIMPLE_HEAVY: Box = Box( " \n" " \n" " ━━ \n" " \n" " \n" " ━━ \n" " \n" " \n" ) HORIZONTALS: Box = Box( " ── \n" " \n" " ── \n" " \n" " ── \n" " ── \n" " \n" " ── \n" ) ROUNDED: Box = Box( "╭─┬╮\n" "│ ││\n" "├─┼┤\n" "│ ││\n" "├─┼┤\n" "├─┼┤\n" "│ ││\n" "╰─┴╯\n" ) HEAVY: Box = Box( "┏━┳┓\n" "┃ ┃┃\n" "┣━╋┫\n" "┃ ┃┃\n" "┣━╋┫\n" "┣━╋┫\n" "┃ ┃┃\n" "┗━┻┛\n" ) HEAVY_EDGE: Box = Box( "┏━┯┓\n" "┃ │┃\n" "┠─┼┨\n" "┃ │┃\n" "┠─┼┨\n" "┠─┼┨\n" "┃ │┃\n" "┗━┷┛\n" ) HEAVY_HEAD: Box = Box( "┏━┳┓\n" "┃ ┃┃\n" "┡━╇┩\n" "│ ││\n" "├─┼┤\n" "├─┼┤\n" "│ ││\n" "└─┴┘\n" ) DOUBLE: Box = Box( "╔═╦╗\n" "║ ║║\n" "╠═╬╣\n" "║ ║║\n" "╠═╬╣\n" "╠═╬╣\n" "║ ║║\n" "╚═╩╝\n" ) DOUBLE_EDGE: Box = Box( "╔═╤╗\n" "║ │║\n" "╟─┼╢\n" "║ │║\n" "╟─┼╢\n" "╟─┼╢\n" "║ │║\n" "╚═╧╝\n" ) MARKDOWN: Box = Box( " \n" "| ||\n" "|-||\n" "| ||\n" "|-||\n" "|-||\n" "| ||\n" " \n", ascii=True, ) # fmt: on # Map Boxes that don't render with raster fonts on to equivalent that do LEGACY_WINDOWS_SUBSTITUTIONS = { ROUNDED: SQUARE, MINIMAL_HEAVY_HEAD: MINIMAL, SIMPLE_HEAVY: SIMPLE, HEAVY: SQUARE, HEAVY_EDGE: SQUARE, HEAVY_HEAD: SQUARE, } # Map headed boxes to their headerless equivalents PLAIN_HEADED_SUBSTITUTIONS = { HEAVY_HEAD: SQUARE, SQUARE_DOUBLE_HEAD: SQUARE, MINIMAL_DOUBLE_HEAD: MINIMAL, MINIMAL_HEAVY_HEAD: MINIMAL, ASCII_DOUBLE_HEAD: ASCII2, } if __name__ == "__main__": # pragma: no cover from rich.columns import Columns from rich.panel import Panel from . import box as box from .console import Console from .table import Table from .text import Text console = Console(record=True) BOXES = [ "ASCII", "ASCII2", "ASCII_DOUBLE_HEAD", "SQUARE", "SQUARE_DOUBLE_HEAD", "MINIMAL", "MINIMAL_HEAVY_HEAD", "MINIMAL_DOUBLE_HEAD", "SIMPLE", "SIMPLE_HEAD", "SIMPLE_HEAVY", "HORIZONTALS", "ROUNDED", "HEAVY", "HEAVY_EDGE", "HEAVY_HEAD", "DOUBLE", "DOUBLE_EDGE", "MARKDOWN", ] console.print(Panel("[bold green]Box Constants", style="green"), justify="center") console.print() columns = Columns(expand=True, padding=2) for box_name in sorted(BOXES): table = Table( show_footer=True, style="dim", border_style="not dim", expand=True ) table.add_column("Header 1", "Footer 1") table.add_column("Header 2", "Footer 2") table.add_row("Cell", "Cell") table.add_row("Cell", "Cell") table.box = getattr(box, box_name) table.title = Text(f"box.{box_name}", style="magenta") columns.add_renderable(table) console.print(columns) # console.save_svg("box.svg")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/table.py
rich/table.py
from dataclasses import dataclass, field, replace from typing import ( TYPE_CHECKING, Dict, Iterable, List, NamedTuple, Optional, Sequence, Tuple, Union, ) from . import box, errors from ._loop import loop_first_last, loop_last from ._pick import pick_bool from ._ratio import ratio_distribute, ratio_reduce from .align import VerticalAlignMethod from .jupyter import JupyterMixin from .measure import Measurement from .padding import Padding, PaddingDimensions from .protocol import is_renderable from .segment import Segment from .style import Style, StyleType from .text import Text, TextType if TYPE_CHECKING: from .console import ( Console, ConsoleOptions, JustifyMethod, OverflowMethod, RenderableType, RenderResult, ) @dataclass class Column: """Defines a column within a ~Table. Args: title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None. caption (Union[str, Text], optional): The table caption rendered below. Defaults to None. width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None. min_width (Optional[int], optional): The minimum width of the table, or ``None`` for no minimum. Defaults to None. box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`), or ``None`` for no box lines. Defaults to box.HEAVY_HEAD. safe_box (Optional[bool], optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True. padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1). collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False. pad_edge (bool, optional): Enable padding of edge cells. Defaults to True. expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False. show_header (bool, optional): Show a header row. Defaults to True. show_footer (bool, optional): Show a footer row. Defaults to False. show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True. show_lines (bool, optional): Draw lines between every row. Defaults to False. leading (int, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0. style (Union[str, Style], optional): Default style for the table. Defaults to "none". row_styles (List[Union, str], optional): Optional list of row styles, if more than one style is given then the styles will alternate. Defaults to None. header_style (Union[str, Style], optional): Style of the header. Defaults to "table.header". footer_style (Union[str, Style], optional): Style of the footer. Defaults to "table.footer". border_style (Union[str, Style], optional): Style of the border. Defaults to None. title_style (Union[str, Style], optional): Style of the title. Defaults to None. caption_style (Union[str, Style], optional): Style of the caption. Defaults to None. title_justify (str, optional): Justify method for title. Defaults to "center". caption_justify (str, optional): Justify method for caption. Defaults to "center". highlight (bool, optional): Highlight cell contents (if str). Defaults to False. """ header: "RenderableType" = "" """RenderableType: Renderable for the header (typically a string)""" footer: "RenderableType" = "" """RenderableType: Renderable for the footer (typically a string)""" header_style: StyleType = "" """StyleType: The style of the header.""" footer_style: StyleType = "" """StyleType: The style of the footer.""" style: StyleType = "" """StyleType: The style of the column.""" justify: "JustifyMethod" = "left" """str: How to justify text within the column ("left", "center", "right", or "full")""" vertical: "VerticalAlignMethod" = "top" """str: How to vertically align content ("top", "middle", or "bottom")""" overflow: "OverflowMethod" = "ellipsis" """str: Overflow method.""" width: Optional[int] = None """Optional[int]: Width of the column, or ``None`` (default) to auto calculate width.""" min_width: Optional[int] = None """Optional[int]: Minimum width of column, or ``None`` for no minimum. Defaults to None.""" max_width: Optional[int] = None """Optional[int]: Maximum width of column, or ``None`` for no maximum. Defaults to None.""" ratio: Optional[int] = None """Optional[int]: Ratio to use when calculating column width, or ``None`` (default) to adapt to column contents.""" no_wrap: bool = False """bool: Prevent wrapping of text within the column. Defaults to ``False``.""" highlight: bool = False """bool: Apply highlighter to column. Defaults to ``False``.""" _index: int = 0 """Index of column.""" _cells: List["RenderableType"] = field(default_factory=list) def copy(self) -> "Column": """Return a copy of this Column.""" return replace(self, _cells=[]) @property def cells(self) -> Iterable["RenderableType"]: """Get all cells in the column, not including header.""" yield from self._cells @property def flexible(self) -> bool: """Check if this column is flexible.""" return self.ratio is not None @dataclass class Row: """Information regarding a row.""" style: Optional[StyleType] = None """Style to apply to row.""" end_section: bool = False """Indicated end of section, which will force a line beneath the row.""" class _Cell(NamedTuple): """A single cell in a table.""" style: StyleType """Style to apply to cell.""" renderable: "RenderableType" """Cell renderable.""" vertical: VerticalAlignMethod """Cell vertical alignment.""" class Table(JupyterMixin): """A console renderable to draw a table. Args: *headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance. title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None. caption (Union[str, Text], optional): The table caption rendered below. Defaults to None. width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None. min_width (Optional[int], optional): The minimum width of the table, or ``None`` for no minimum. Defaults to None. box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`), or ``None`` for no box lines. Defaults to box.HEAVY_HEAD. safe_box (Optional[bool], optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True. padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1). collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False. pad_edge (bool, optional): Enable padding of edge cells. Defaults to True. expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False. show_header (bool, optional): Show a header row. Defaults to True. show_footer (bool, optional): Show a footer row. Defaults to False. show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True. show_lines (bool, optional): Draw lines between every row. Defaults to False. leading (int, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0. style (Union[str, Style], optional): Default style for the table. Defaults to "none". row_styles (List[Union, str], optional): Optional list of row styles, if more than one style is given then the styles will alternate. Defaults to None. header_style (Union[str, Style], optional): Style of the header. Defaults to "table.header". footer_style (Union[str, Style], optional): Style of the footer. Defaults to "table.footer". border_style (Union[str, Style], optional): Style of the border. Defaults to None. title_style (Union[str, Style], optional): Style of the title. Defaults to None. caption_style (Union[str, Style], optional): Style of the caption. Defaults to None. title_justify (str, optional): Justify method for title. Defaults to "center". caption_justify (str, optional): Justify method for caption. Defaults to "center". highlight (bool, optional): Highlight cell contents (if str). Defaults to False. """ columns: List[Column] rows: List[Row] def __init__( self, *headers: Union[Column, str], title: Optional[TextType] = None, caption: Optional[TextType] = None, width: Optional[int] = None, min_width: Optional[int] = None, box: Optional[box.Box] = box.HEAVY_HEAD, safe_box: Optional[bool] = None, padding: PaddingDimensions = (0, 1), collapse_padding: bool = False, pad_edge: bool = True, expand: bool = False, show_header: bool = True, show_footer: bool = False, show_edge: bool = True, show_lines: bool = False, leading: int = 0, style: StyleType = "none", row_styles: Optional[Iterable[StyleType]] = None, header_style: Optional[StyleType] = "table.header", footer_style: Optional[StyleType] = "table.footer", border_style: Optional[StyleType] = None, title_style: Optional[StyleType] = None, caption_style: Optional[StyleType] = None, title_justify: "JustifyMethod" = "center", caption_justify: "JustifyMethod" = "center", highlight: bool = False, ) -> None: self.columns: List[Column] = [] self.rows: List[Row] = [] self.title = title self.caption = caption self.width = width self.min_width = min_width self.box = box self.safe_box = safe_box self._padding = Padding.unpack(padding) self.pad_edge = pad_edge self._expand = expand self.show_header = show_header self.show_footer = show_footer self.show_edge = show_edge self.show_lines = show_lines self.leading = leading self.collapse_padding = collapse_padding self.style = style self.header_style = header_style or "" self.footer_style = footer_style or "" self.border_style = border_style self.title_style = title_style self.caption_style = caption_style self.title_justify: "JustifyMethod" = title_justify self.caption_justify: "JustifyMethod" = caption_justify self.highlight = highlight self.row_styles: Sequence[StyleType] = list(row_styles or []) append_column = self.columns.append for header in headers: if isinstance(header, str): self.add_column(header=header) else: header._index = len(self.columns) append_column(header) @classmethod def grid( cls, *headers: Union[Column, str], padding: PaddingDimensions = 0, collapse_padding: bool = True, pad_edge: bool = False, expand: bool = False, ) -> "Table": """Get a table with no lines, headers, or footer. Args: *headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance. padding (PaddingDimensions, optional): Get padding around cells. Defaults to 0. collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to True. pad_edge (bool, optional): Enable padding around edges of table. Defaults to False. expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False. Returns: Table: A table instance. """ return cls( *headers, box=None, padding=padding, collapse_padding=collapse_padding, show_header=False, show_footer=False, show_edge=False, pad_edge=pad_edge, expand=expand, ) @property def expand(self) -> bool: """Setting a non-None self.width implies expand.""" return self._expand or self.width is not None @expand.setter def expand(self, expand: bool) -> None: """Set expand.""" self._expand = expand @property def _extra_width(self) -> int: """Get extra width to add to cell content.""" width = 0 if self.box and self.show_edge: width += 2 if self.box: width += len(self.columns) - 1 return width @property def row_count(self) -> int: """Get the current number of rows.""" return len(self.rows) def get_row_style(self, console: "Console", index: int) -> StyleType: """Get the current row style.""" style = Style.null() if self.row_styles: style += console.get_style(self.row_styles[index % len(self.row_styles)]) row_style = self.rows[index].style if row_style is not None: style += console.get_style(row_style) return style def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> Measurement: max_width = options.max_width if self.width is not None: max_width = self.width if max_width < 0: return Measurement(0, 0) extra_width = self._extra_width max_width = sum( self._calculate_column_widths( console, options.update_width(max_width - extra_width) ) ) _measure_column = self._measure_column measurements = [ _measure_column(console, options.update_width(max_width), column) for column in self.columns ] minimum_width = ( sum(measurement.minimum for measurement in measurements) + extra_width ) maximum_width = ( sum(measurement.maximum for measurement in measurements) + extra_width if (self.width is None) else self.width ) measurement = Measurement(minimum_width, maximum_width) measurement = measurement.clamp(self.min_width) return measurement @property def padding(self) -> Tuple[int, int, int, int]: """Get cell padding.""" return self._padding @padding.setter def padding(self, padding: PaddingDimensions) -> "Table": """Set cell padding.""" self._padding = Padding.unpack(padding) return self def add_column( self, header: "RenderableType" = "", footer: "RenderableType" = "", *, header_style: Optional[StyleType] = None, highlight: Optional[bool] = None, footer_style: Optional[StyleType] = None, style: Optional[StyleType] = None, justify: "JustifyMethod" = "left", vertical: "VerticalAlignMethod" = "top", overflow: "OverflowMethod" = "ellipsis", width: Optional[int] = None, min_width: Optional[int] = None, max_width: Optional[int] = None, ratio: Optional[int] = None, no_wrap: bool = False, ) -> None: """Add a column to the table. Args: header (RenderableType, optional): Text or renderable for the header. Defaults to "". footer (RenderableType, optional): Text or renderable for the footer. Defaults to "". header_style (Union[str, Style], optional): Style for the header, or None for default. Defaults to None. highlight (bool, optional): Whether to highlight the text. The default of None uses the value of the table (self) object. footer_style (Union[str, Style], optional): Style for the footer, or None for default. Defaults to None. style (Union[str, Style], optional): Style for the column cells, or None for default. Defaults to None. justify (JustifyMethod, optional): Alignment for cells. Defaults to "left". vertical (VerticalAlignMethod, optional): Vertical alignment, one of "top", "middle", or "bottom". Defaults to "top". overflow (OverflowMethod): Overflow method: "crop", "fold", "ellipsis". Defaults to "ellipsis". width (int, optional): Desired width of column in characters, or None to fit to contents. Defaults to None. min_width (Optional[int], optional): Minimum width of column, or ``None`` for no minimum. Defaults to None. max_width (Optional[int], optional): Maximum width of column, or ``None`` for no maximum. Defaults to None. ratio (int, optional): Flexible ratio for the column (requires ``Table.expand`` or ``Table.width``). Defaults to None. no_wrap (bool, optional): Set to ``True`` to disable wrapping of this column. """ column = Column( _index=len(self.columns), header=header, footer=footer, header_style=header_style or "", highlight=highlight if highlight is not None else self.highlight, footer_style=footer_style or "", style=style or "", justify=justify, vertical=vertical, overflow=overflow, width=width, min_width=min_width, max_width=max_width, ratio=ratio, no_wrap=no_wrap, ) self.columns.append(column) def add_row( self, *renderables: Optional["RenderableType"], style: Optional[StyleType] = None, end_section: bool = False, ) -> None: """Add a row of renderables. Args: *renderables (None or renderable): Each cell in a row must be a renderable object (including str), or ``None`` for a blank cell. style (StyleType, optional): An optional style to apply to the entire row. Defaults to None. end_section (bool, optional): End a section and draw a line. Defaults to False. Raises: errors.NotRenderableError: If you add something that can't be rendered. """ def add_cell(column: Column, renderable: "RenderableType") -> None: column._cells.append(renderable) cell_renderables: List[Optional["RenderableType"]] = list(renderables) columns = self.columns if len(cell_renderables) < len(columns): cell_renderables = [ *cell_renderables, *[None] * (len(columns) - len(cell_renderables)), ] for index, renderable in enumerate(cell_renderables): if index == len(columns): column = Column(_index=index, highlight=self.highlight) for _ in self.rows: add_cell(column, Text("")) self.columns.append(column) else: column = columns[index] if renderable is None: add_cell(column, "") elif is_renderable(renderable): add_cell(column, renderable) else: raise errors.NotRenderableError( f"unable to render {type(renderable).__name__}; a string or other renderable object is required" ) self.rows.append(Row(style=style, end_section=end_section)) def add_section(self) -> None: """Add a new section (draw a line after current row).""" if self.rows: self.rows[-1].end_section = True def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": if not self.columns: yield Segment("\n") return max_width = options.max_width if self.width is not None: max_width = self.width extra_width = self._extra_width widths = self._calculate_column_widths( console, options.update_width(max_width - extra_width) ) table_width = sum(widths) + extra_width render_options = options.update( width=table_width, highlight=self.highlight, height=None ) def render_annotation( text: TextType, style: StyleType, justify: "JustifyMethod" = "center" ) -> "RenderResult": render_text = ( console.render_str(text, style=style, highlight=False) if isinstance(text, str) else text ) return console.render( render_text, options=render_options.update(justify=justify) ) if self.title: yield from render_annotation( self.title, style=Style.pick_first(self.title_style, "table.title"), justify=self.title_justify, ) yield from self._render(console, render_options, widths) if self.caption: yield from render_annotation( self.caption, style=Style.pick_first(self.caption_style, "table.caption"), justify=self.caption_justify, ) def _calculate_column_widths( self, console: "Console", options: "ConsoleOptions" ) -> List[int]: """Calculate the widths of each column, including padding, not including borders.""" max_width = options.max_width columns = self.columns width_ranges = [ self._measure_column(console, options, column) for column in columns ] widths = [_range.maximum or 1 for _range in width_ranges] get_padding_width = self._get_padding_width extra_width = self._extra_width if self.expand: ratios = [col.ratio or 0 for col in columns if col.flexible] if any(ratios): fixed_widths = [ 0 if column.flexible else _range.maximum for _range, column in zip(width_ranges, columns) ] flex_minimum = [ (column.width or 1) + get_padding_width(column._index) for column in columns if column.flexible ] flexible_width = max_width - sum(fixed_widths) flex_widths = ratio_distribute(flexible_width, ratios, flex_minimum) iter_flex_widths = iter(flex_widths) for index, column in enumerate(columns): if column.flexible: widths[index] = fixed_widths[index] + next(iter_flex_widths) table_width = sum(widths) if table_width > max_width: widths = self._collapse_widths( widths, [(column.width is None and not column.no_wrap) for column in columns], max_width, ) table_width = sum(widths) # last resort, reduce columns evenly if table_width > max_width: excess_width = table_width - max_width widths = ratio_reduce(excess_width, [1] * len(widths), widths, widths) table_width = sum(widths) width_ranges = [ self._measure_column(console, options.update_width(width), column) for width, column in zip(widths, columns) ] widths = [_range.maximum or 0 for _range in width_ranges] if (table_width < max_width and self.expand) or ( self.min_width is not None and table_width < (self.min_width - extra_width) ): _max_width = ( max_width if self.min_width is None else min(self.min_width - extra_width, max_width) ) pad_widths = ratio_distribute(_max_width - table_width, widths) widths = [_width + pad for _width, pad in zip(widths, pad_widths)] return widths @classmethod def _collapse_widths( cls, widths: List[int], wrapable: List[bool], max_width: int ) -> List[int]: """Reduce widths so that the total is under max_width. Args: widths (List[int]): List of widths. wrapable (List[bool]): List of booleans that indicate if a column may shrink. max_width (int): Maximum width to reduce to. Returns: List[int]: A new list of widths. """ total_width = sum(widths) excess_width = total_width - max_width if any(wrapable): while total_width and excess_width > 0: max_column = max( width for width, allow_wrap in zip(widths, wrapable) if allow_wrap ) second_max_column = max( width if allow_wrap and width != max_column else 0 for width, allow_wrap in zip(widths, wrapable) ) column_difference = max_column - second_max_column ratios = [ (1 if (width == max_column and allow_wrap) else 0) for width, allow_wrap in zip(widths, wrapable) ] if not any(ratios) or not column_difference: break max_reduce = [min(excess_width, column_difference)] * len(widths) widths = ratio_reduce(excess_width, ratios, max_reduce, widths) total_width = sum(widths) excess_width = total_width - max_width return widths def _get_cells( self, console: "Console", column_index: int, column: Column ) -> Iterable[_Cell]: """Get all the cells with padding and optional header.""" collapse_padding = self.collapse_padding pad_edge = self.pad_edge padding = self.padding any_padding = any(padding) first_column = column_index == 0 last_column = column_index == len(self.columns) - 1 _padding_cache: Dict[Tuple[bool, bool], Tuple[int, int, int, int]] = {} def get_padding(first_row: bool, last_row: bool) -> Tuple[int, int, int, int]: cached = _padding_cache.get((first_row, last_row)) if cached: return cached top, right, bottom, left = padding if collapse_padding: if not first_column: left = max(0, left - right) if not last_row: bottom = max(0, top - bottom) if not pad_edge: if first_column: left = 0 if last_column: right = 0 if first_row: top = 0 if last_row: bottom = 0 _padding = (top, right, bottom, left) _padding_cache[(first_row, last_row)] = _padding return _padding raw_cells: List[Tuple[StyleType, "RenderableType"]] = [] _append = raw_cells.append get_style = console.get_style if self.show_header: header_style = get_style(self.header_style or "") + get_style( column.header_style ) _append((header_style, column.header)) cell_style = get_style(column.style or "") for cell in column.cells: _append((cell_style, cell)) if self.show_footer: footer_style = get_style(self.footer_style or "") + get_style( column.footer_style ) _append((footer_style, column.footer)) if any_padding: _Padding = Padding for first, last, (style, renderable) in loop_first_last(raw_cells): yield _Cell( style, _Padding(renderable, get_padding(first, last)), getattr(renderable, "vertical", None) or column.vertical, ) else: for style, renderable in raw_cells: yield _Cell( style, renderable, getattr(renderable, "vertical", None) or column.vertical, ) def _get_padding_width(self, column_index: int) -> int: """Get extra width from padding.""" _, pad_right, _, pad_left = self.padding if self.collapse_padding: if column_index > 0: pad_left = max(0, pad_left - pad_right) return pad_left + pad_right def _measure_column( self, console: "Console", options: "ConsoleOptions", column: Column, ) -> Measurement: """Get the minimum and maximum width of the column.""" max_width = options.max_width if max_width < 1: return Measurement(0, 0) padding_width = self._get_padding_width(column._index) if column.width is not None: # Fixed width column return Measurement( column.width + padding_width, column.width + padding_width ).with_maximum(max_width) # Flexible column, we need to measure contents min_widths: List[int] = [] max_widths: List[int] = [] append_min = min_widths.append append_max = max_widths.append get_render_width = Measurement.get for cell in self._get_cells(console, column._index, column): _min, _max = get_render_width(console, options, cell.renderable) append_min(_min) append_max(_max) measurement = Measurement( max(min_widths) if min_widths else 1, max(max_widths) if max_widths else max_width, ).with_maximum(max_width) measurement = measurement.clamp( None if column.min_width is None else column.min_width + padding_width, None if column.max_width is None else column.max_width + padding_width, ) return measurement def _render( self, console: "Console", options: "ConsoleOptions", widths: List[int] ) -> "RenderResult": table_style = console.get_style(self.style or "") border_style = table_style + console.get_style(self.border_style or "") _column_cells = ( self._get_cells(console, column_index, column) for column_index, column in enumerate(self.columns) ) row_cells: List[Tuple[_Cell, ...]] = list(zip(*_column_cells)) _box = ( self.box.substitute( options, safe=pick_bool(self.safe_box, console.safe_box) ) if self.box else None ) _box = _box.get_plain_headed_box() if _box and not self.show_header else _box new_line = Segment.line() columns = self.columns show_header = self.show_header show_footer = self.show_footer show_edge = self.show_edge show_lines = self.show_lines leading = self.leading _Segment = Segment if _box: box_segments = [ ( _Segment(_box.head_left, border_style), _Segment(_box.head_right, border_style), _Segment(_box.head_vertical, border_style), ), ( _Segment(_box.mid_left, border_style), _Segment(_box.mid_right, border_style), _Segment(_box.mid_vertical, border_style), ), ( _Segment(_box.foot_left, border_style), _Segment(_box.foot_right, border_style), _Segment(_box.foot_vertical, border_style), ), ] if show_edge: yield _Segment(_box.get_top(widths), border_style) yield new_line else: box_segments = [] get_row_style = self.get_row_style
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
true
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_spinners.py
rich/_spinners.py
""" Spinners are from: * cli-spinners: MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ SPINNERS = { "dots": { "interval": 80, "frames": "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏", }, "dots2": {"interval": 80, "frames": "⣾⣽⣻⢿⡿⣟⣯⣷"}, "dots3": { "interval": 80, "frames": "⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓", }, "dots4": { "interval": 80, "frames": "⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆", }, "dots5": { "interval": 80, "frames": "⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋", }, "dots6": { "interval": 80, "frames": "⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁", }, "dots7": { "interval": 80, "frames": "⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈", }, "dots8": { "interval": 80, "frames": "⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈", }, "dots9": {"interval": 80, "frames": "⢹⢺⢼⣸⣇⡧⡗⡏"}, "dots10": {"interval": 80, "frames": "⢄⢂⢁⡁⡈⡐⡠"}, "dots11": {"interval": 100, "frames": "⠁⠂⠄⡀⢀⠠⠐⠈"}, "dots12": { "interval": 80, "frames": [ "⢀⠀", "⡀⠀", "⠄⠀", "⢂⠀", "⡂⠀", "⠅⠀", "⢃⠀", "⡃⠀", "⠍⠀", "⢋⠀", "⡋⠀", "⠍⠁", "⢋⠁", "⡋⠁", "⠍⠉", "⠋⠉", "⠋⠉", "⠉⠙", "⠉⠙", "⠉⠩", "⠈⢙", "⠈⡙", "⢈⠩", "⡀⢙", "⠄⡙", "⢂⠩", "⡂⢘", "⠅⡘", "⢃⠨", "⡃⢐", "⠍⡐", "⢋⠠", "⡋⢀", "⠍⡁", "⢋⠁", "⡋⠁", "⠍⠉", "⠋⠉", "⠋⠉", "⠉⠙", "⠉⠙", "⠉⠩", "⠈⢙", "⠈⡙", "⠈⠩", "⠀⢙", "⠀⡙", "⠀⠩", "⠀⢘", "⠀⡘", "⠀⠨", "⠀⢐", "⠀⡐", "⠀⠠", "⠀⢀", "⠀⡀", ], }, "dots8Bit": { "interval": 80, "frames": "⠀⠁⠂⠃⠄⠅⠆⠇⡀⡁⡂⡃⡄⡅⡆⡇⠈⠉⠊⠋⠌⠍⠎⠏⡈⡉⡊⡋⡌⡍⡎⡏⠐⠑⠒⠓⠔⠕⠖⠗⡐⡑⡒⡓⡔⡕⡖⡗⠘⠙⠚⠛⠜⠝⠞⠟⡘⡙" "⡚⡛⡜⡝⡞⡟⠠⠡⠢⠣⠤⠥⠦⠧⡠⡡⡢⡣⡤⡥⡦⡧⠨⠩⠪⠫⠬⠭⠮⠯⡨⡩⡪⡫⡬⡭⡮⡯⠰⠱⠲⠳⠴⠵⠶⠷⡰⡱⡲⡳⡴⡵⡶⡷⠸⠹⠺⠻" "⠼⠽⠾⠿⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⣀⣁⣂⣃⣄⣅⣆⣇⢈⢉⢊⢋⢌⢍⢎⢏⣈⣉⣊⣋⣌⣍⣎⣏⢐⢑⢒⢓⢔⢕⢖⢗⣐⣑⣒⣓⣔⣕" "⣖⣗⢘⢙⢚⢛⢜⢝⢞⢟⣘⣙⣚⣛⣜⣝⣞⣟⢠⢡⢢⢣⢤⢥⢦⢧⣠⣡⣢⣣⣤⣥⣦⣧⢨⢩⢪⢫⢬⢭⢮⢯⣨⣩⣪⣫⣬⣭⣮⣯⢰⢱⢲⢳⢴⢵⢶⢷" "⣰⣱⣲⣳⣴⣵⣶⣷⢸⢹⢺⢻⢼⢽⢾⢿⣸⣹⣺⣻⣼⣽⣾⣿", }, "line": {"interval": 130, "frames": ["-", "\\", "|", "/"]}, "line2": {"interval": 100, "frames": "⠂-–—–-"}, "pipe": {"interval": 100, "frames": "┤┘┴└├┌┬┐"}, "simpleDots": {"interval": 400, "frames": [". ", ".. ", "...", " "]}, "simpleDotsScrolling": { "interval": 200, "frames": [". ", ".. ", "...", " ..", " .", " "], }, "star": {"interval": 70, "frames": "✶✸✹✺✹✷"}, "star2": {"interval": 80, "frames": "+x*"}, "flip": { "interval": 70, "frames": "___-``'´-___", }, "hamburger": {"interval": 100, "frames": "☱☲☴"}, "growVertical": { "interval": 120, "frames": "▁▃▄▅▆▇▆▅▄▃", }, "growHorizontal": { "interval": 120, "frames": "▏▎▍▌▋▊▉▊▋▌▍▎", }, "balloon": {"interval": 140, "frames": " .oO@* "}, "balloon2": {"interval": 120, "frames": ".oO°Oo."}, "noise": {"interval": 100, "frames": "▓▒░"}, "bounce": {"interval": 120, "frames": "⠁⠂⠄⠂"}, "boxBounce": {"interval": 120, "frames": "▖▘▝▗"}, "boxBounce2": {"interval": 100, "frames": "▌▀▐▄"}, "triangle": {"interval": 50, "frames": "◢◣◤◥"}, "arc": {"interval": 100, "frames": "◜◠◝◞◡◟"}, "circle": {"interval": 120, "frames": "◡⊙◠"}, "squareCorners": {"interval": 180, "frames": "◰◳◲◱"}, "circleQuarters": {"interval": 120, "frames": "◴◷◶◵"}, "circleHalves": {"interval": 50, "frames": "◐◓◑◒"}, "squish": {"interval": 100, "frames": "╫╪"}, "toggle": {"interval": 250, "frames": "⊶⊷"}, "toggle2": {"interval": 80, "frames": "▫▪"}, "toggle3": {"interval": 120, "frames": "□■"}, "toggle4": {"interval": 100, "frames": "■□▪▫"}, "toggle5": {"interval": 100, "frames": "▮▯"}, "toggle6": {"interval": 300, "frames": "ဝ၀"}, "toggle7": {"interval": 80, "frames": "⦾⦿"}, "toggle8": {"interval": 100, "frames": "◍◌"}, "toggle9": {"interval": 100, "frames": "◉◎"}, "toggle10": {"interval": 100, "frames": "㊂㊀㊁"}, "toggle11": {"interval": 50, "frames": "⧇⧆"}, "toggle12": {"interval": 120, "frames": "☗☖"}, "toggle13": {"interval": 80, "frames": "=*-"}, "arrow": {"interval": 100, "frames": "←↖↑↗→↘↓↙"}, "arrow2": { "interval": 80, "frames": ["⬆️ ", "↗️ ", "➡️ ", "↘️ ", "⬇️ ", "↙️ ", "⬅️ ", "↖️ "], }, "arrow3": { "interval": 120, "frames": ["▹▹▹▹▹", "▸▹▹▹▹", "▹▸▹▹▹", "▹▹▸▹▹", "▹▹▹▸▹", "▹▹▹▹▸"], }, "bouncingBar": { "interval": 80, "frames": [ "[ ]", "[= ]", "[== ]", "[=== ]", "[ ===]", "[ ==]", "[ =]", "[ ]", "[ =]", "[ ==]", "[ ===]", "[====]", "[=== ]", "[== ]", "[= ]", ], }, "bouncingBall": { "interval": 80, "frames": [ "( ● )", "( ● )", "( ● )", "( ● )", "( ●)", "( ● )", "( ● )", "( ● )", "( ● )", "(● )", ], }, "smiley": {"interval": 200, "frames": ["😄 ", "😝 "]}, "monkey": {"interval": 300, "frames": ["🙈 ", "🙈 ", "🙉 ", "🙊 "]}, "hearts": {"interval": 100, "frames": ["💛 ", "💙 ", "💜 ", "💚 ", "❤️ "]}, "clock": { "interval": 100, "frames": [ "🕛 ", "🕐 ", "🕑 ", "🕒 ", "🕓 ", "🕔 ", "🕕 ", "🕖 ", "🕗 ", "🕘 ", "🕙 ", "🕚 ", ], }, "earth": {"interval": 180, "frames": ["🌍 ", "🌎 ", "🌏 "]}, "material": { "interval": 17, "frames": [ "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "███████▁▁▁▁▁▁▁▁▁▁▁▁▁", "████████▁▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "██████████▁▁▁▁▁▁▁▁▁▁", "███████████▁▁▁▁▁▁▁▁▁", "█████████████▁▁▁▁▁▁▁", "██████████████▁▁▁▁▁▁", "██████████████▁▁▁▁▁▁", "▁██████████████▁▁▁▁▁", "▁██████████████▁▁▁▁▁", "▁██████████████▁▁▁▁▁", "▁▁██████████████▁▁▁▁", "▁▁▁██████████████▁▁▁", "▁▁▁▁█████████████▁▁▁", "▁▁▁▁██████████████▁▁", "▁▁▁▁██████████████▁▁", "▁▁▁▁▁██████████████▁", "▁▁▁▁▁██████████████▁", "▁▁▁▁▁██████████████▁", "▁▁▁▁▁▁██████████████", "▁▁▁▁▁▁██████████████", "▁▁▁▁▁▁▁█████████████", "▁▁▁▁▁▁▁█████████████", "▁▁▁▁▁▁▁▁████████████", "▁▁▁▁▁▁▁▁████████████", "▁▁▁▁▁▁▁▁▁███████████", "▁▁▁▁▁▁▁▁▁███████████", "▁▁▁▁▁▁▁▁▁▁██████████", "▁▁▁▁▁▁▁▁▁▁██████████", "▁▁▁▁▁▁▁▁▁▁▁▁████████", "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", "██████▁▁▁▁▁▁▁▁▁▁▁▁▁█", "████████▁▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "███████████▁▁▁▁▁▁▁▁▁", "████████████▁▁▁▁▁▁▁▁", "████████████▁▁▁▁▁▁▁▁", "██████████████▁▁▁▁▁▁", "██████████████▁▁▁▁▁▁", "▁██████████████▁▁▁▁▁", "▁██████████████▁▁▁▁▁", "▁▁▁█████████████▁▁▁▁", "▁▁▁▁▁████████████▁▁▁", "▁▁▁▁▁████████████▁▁▁", "▁▁▁▁▁▁███████████▁▁▁", "▁▁▁▁▁▁▁▁█████████▁▁▁", "▁▁▁▁▁▁▁▁█████████▁▁▁", "▁▁▁▁▁▁▁▁▁█████████▁▁", "▁▁▁▁▁▁▁▁▁█████████▁▁", "▁▁▁▁▁▁▁▁▁▁█████████▁", "▁▁▁▁▁▁▁▁▁▁▁████████▁", "▁▁▁▁▁▁▁▁▁▁▁████████▁", "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", ], }, "moon": { "interval": 80, "frames": ["🌑 ", "🌒 ", "🌓 ", "🌔 ", "🌕 ", "🌖 ", "🌗 ", "🌘 "], }, "runner": {"interval": 140, "frames": ["🚶 ", "🏃 "]}, "pong": { "interval": 80, "frames": [ "▐⠂ ▌", "▐⠈ ▌", "▐ ⠂ ▌", "▐ ⠠ ▌", "▐ ⡀ ▌", "▐ ⠠ ▌", "▐ ⠂ ▌", "▐ ⠈ ▌", "▐ ⠂ ▌", "▐ ⠠ ▌", "▐ ⡀ ▌", "▐ ⠠ ▌", "▐ ⠂ ▌", "▐ ⠈ ▌", "▐ ⠂▌", "▐ ⠠▌", "▐ ⡀▌", "▐ ⠠ ▌", "▐ ⠂ ▌", "▐ ⠈ ▌", "▐ ⠂ ▌", "▐ ⠠ ▌", "▐ ⡀ ▌", "▐ ⠠ ▌", "▐ ⠂ ▌", "▐ ⠈ ▌", "▐ ⠂ ▌", "▐ ⠠ ▌", "▐ ⡀ ▌", "▐⠠ ▌", ], }, "shark": { "interval": 120, "frames": [ "▐|\\____________▌", "▐_|\\___________▌", "▐__|\\__________▌", "▐___|\\_________▌", "▐____|\\________▌", "▐_____|\\_______▌", "▐______|\\______▌", "▐_______|\\_____▌", "▐________|\\____▌", "▐_________|\\___▌", "▐__________|\\__▌", "▐___________|\\_▌", "▐____________|\\▌", "▐____________/|▌", "▐___________/|_▌", "▐__________/|__▌", "▐_________/|___▌", "▐________/|____▌", "▐_______/|_____▌", "▐______/|______▌", "▐_____/|_______▌", "▐____/|________▌", "▐___/|_________▌", "▐__/|__________▌", "▐_/|___________▌", "▐/|____________▌", ], }, "dqpb": {"interval": 100, "frames": "dqpb"}, "weather": { "interval": 100, "frames": [ "☀️ ", "☀️ ", "☀️ ", "🌤 ", "⛅️ ", "🌥 ", "☁️ ", "🌧 ", "🌨 ", "🌧 ", "🌨 ", "🌧 ", "🌨 ", "⛈ ", "🌨 ", "🌧 ", "🌨 ", "☁️ ", "🌥 ", "⛅️ ", "🌤 ", "☀️ ", "☀️ ", ], }, "christmas": {"interval": 400, "frames": "🌲🎄"}, "grenade": { "interval": 80, "frames": [ "، ", "′ ", " ´ ", " ‾ ", " ⸌", " ⸊", " |", " ⁎", " ⁕", " ෴ ", " ⁓", " ", " ", " ", ], }, "point": {"interval": 125, "frames": ["∙∙∙", "●∙∙", "∙●∙", "∙∙●", "∙∙∙"]}, "layer": {"interval": 150, "frames": "-=≡"}, "betaWave": { "interval": 80, "frames": [ "ρββββββ", "βρβββββ", "ββρββββ", "βββρβββ", "ββββρββ", "βββββρβ", "ββββββρ", ], }, "aesthetic": { "interval": 80, "frames": [ "▰▱▱▱▱▱▱", "▰▰▱▱▱▱▱", "▰▰▰▱▱▱▱", "▰▰▰▰▱▱▱", "▰▰▰▰▰▱▱", "▰▰▰▰▰▰▱", "▰▰▰▰▰▰▰", "▰▱▱▱▱▱▱", ], }, }
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/panel.py
rich/panel.py
from typing import TYPE_CHECKING, Optional from .align import AlignMethod from .box import ROUNDED, Box from .cells import cell_len from .jupyter import JupyterMixin from .measure import Measurement, measure_renderables from .padding import Padding, PaddingDimensions from .segment import Segment from .style import Style, StyleType from .text import Text, TextType if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderableType, RenderResult class Panel(JupyterMixin): """A console renderable that draws a border around its contents. Example: >>> console.print(Panel("Hello, World!")) Args: renderable (RenderableType): A console renderable object. box (Box): A Box instance that defines the look of the border (see :ref:`appendix_box`. Defaults to box.ROUNDED. title (Optional[TextType], optional): Optional title displayed in panel header. Defaults to None. title_align (AlignMethod, optional): Alignment of title. Defaults to "center". subtitle (Optional[TextType], optional): Optional subtitle displayed in panel footer. Defaults to None. subtitle_align (AlignMethod, optional): Alignment of subtitle. Defaults to "center". safe_box (bool, optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True. expand (bool, optional): If True the panel will stretch to fill the console width, otherwise it will be sized to fit the contents. Defaults to True. style (str, optional): The style of the panel (border and contents). Defaults to "none". border_style (str, optional): The style of the border. Defaults to "none". width (Optional[int], optional): Optional width of panel. Defaults to None to auto-detect. height (Optional[int], optional): Optional height of panel. Defaults to None to auto-detect. padding (Optional[PaddingDimensions]): Optional padding around renderable. Defaults to 0. highlight (bool, optional): Enable automatic highlighting of panel title (if str). Defaults to False. """ def __init__( self, renderable: "RenderableType", box: Box = ROUNDED, *, title: Optional[TextType] = None, title_align: AlignMethod = "center", subtitle: Optional[TextType] = None, subtitle_align: AlignMethod = "center", safe_box: Optional[bool] = None, expand: bool = True, style: StyleType = "none", border_style: StyleType = "none", width: Optional[int] = None, height: Optional[int] = None, padding: PaddingDimensions = (0, 1), highlight: bool = False, ) -> None: self.renderable = renderable self.box = box self.title = title self.title_align: AlignMethod = title_align self.subtitle = subtitle self.subtitle_align = subtitle_align self.safe_box = safe_box self.expand = expand self.style = style self.border_style = border_style self.width = width self.height = height self.padding = padding self.highlight = highlight @classmethod def fit( cls, renderable: "RenderableType", box: Box = ROUNDED, *, title: Optional[TextType] = None, title_align: AlignMethod = "center", subtitle: Optional[TextType] = None, subtitle_align: AlignMethod = "center", safe_box: Optional[bool] = None, style: StyleType = "none", border_style: StyleType = "none", width: Optional[int] = None, height: Optional[int] = None, padding: PaddingDimensions = (0, 1), highlight: bool = False, ) -> "Panel": """An alternative constructor that sets expand=False.""" return cls( renderable, box, title=title, title_align=title_align, subtitle=subtitle, subtitle_align=subtitle_align, safe_box=safe_box, style=style, border_style=border_style, width=width, height=height, padding=padding, highlight=highlight, expand=False, ) @property def _title(self) -> Optional[Text]: if self.title: title_text = ( Text.from_markup(self.title) if isinstance(self.title, str) else self.title.copy() ) title_text.end = "" title_text.plain = title_text.plain.replace("\n", " ") title_text.no_wrap = True title_text.expand_tabs() title_text.pad(1) return title_text return None @property def _subtitle(self) -> Optional[Text]: if self.subtitle: subtitle_text = ( Text.from_markup(self.subtitle) if isinstance(self.subtitle, str) else self.subtitle.copy() ) subtitle_text.end = "" subtitle_text.plain = subtitle_text.plain.replace("\n", " ") subtitle_text.no_wrap = True subtitle_text.expand_tabs() subtitle_text.pad(1) return subtitle_text return None def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": _padding = Padding.unpack(self.padding) renderable = ( Padding(self.renderable, _padding) if any(_padding) else self.renderable ) style = console.get_style(self.style) border_style = style + console.get_style(self.border_style) width = ( options.max_width if self.width is None else min(options.max_width, self.width) ) safe_box: bool = console.safe_box if self.safe_box is None else self.safe_box box = self.box.substitute(options, safe=safe_box) def align_text( text: Text, width: int, align: str, character: str, style: Style ) -> Text: """Gets new aligned text. Args: text (Text): Title or subtitle text. width (int): Desired width. align (str): Alignment. character (str): Character for alignment. style (Style): Border style Returns: Text: New text instance """ text = text.copy() text.truncate(width) excess_space = width - cell_len(text.plain) if text.style: text.stylize(console.get_style(text.style)) if excess_space: if align == "left": return Text.assemble( text, (character * excess_space, style), no_wrap=True, end="", ) elif align == "center": left = excess_space // 2 return Text.assemble( (character * left, style), text, (character * (excess_space - left), style), no_wrap=True, end="", ) else: return Text.assemble( (character * excess_space, style), text, no_wrap=True, end="", ) return text title_text = self._title if title_text is not None: title_text.stylize_before(border_style) child_width = ( width - 2 if self.expand else console.measure( renderable, options=options.update_width(width - 2) ).maximum ) child_height = self.height or options.height or None if child_height: child_height -= 2 if title_text is not None: child_width = min( options.max_width - 2, max(child_width, title_text.cell_len + 2) ) width = child_width + 2 child_options = options.update( width=child_width, height=child_height, highlight=self.highlight ) lines = console.render_lines(renderable, child_options, style=style) line_start = Segment(box.mid_left, border_style) line_end = Segment(f"{box.mid_right}", border_style) new_line = Segment.line() if title_text is None or width <= 4: yield Segment(box.get_top([width - 2]), border_style) else: title_text = align_text( title_text, width - 4, self.title_align, box.top, border_style, ) yield Segment(box.top_left + box.top, border_style) yield from console.render(title_text, child_options.update_width(width - 4)) yield Segment(box.top + box.top_right, border_style) yield new_line for line in lines: yield line_start yield from line yield line_end yield new_line subtitle_text = self._subtitle if subtitle_text is not None: subtitle_text.stylize_before(border_style) if subtitle_text is None or width <= 4: yield Segment(box.get_bottom([width - 2]), border_style) else: subtitle_text = align_text( subtitle_text, width - 4, self.subtitle_align, box.bottom, border_style, ) yield Segment(box.bottom_left + box.bottom, border_style) yield from console.render( subtitle_text, child_options.update_width(width - 4) ) yield Segment(box.bottom + box.bottom_right, border_style) yield new_line def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> "Measurement": _title = self._title _, right, _, left = Padding.unpack(self.padding) padding = left + right renderables = [self.renderable, _title] if _title else [self.renderable] if self.width is None: width = ( measure_renderables( console, options.update_width(options.max_width - padding - 2), renderables, ).maximum + padding + 2 ) else: width = self.width return Measurement(width, width) if __name__ == "__main__": # pragma: no cover from .console import Console c = Console() from .box import DOUBLE, ROUNDED from .padding import Padding p = Panel( "Hello, World!", title="rich.Panel", style="white on blue", box=DOUBLE, padding=1, ) c.print() c.print(p)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/markup.py
rich/markup.py
import re from ast import literal_eval from operator import attrgetter from typing import Callable, Iterable, List, Match, NamedTuple, Optional, Tuple, Union from ._emoji_replace import _emoji_replace from .emoji import EmojiVariant from .errors import MarkupError from .style import Style from .text import Span, Text RE_TAGS = re.compile( r"""((\\*)\[([a-z#/@][^[]*?)])""", re.VERBOSE, ) RE_HANDLER = re.compile(r"^([\w.]*?)(\(.*?\))?$") class Tag(NamedTuple): """A tag in console markup.""" name: str """The tag name. e.g. 'bold'.""" parameters: Optional[str] """Any additional parameters after the name.""" def __str__(self) -> str: return ( self.name if self.parameters is None else f"{self.name} {self.parameters}" ) @property def markup(self) -> str: """Get the string representation of this tag.""" return ( f"[{self.name}]" if self.parameters is None else f"[{self.name}={self.parameters}]" ) _ReStringMatch = Match[str] # regex match object _ReSubCallable = Callable[[_ReStringMatch], str] # Callable invoked by re.sub _EscapeSubMethod = Callable[[_ReSubCallable, str], str] # Sub method of a compiled re def escape( markup: str, _escape: _EscapeSubMethod = re.compile(r"(\\*)(\[[a-z#/@][^[]*?])").sub, ) -> str: """Escapes text so that it won't be interpreted as markup. Args: markup (str): Content to be inserted in to markup. Returns: str: Markup with square brackets escaped. """ def escape_backslashes(match: Match[str]) -> str: """Called by re.sub replace matches.""" backslashes, text = match.groups() return f"{backslashes}{backslashes}\\{text}" markup = _escape(escape_backslashes, markup) if markup.endswith("\\") and not markup.endswith("\\\\"): return markup + "\\" return markup def _parse(markup: str) -> Iterable[Tuple[int, Optional[str], Optional[Tag]]]: """Parse markup in to an iterable of tuples of (position, text, tag). Args: markup (str): A string containing console markup """ position = 0 _divmod = divmod _Tag = Tag for match in RE_TAGS.finditer(markup): full_text, escapes, tag_text = match.groups() start, end = match.span() if start > position: yield start, markup[position:start], None if escapes: backslashes, escaped = _divmod(len(escapes), 2) if backslashes: # Literal backslashes yield start, "\\" * backslashes, None start += backslashes * 2 if escaped: # Escape of tag yield start, full_text[len(escapes) :], None position = end continue text, equals, parameters = tag_text.partition("=") yield start, None, _Tag(text, parameters if equals else None) position = end if position < len(markup): yield position, markup[position:], None def render( markup: str, style: Union[str, Style] = "", emoji: bool = True, emoji_variant: Optional[EmojiVariant] = None, ) -> Text: """Render console markup in to a Text instance. Args: markup (str): A string containing console markup. style: (Union[str, Style]): The style to use. emoji (bool, optional): Also render emoji code. Defaults to True. emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None. Raises: MarkupError: If there is a syntax error in the markup. Returns: Text: A test instance. """ emoji_replace = _emoji_replace if "[" not in markup: return Text( emoji_replace(markup, default_variant=emoji_variant) if emoji else markup, style=style, ) text = Text(style=style) append = text.append normalize = Style.normalize style_stack: List[Tuple[int, Tag]] = [] pop = style_stack.pop spans: List[Span] = [] append_span = spans.append _Span = Span _Tag = Tag def pop_style(style_name: str) -> Tuple[int, Tag]: """Pop tag matching given style name.""" for index, (_, tag) in enumerate(reversed(style_stack), 1): if tag.name == style_name: return pop(-index) raise KeyError(style_name) for position, plain_text, tag in _parse(markup): if plain_text is not None: # Handle open brace escapes, where the brace is not part of a tag. plain_text = plain_text.replace("\\[", "[") append(emoji_replace(plain_text) if emoji else plain_text) elif tag is not None: if tag.name.startswith("/"): # Closing tag style_name = tag.name[1:].strip() if style_name: # explicit close style_name = normalize(style_name) try: start, open_tag = pop_style(style_name) except KeyError: raise MarkupError( f"closing tag '{tag.markup}' at position {position} doesn't match any open tag" ) from None else: # implicit close try: start, open_tag = pop() except IndexError: raise MarkupError( f"closing tag '[/]' at position {position} has nothing to close" ) from None if open_tag.name.startswith("@"): if open_tag.parameters: handler_name = "" parameters = open_tag.parameters.strip() handler_match = RE_HANDLER.match(parameters) if handler_match is not None: handler_name, match_parameters = handler_match.groups() parameters = ( "()" if match_parameters is None else match_parameters ) try: meta_params = literal_eval(parameters) except SyntaxError as error: raise MarkupError( f"error parsing {parameters!r} in {open_tag.parameters!r}; {error.msg}" ) except Exception as error: raise MarkupError( f"error parsing {open_tag.parameters!r}; {error}" ) from None if handler_name: meta_params = ( handler_name, meta_params if isinstance(meta_params, tuple) else (meta_params,), ) else: meta_params = () append_span( _Span( start, len(text), Style(meta={open_tag.name: meta_params}) ) ) else: append_span(_Span(start, len(text), str(open_tag))) else: # Opening tag normalized_tag = _Tag(normalize(tag.name), tag.parameters) style_stack.append((len(text), normalized_tag)) text_length = len(text) while style_stack: start, tag = style_stack.pop() style = str(tag) if style: append_span(_Span(start, text_length, style)) text.spans = sorted(spans[::-1], key=attrgetter("start")) return text if __name__ == "__main__": # pragma: no cover MARKUP = [ "[red]Hello World[/red]", "[magenta]Hello [b]World[/b]", "[bold]Bold[italic] bold and italic [/bold]italic[/italic]", "Click [link=https://www.willmcgugan.com]here[/link] to visit my Blog", ":warning-emoji: [bold red blink] DANGER![/]", ] from rich import print from rich.table import Table grid = Table("Markup", "Result", padding=(0, 1)) for markup in MARKUP: grid.add_row(Text(markup), markup) print(grid)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/align.py
rich/align.py
from itertools import chain from typing import TYPE_CHECKING, Iterable, Optional, Literal from .constrain import Constrain from .jupyter import JupyterMixin from .measure import Measurement from .segment import Segment from .style import StyleType if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderableType, RenderResult AlignMethod = Literal["left", "center", "right"] VerticalAlignMethod = Literal["top", "middle", "bottom"] class Align(JupyterMixin): """Align a renderable by adding spaces if necessary. Args: renderable (RenderableType): A console renderable. align (AlignMethod): One of "left", "center", or "right"" style (StyleType, optional): An optional style to apply to the background. vertical (Optional[VerticalAlignMethod], optional): Optional vertical align, one of "top", "middle", or "bottom". Defaults to None. pad (bool, optional): Pad the right with spaces. Defaults to True. width (int, optional): Restrict contents to given width, or None to use default width. Defaults to None. height (int, optional): Set height of align renderable, or None to fit to contents. Defaults to None. Raises: ValueError: if ``align`` is not one of the expected values. """ def __init__( self, renderable: "RenderableType", align: AlignMethod = "left", style: Optional[StyleType] = None, *, vertical: Optional[VerticalAlignMethod] = None, pad: bool = True, width: Optional[int] = None, height: Optional[int] = None, ) -> None: if align not in ("left", "center", "right"): raise ValueError( f'invalid value for align, expected "left", "center", or "right" (not {align!r})' ) if vertical is not None and vertical not in ("top", "middle", "bottom"): raise ValueError( f'invalid value for vertical, expected "top", "middle", or "bottom" (not {vertical!r})' ) self.renderable = renderable self.align = align self.style = style self.vertical = vertical self.pad = pad self.width = width self.height = height def __repr__(self) -> str: return f"Align({self.renderable!r}, {self.align!r})" @classmethod def left( cls, renderable: "RenderableType", style: Optional[StyleType] = None, *, vertical: Optional[VerticalAlignMethod] = None, pad: bool = True, width: Optional[int] = None, height: Optional[int] = None, ) -> "Align": """Align a renderable to the left.""" return cls( renderable, "left", style=style, vertical=vertical, pad=pad, width=width, height=height, ) @classmethod def center( cls, renderable: "RenderableType", style: Optional[StyleType] = None, *, vertical: Optional[VerticalAlignMethod] = None, pad: bool = True, width: Optional[int] = None, height: Optional[int] = None, ) -> "Align": """Align a renderable to the center.""" return cls( renderable, "center", style=style, vertical=vertical, pad=pad, width=width, height=height, ) @classmethod def right( cls, renderable: "RenderableType", style: Optional[StyleType] = None, *, vertical: Optional[VerticalAlignMethod] = None, pad: bool = True, width: Optional[int] = None, height: Optional[int] = None, ) -> "Align": """Align a renderable to the right.""" return cls( renderable, "right", style=style, vertical=vertical, pad=pad, width=width, height=height, ) def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": align = self.align width = console.measure(self.renderable, options=options).maximum rendered = console.render( Constrain( self.renderable, width if self.width is None else min(width, self.width) ), options.update(height=None), ) lines = list(Segment.split_lines(rendered)) width, height = Segment.get_shape(lines) lines = Segment.set_shape(lines, width, height) new_line = Segment.line() excess_space = options.max_width - width style = console.get_style(self.style) if self.style is not None else None def generate_segments() -> Iterable[Segment]: if excess_space <= 0: # Exact fit for line in lines: yield from line yield new_line elif align == "left": # Pad on the right pad = Segment(" " * excess_space, style) if self.pad else None for line in lines: yield from line if pad: yield pad yield new_line elif align == "center": # Pad left and right left = excess_space // 2 pad = Segment(" " * left, style) pad_right = ( Segment(" " * (excess_space - left), style) if self.pad else None ) for line in lines: if left: yield pad yield from line if pad_right: yield pad_right yield new_line elif align == "right": # Padding on left pad = Segment(" " * excess_space, style) for line in lines: yield pad yield from line yield new_line blank_line = ( Segment(f"{' ' * (self.width or options.max_width)}\n", style) if self.pad else Segment("\n") ) def blank_lines(count: int) -> Iterable[Segment]: if count > 0: for _ in range(count): yield blank_line vertical_height = self.height or options.height iter_segments: Iterable[Segment] if self.vertical and vertical_height is not None: if self.vertical == "top": bottom_space = vertical_height - height iter_segments = chain(generate_segments(), blank_lines(bottom_space)) elif self.vertical == "middle": top_space = (vertical_height - height) // 2 bottom_space = vertical_height - top_space - height iter_segments = chain( blank_lines(top_space), generate_segments(), blank_lines(bottom_space), ) else: # self.vertical == "bottom": top_space = vertical_height - height iter_segments = chain(blank_lines(top_space), generate_segments()) else: iter_segments = generate_segments() if self.style: style = console.get_style(self.style) iter_segments = Segment.apply_style(iter_segments, style) yield from iter_segments def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> Measurement: measurement = Measurement.get(console, options, self.renderable) return measurement class VerticalCenter(JupyterMixin): """Vertically aligns a renderable. Warn: This class is deprecated and may be removed in a future version. Use Align class with `vertical="middle"`. Args: renderable (RenderableType): A renderable object. style (StyleType, optional): An optional style to apply to the background. Defaults to None. """ def __init__( self, renderable: "RenderableType", style: Optional[StyleType] = None, ) -> None: self.renderable = renderable self.style = style def __repr__(self) -> str: return f"VerticalCenter({self.renderable!r})" def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": style = console.get_style(self.style) if self.style is not None else None lines = console.render_lines( self.renderable, options.update(height=None), pad=False ) width, _height = Segment.get_shape(lines) new_line = Segment.line() height = options.height or options.size.height top_space = (height - len(lines)) // 2 bottom_space = height - top_space - len(lines) blank_line = Segment(f"{' ' * width}", style) def blank_lines(count: int) -> Iterable[Segment]: for _ in range(count): yield blank_line yield new_line if top_space > 0: yield from blank_lines(top_space) for line in lines: yield from line yield new_line if bottom_space > 0: yield from blank_lines(bottom_space) def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> Measurement: measurement = Measurement.get(console, options, self.renderable) return measurement if __name__ == "__main__": # pragma: no cover from rich.console import Console, Group from rich.highlighter import ReprHighlighter from rich.panel import Panel highlighter = ReprHighlighter() console = Console() panel = Panel( Group( Align.left(highlighter("align='left'")), Align.center(highlighter("align='center'")), Align.right(highlighter("align='right'")), ), width=60, style="on dark_blue", title="Align", ) console.print( Align.center(panel, vertical="middle", style="on red", height=console.height) )
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_wrap.py
rich/_wrap.py
from __future__ import annotations import re from typing import Iterable from ._loop import loop_last from .cells import cell_len, chop_cells re_word = re.compile(r"\s*\S+\s*") def words(text: str) -> Iterable[tuple[int, int, str]]: """Yields each word from the text as a tuple containing (start_index, end_index, word). A "word" in this context may include the actual word and any whitespace to the right. """ position = 0 word_match = re_word.match(text, position) while word_match is not None: start, end = word_match.span() word = word_match.group(0) yield start, end, word word_match = re_word.match(text, end) def divide_line(text: str, width: int, fold: bool = True) -> list[int]: """Given a string of text, and a width (measured in cells), return a list of cell offsets which the string should be split at in order for it to fit within the given width. Args: text: The text to examine. width: The available cell width. fold: If True, words longer than `width` will be folded onto a new line. Returns: A list of indices to break the line at. """ break_positions: list[int] = [] # offsets to insert the breaks at append = break_positions.append cell_offset = 0 _cell_len = cell_len for start, _end, word in words(text): word_length = _cell_len(word.rstrip()) remaining_space = width - cell_offset word_fits_remaining_space = remaining_space >= word_length if word_fits_remaining_space: # Simplest case - the word fits within the remaining width for this line. cell_offset += _cell_len(word) else: # Not enough space remaining for this word on the current line. if word_length > width: # The word doesn't fit on any line, so we can't simply # place it on the next line... if fold: # Fold the word across multiple lines. folded_word = chop_cells(word, width=width) for last, line in loop_last(folded_word): if start: append(start) if last: cell_offset = _cell_len(line) else: start += len(line) else: # Folding isn't allowed, so crop the word. if start: append(start) cell_offset = _cell_len(word) elif cell_offset and start: # The word doesn't fit within the remaining space on the current # line, but it *can* fit on to the next (empty) line. append(start) cell_offset = _cell_len(word) return break_positions if __name__ == "__main__": # pragma: no cover from .console import Console console = Console(width=10) console.print("12345 abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ 12345") print(chop_cells("abcdefghijklmnopqrstuvwxyz", 10)) console = Console(width=20) console.rule() console.print("TextualはPythonの高速アプリケーション開発フレームワークです") console.rule() console.print("アプリケーションは1670万色を使用でき")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_fileno.py
rich/_fileno.py
from __future__ import annotations from typing import IO, Callable def get_fileno(file_like: IO[str]) -> int | None: """Get fileno() from a file, accounting for poorly implemented file-like objects. Args: file_like (IO): A file-like object. Returns: int | None: The result of fileno if available, or None if operation failed. """ fileno: Callable[[], int] | None = getattr(file_like, "fileno", None) if fileno is not None: try: return fileno() except Exception: # `fileno` is documented as potentially raising a OSError # Alas, from the issues, there are so many poorly implemented file-like objects, # that `fileno()` can raise just about anything. return None return None
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/segment.py
rich/segment.py
from enum import IntEnum from functools import lru_cache from itertools import filterfalse from logging import getLogger from operator import attrgetter from typing import ( TYPE_CHECKING, Dict, Iterable, List, NamedTuple, Optional, Sequence, Tuple, Type, Union, ) from .cells import ( _is_single_cell_widths, cached_cell_len, cell_len, get_character_cell_size, set_cell_size, ) from .repr import Result, rich_repr from .style import Style if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderResult log = getLogger("rich") class ControlType(IntEnum): """Non-printable control codes which typically translate to ANSI codes.""" BELL = 1 CARRIAGE_RETURN = 2 HOME = 3 CLEAR = 4 SHOW_CURSOR = 5 HIDE_CURSOR = 6 ENABLE_ALT_SCREEN = 7 DISABLE_ALT_SCREEN = 8 CURSOR_UP = 9 CURSOR_DOWN = 10 CURSOR_FORWARD = 11 CURSOR_BACKWARD = 12 CURSOR_MOVE_TO_COLUMN = 13 CURSOR_MOVE_TO = 14 ERASE_IN_LINE = 15 SET_WINDOW_TITLE = 16 ControlCode = Union[ Tuple[ControlType], Tuple[ControlType, Union[int, str]], Tuple[ControlType, int, int], ] @rich_repr() class Segment(NamedTuple): """A piece of text with associated style. Segments are produced by the Console render process and are ultimately converted in to strings to be written to the terminal. Args: text (str): A piece of text. style (:class:`~rich.style.Style`, optional): An optional style to apply to the text. control (Tuple[ControlCode], optional): Optional sequence of control codes. Attributes: cell_length (int): The cell length of this Segment. """ text: str style: Optional[Style] = None control: Optional[Sequence[ControlCode]] = None @property def cell_length(self) -> int: """The number of terminal cells required to display self.text. Returns: int: A number of cells. """ text, _style, control = self return 0 if control else cell_len(text) def __rich_repr__(self) -> Result: yield self.text if self.control is None: if self.style is not None: yield self.style else: yield self.style yield self.control def __bool__(self) -> bool: """Check if the segment contains text.""" return bool(self.text) @property def is_control(self) -> bool: """Check if the segment contains control codes.""" return self.control is not None @classmethod @lru_cache(1024 * 16) def _split_cells(cls, segment: "Segment", cut: int) -> Tuple["Segment", "Segment"]: """Split a segment in to two at a given cell position. Note that splitting a double-width character, may result in that character turning into two spaces. Args: segment (Segment): A segment to split. cut (int): A cell position to cut on. Returns: A tuple of two segments. """ text, style, control = segment _Segment = Segment cell_length = segment.cell_length if cut >= cell_length: return segment, _Segment("", style, control) cell_size = get_character_cell_size pos = int((cut / cell_length) * len(text)) while True: before = text[:pos] cell_pos = cell_len(before) out_by = cell_pos - cut if not out_by: return ( _Segment(before, style, control), _Segment(text[pos:], style, control), ) if out_by == -1 and cell_size(text[pos]) == 2: return ( _Segment(text[:pos] + " ", style, control), _Segment(" " + text[pos + 1 :], style, control), ) if out_by == +1 and cell_size(text[pos - 1]) == 2: return ( _Segment(text[: pos - 1] + " ", style, control), _Segment(" " + text[pos:], style, control), ) if cell_pos < cut: pos += 1 else: pos -= 1 def split_cells(self, cut: int) -> Tuple["Segment", "Segment"]: """Split segment in to two segments at the specified column. If the cut point falls in the middle of a 2-cell wide character then it is replaced by two spaces, to preserve the display width of the parent segment. Args: cut (int): Offset within the segment to cut. Returns: Tuple[Segment, Segment]: Two segments. """ text, style, control = self assert cut >= 0 if _is_single_cell_widths(text): # Fast path with all 1 cell characters if cut >= len(text): return self, Segment("", style, control) return ( Segment(text[:cut], style, control), Segment(text[cut:], style, control), ) return self._split_cells(self, cut) @classmethod def line(cls) -> "Segment": """Make a new line segment.""" return cls("\n") @classmethod def apply_style( cls, segments: Iterable["Segment"], style: Optional[Style] = None, post_style: Optional[Style] = None, ) -> Iterable["Segment"]: """Apply style(s) to an iterable of segments. Returns an iterable of segments where the style is replaced by ``style + segment.style + post_style``. Args: segments (Iterable[Segment]): Segments to process. style (Style, optional): Base style. Defaults to None. post_style (Style, optional): Style to apply on top of segment style. Defaults to None. Returns: Iterable[Segments]: A new iterable of segments (possibly the same iterable). """ result_segments = segments if style: apply = style.__add__ result_segments = ( cls(text, None if control else apply(_style), control) for text, _style, control in result_segments ) if post_style: result_segments = ( cls( text, ( None if control else (_style + post_style if _style else post_style) ), control, ) for text, _style, control in result_segments ) return result_segments @classmethod def filter_control( cls, segments: Iterable["Segment"], is_control: bool = False ) -> Iterable["Segment"]: """Filter segments by ``is_control`` attribute. Args: segments (Iterable[Segment]): An iterable of Segment instances. is_control (bool, optional): is_control flag to match in search. Returns: Iterable[Segment]: And iterable of Segment instances. """ if is_control: return filter(attrgetter("control"), segments) else: return filterfalse(attrgetter("control"), segments) @classmethod def split_lines(cls, segments: Iterable["Segment"]) -> Iterable[List["Segment"]]: """Split a sequence of segments in to a list of lines. Args: segments (Iterable[Segment]): Segments potentially containing line feeds. Yields: Iterable[List[Segment]]: Iterable of segment lists, one per line. """ line: List[Segment] = [] append = line.append for segment in segments: if "\n" in segment.text and not segment.control: text, style, _ = segment while text: _text, new_line, text = text.partition("\n") if _text: append(cls(_text, style)) if new_line: yield line line = [] append = line.append else: append(segment) if line: yield line @classmethod def split_and_crop_lines( cls, segments: Iterable["Segment"], length: int, style: Optional[Style] = None, pad: bool = True, include_new_lines: bool = True, ) -> Iterable[List["Segment"]]: """Split segments in to lines, and crop lines greater than a given length. Args: segments (Iterable[Segment]): An iterable of segments, probably generated from console.render. length (int): Desired line length. style (Style, optional): Style to use for any padding. pad (bool): Enable padding of lines that are less than `length`. Returns: Iterable[List[Segment]]: An iterable of lines of segments. """ line: List[Segment] = [] append = line.append adjust_line_length = cls.adjust_line_length new_line_segment = cls("\n") for segment in segments: if "\n" in segment.text and not segment.control: text, segment_style, _ = segment while text: _text, new_line, text = text.partition("\n") if _text: append(cls(_text, segment_style)) if new_line: cropped_line = adjust_line_length( line, length, style=style, pad=pad ) if include_new_lines: cropped_line.append(new_line_segment) yield cropped_line line.clear() else: append(segment) if line: yield adjust_line_length(line, length, style=style, pad=pad) @classmethod def adjust_line_length( cls, line: List["Segment"], length: int, style: Optional[Style] = None, pad: bool = True, ) -> List["Segment"]: """Adjust a line to a given width (cropping or padding as required). Args: segments (Iterable[Segment]): A list of segments in a single line. length (int): The desired width of the line. style (Style, optional): The style of padding if used (space on the end). Defaults to None. pad (bool, optional): Pad lines with spaces if they are shorter than `length`. Defaults to True. Returns: List[Segment]: A line of segments with the desired length. """ line_length = sum(segment.cell_length for segment in line) new_line: List[Segment] if line_length < length: if pad: new_line = line + [cls(" " * (length - line_length), style)] else: new_line = line[:] elif line_length > length: new_line = [] append = new_line.append line_length = 0 for segment in line: segment_length = segment.cell_length if line_length + segment_length < length or segment.control: append(segment) line_length += segment_length else: text, segment_style, _ = segment text = set_cell_size(text, length - line_length) append(cls(text, segment_style)) break else: new_line = line[:] return new_line @classmethod def get_line_length(cls, line: List["Segment"]) -> int: """Get the length of list of segments. Args: line (List[Segment]): A line encoded as a list of Segments (assumes no '\\\\n' characters), Returns: int: The length of the line. """ _cell_len = cell_len return sum(_cell_len(text) for text, style, control in line if not control) @classmethod def get_shape(cls, lines: List[List["Segment"]]) -> Tuple[int, int]: """Get the shape (enclosing rectangle) of a list of lines. Args: lines (List[List[Segment]]): A list of lines (no '\\\\n' characters). Returns: Tuple[int, int]: Width and height in characters. """ get_line_length = cls.get_line_length max_width = max(get_line_length(line) for line in lines) if lines else 0 return (max_width, len(lines)) @classmethod def set_shape( cls, lines: List[List["Segment"]], width: int, height: Optional[int] = None, style: Optional[Style] = None, new_lines: bool = False, ) -> List[List["Segment"]]: """Set the shape of a list of lines (enclosing rectangle). Args: lines (List[List[Segment]]): A list of lines. width (int): Desired width. height (int, optional): Desired height or None for no change. style (Style, optional): Style of any padding added. new_lines (bool, optional): Padded lines should include "\n". Defaults to False. Returns: List[List[Segment]]: New list of lines. """ _height = height or len(lines) blank = ( [cls(" " * width + "\n", style)] if new_lines else [cls(" " * width, style)] ) adjust_line_length = cls.adjust_line_length shaped_lines = lines[:_height] shaped_lines[:] = [ adjust_line_length(line, width, style=style) for line in lines ] if len(shaped_lines) < _height: shaped_lines.extend([blank] * (_height - len(shaped_lines))) return shaped_lines @classmethod def align_top( cls: Type["Segment"], lines: List[List["Segment"]], width: int, height: int, style: Style, new_lines: bool = False, ) -> List[List["Segment"]]: """Aligns lines to top (adds extra lines to bottom as required). Args: lines (List[List[Segment]]): A list of lines. width (int): Desired width. height (int, optional): Desired height or None for no change. style (Style): Style of any padding added. new_lines (bool, optional): Padded lines should include "\n". Defaults to False. Returns: List[List[Segment]]: New list of lines. """ extra_lines = height - len(lines) if not extra_lines: return lines[:] lines = lines[:height] blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style) lines = lines + [[blank]] * extra_lines return lines @classmethod def align_bottom( cls: Type["Segment"], lines: List[List["Segment"]], width: int, height: int, style: Style, new_lines: bool = False, ) -> List[List["Segment"]]: """Aligns render to bottom (adds extra lines above as required). Args: lines (List[List[Segment]]): A list of lines. width (int): Desired width. height (int, optional): Desired height or None for no change. style (Style): Style of any padding added. Defaults to None. new_lines (bool, optional): Padded lines should include "\n". Defaults to False. Returns: List[List[Segment]]: New list of lines. """ extra_lines = height - len(lines) if not extra_lines: return lines[:] lines = lines[:height] blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style) lines = [[blank]] * extra_lines + lines return lines @classmethod def align_middle( cls: Type["Segment"], lines: List[List["Segment"]], width: int, height: int, style: Style, new_lines: bool = False, ) -> List[List["Segment"]]: """Aligns lines to middle (adds extra lines to above and below as required). Args: lines (List[List[Segment]]): A list of lines. width (int): Desired width. height (int, optional): Desired height or None for no change. style (Style): Style of any padding added. new_lines (bool, optional): Padded lines should include "\n". Defaults to False. Returns: List[List[Segment]]: New list of lines. """ extra_lines = height - len(lines) if not extra_lines: return lines[:] lines = lines[:height] blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style) top_lines = extra_lines // 2 bottom_lines = extra_lines - top_lines lines = [[blank]] * top_lines + lines + [[blank]] * bottom_lines return lines @classmethod def simplify(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]: """Simplify an iterable of segments by combining contiguous segments with the same style. Args: segments (Iterable[Segment]): An iterable of segments. Returns: Iterable[Segment]: A possibly smaller iterable of segments that will render the same way. """ iter_segments = iter(segments) try: last_segment = next(iter_segments) except StopIteration: return _Segment = Segment for segment in iter_segments: if last_segment.style == segment.style and not segment.control: last_segment = _Segment( last_segment.text + segment.text, last_segment.style ) else: yield last_segment last_segment = segment yield last_segment @classmethod def strip_links(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]: """Remove all links from an iterable of styles. Args: segments (Iterable[Segment]): An iterable segments. Yields: Segment: Segments with link removed. """ for segment in segments: if segment.control or segment.style is None: yield segment else: text, style, _control = segment yield cls(text, style.update_link(None) if style else None) @classmethod def strip_styles(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]: """Remove all styles from an iterable of segments. Args: segments (Iterable[Segment]): An iterable segments. Yields: Segment: Segments with styles replace with None """ for text, _style, control in segments: yield cls(text, None, control) @classmethod def remove_color(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]: """Remove all color from an iterable of segments. Args: segments (Iterable[Segment]): An iterable segments. Yields: Segment: Segments with colorless style. """ cache: Dict[Style, Style] = {} for text, style, control in segments: if style: colorless_style = cache.get(style) if colorless_style is None: colorless_style = style.without_color cache[style] = colorless_style yield cls(text, colorless_style, control) else: yield cls(text, None, control) @classmethod def divide( cls, segments: Iterable["Segment"], cuts: Iterable[int] ) -> Iterable[List["Segment"]]: """Divides an iterable of segments in to portions. Args: cuts (Iterable[int]): Cell positions where to divide. Yields: [Iterable[List[Segment]]]: An iterable of Segments in List. """ split_segments: List["Segment"] = [] add_segment = split_segments.append iter_cuts = iter(cuts) while True: cut = next(iter_cuts, -1) if cut == -1: return if cut != 0: break yield [] pos = 0 segments_clear = split_segments.clear segments_copy = split_segments.copy _cell_len = cached_cell_len for segment in segments: text, _style, control = segment while text: end_pos = pos if control else pos + _cell_len(text) if end_pos < cut: add_segment(segment) pos = end_pos break if end_pos == cut: add_segment(segment) yield segments_copy() segments_clear() pos = end_pos cut = next(iter_cuts, -1) if cut == -1: if split_segments: yield segments_copy() return break else: before, segment = segment.split_cells(cut - pos) text, _style, control = segment add_segment(before) yield segments_copy() segments_clear() pos = cut cut = next(iter_cuts, -1) if cut == -1: if split_segments: yield segments_copy() return yield segments_copy() class Segments: """A simple renderable to render an iterable of segments. This class may be useful if you want to print segments outside of a __rich_console__ method. Args: segments (Iterable[Segment]): An iterable of segments. new_lines (bool, optional): Add new lines between segments. Defaults to False. """ def __init__(self, segments: Iterable[Segment], new_lines: bool = False) -> None: self.segments = list(segments) self.new_lines = new_lines def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": if self.new_lines: line = Segment.line() for segment in self.segments: yield segment yield line else: yield from self.segments class SegmentLines: def __init__(self, lines: Iterable[List[Segment]], new_lines: bool = False) -> None: """A simple renderable containing a number of lines of segments. May be used as an intermediate in rendering process. Args: lines (Iterable[List[Segment]]): Lists of segments forming lines. new_lines (bool, optional): Insert new lines after each line. Defaults to False. """ self.lines = list(lines) self.new_lines = new_lines def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": if self.new_lines: new_line = Segment.line() for line in self.lines: yield from line yield new_line else: for line in self.lines: yield from line if __name__ == "__main__": # pragma: no cover from rich.console import Console from rich.syntax import Syntax from rich.text import Text code = """from rich.console import Console console = Console() text = Text.from_markup("Hello, [bold magenta]World[/]!") console.print(text)""" text = Text.from_markup("Hello, [bold magenta]World[/]!") console = Console() console.rule("rich.Segment") console.print( "A Segment is the last step in the Rich render process before generating text with ANSI codes." ) console.print("\nConsider the following code:\n") console.print(Syntax(code, "python", line_numbers=True)) console.print() console.print( "When you call [b]print()[/b], Rich [i]renders[/i] the object in to the following:\n" ) fragments = list(console.render(text)) console.print(fragments) console.print() console.print("The Segments are then processed to produce the following output:\n") console.print(text) console.print( "\nYou will only need to know this if you are implementing your own Rich renderables." )
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/tree.py
rich/tree.py
from typing import Iterator, List, Optional, Tuple from ._loop import loop_first, loop_last from .console import Console, ConsoleOptions, RenderableType, RenderResult from .jupyter import JupyterMixin from .measure import Measurement from .segment import Segment from .style import Style, StyleStack, StyleType from .styled import Styled GuideType = Tuple[str, str, str, str] class Tree(JupyterMixin): """A renderable for a tree structure. Attributes: ASCII_GUIDES (GuideType): Guide lines used when Console.ascii_only is True. TREE_GUIDES (List[GuideType, GuideType, GuideType]): Default guide lines. Args: label (RenderableType): The renderable or str for the tree label. style (StyleType, optional): Style of this tree. Defaults to "tree". guide_style (StyleType, optional): Style of the guide lines. Defaults to "tree.line". expanded (bool, optional): Also display children. Defaults to True. highlight (bool, optional): Highlight renderable (if str). Defaults to False. hide_root (bool, optional): Hide the root node. Defaults to False. """ ASCII_GUIDES = (" ", "| ", "+-- ", "`-- ") TREE_GUIDES = [ (" ", "│ ", "├── ", "└── "), (" ", "┃ ", "┣━━ ", "┗━━ "), (" ", "║ ", "╠══ ", "╚══ "), ] def __init__( self, label: RenderableType, *, style: StyleType = "tree", guide_style: StyleType = "tree.line", expanded: bool = True, highlight: bool = False, hide_root: bool = False, ) -> None: self.label = label self.style = style self.guide_style = guide_style self.children: List[Tree] = [] self.expanded = expanded self.highlight = highlight self.hide_root = hide_root def add( self, label: RenderableType, *, style: Optional[StyleType] = None, guide_style: Optional[StyleType] = None, expanded: bool = True, highlight: Optional[bool] = False, ) -> "Tree": """Add a child tree. Args: label (RenderableType): The renderable or str for the tree label. style (StyleType, optional): Style of this tree. Defaults to "tree". guide_style (StyleType, optional): Style of the guide lines. Defaults to "tree.line". expanded (bool, optional): Also display children. Defaults to True. highlight (Optional[bool], optional): Highlight renderable (if str). Defaults to False. Returns: Tree: A new child Tree, which may be further modified. """ node = Tree( label, style=self.style if style is None else style, guide_style=self.guide_style if guide_style is None else guide_style, expanded=expanded, highlight=self.highlight if highlight is None else highlight, ) self.children.append(node) return node def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": stack: List[Iterator[Tuple[bool, Tree]]] = [] pop = stack.pop push = stack.append new_line = Segment.line() get_style = console.get_style null_style = Style.null() guide_style = get_style(self.guide_style, default="") or null_style SPACE, CONTINUE, FORK, END = range(4) _Segment = Segment def make_guide(index: int, style: Style) -> Segment: """Make a Segment for a level of the guide lines.""" if options.ascii_only: line = self.ASCII_GUIDES[index] else: guide = 1 if style.bold else (2 if style.underline2 else 0) line = self.TREE_GUIDES[0 if options.legacy_windows else guide][index] return _Segment(line, style) levels: List[Segment] = [make_guide(CONTINUE, guide_style)] push(iter(loop_last([self]))) guide_style_stack = StyleStack(get_style(self.guide_style)) style_stack = StyleStack(get_style(self.style)) remove_guide_styles = Style(bold=False, underline2=False) depth = 0 while stack: stack_node = pop() try: last, node = next(stack_node) except StopIteration: levels.pop() if levels: guide_style = levels[-1].style or null_style levels[-1] = make_guide(FORK, guide_style) guide_style_stack.pop() style_stack.pop() continue push(stack_node) if last: levels[-1] = make_guide(END, levels[-1].style or null_style) guide_style = guide_style_stack.current + get_style(node.guide_style) style = style_stack.current + get_style(node.style) prefix = levels[(2 if self.hide_root else 1) :] renderable_lines = console.render_lines( Styled(node.label, style), options.update( width=options.max_width - sum(level.cell_length for level in prefix), highlight=self.highlight, height=None, ), pad=options.justify is not None, ) if not (depth == 0 and self.hide_root): for first, line in loop_first(renderable_lines): if prefix: yield from _Segment.apply_style( prefix, style.background_style, post_style=remove_guide_styles, ) yield from line yield new_line if first and prefix: prefix[-1] = make_guide( SPACE if last else CONTINUE, prefix[-1].style or null_style ) if node.expanded and node.children: levels[-1] = make_guide( SPACE if last else CONTINUE, levels[-1].style or null_style ) levels.append( make_guide(END if len(node.children) == 1 else FORK, guide_style) ) style_stack.push(get_style(node.style)) guide_style_stack.push(get_style(node.guide_style)) push(iter(loop_last(node.children))) depth += 1 def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> "Measurement": stack: List[Iterator[Tree]] = [iter([self])] pop = stack.pop push = stack.append minimum = 0 maximum = 0 measure = Measurement.get level = 0 while stack: iter_tree = pop() try: tree = next(iter_tree) except StopIteration: level -= 1 continue push(iter_tree) min_measure, max_measure = measure(console, options, tree.label) indent = level * 4 minimum = max(min_measure + indent, minimum) maximum = max(max_measure + indent, maximum) if tree.expanded and tree.children: push(iter(tree.children)) level += 1 return Measurement(minimum, maximum) if __name__ == "__main__": # pragma: no cover from rich.console import Group from rich.markdown import Markdown from rich.panel import Panel from rich.syntax import Syntax from rich.table import Table table = Table(row_styles=["", "dim"]) table.add_column("Released", style="cyan", no_wrap=True) table.add_column("Title", style="magenta") table.add_column("Box Office", justify="right", style="green") table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690") table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347") table.add_row("Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi", "$1,332,539,889") table.add_row("Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889") code = """\ class Segment(NamedTuple): text: str = "" style: Optional[Style] = None is_control: bool = False """ syntax = Syntax(code, "python", theme="monokai", line_numbers=True) markdown = Markdown( """\ ### example.md > Hello, World! > > Markdown _all_ the things """ ) root = Tree("🌲 [b green]Rich Tree", highlight=True, hide_root=True) node = root.add(":file_folder: Renderables", guide_style="red") simple_node = node.add(":file_folder: [bold yellow]Atomic", guide_style="uu green") simple_node.add(Group("📄 Syntax", syntax)) simple_node.add(Group("📄 Markdown", Panel(markdown, border_style="green"))) containers_node = node.add( ":file_folder: [bold magenta]Containers", guide_style="bold magenta" ) containers_node.expanded = True panel = Panel.fit("Just a panel", border_style="red") containers_node.add(Group("📄 Panels", panel)) containers_node.add(Group("📄 [b magenta]Table", table)) console = Console() console.print(root)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_export_format.py
rich/_export_format.py
CONSOLE_HTML_FORMAT = """\ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> {stylesheet} body {{ color: {foreground}; background-color: {background}; }} </style> </head> <body> <pre style="font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><code style="font-family:inherit">{code}</code></pre> </body> </html> """ CONSOLE_SVG_FORMAT = """\ <svg class="rich-terminal" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg"> <!-- Generated with Rich https://www.textualize.io --> <style> @font-face {{ font-family: "Fira Code"; src: local("FiraCode-Regular"), url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"), url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff"); font-style: normal; font-weight: 400; }} @font-face {{ font-family: "Fira Code"; src: local("FiraCode-Bold"), url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"), url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff"); font-style: bold; font-weight: 700; }} .{unique_id}-matrix {{ font-family: Fira Code, monospace; font-size: {char_height}px; line-height: {line_height}px; font-variant-east-asian: full-width; }} .{unique_id}-title {{ font-size: 18px; font-weight: bold; font-family: arial; }} {styles} </style> <defs> <clipPath id="{unique_id}-clip-terminal"> <rect x="0" y="0" width="{terminal_width}" height="{terminal_height}" /> </clipPath> {lines} </defs> {chrome} <g transform="translate({terminal_x}, {terminal_y})" clip-path="url(#{unique_id}-clip-terminal)"> {backgrounds} <g class="{unique_id}-matrix"> {matrix} </g> </g> </svg> """ _SVG_FONT_FAMILY = "Rich Fira Code" _SVG_CLASSES_PREFIX = "rich-svg"
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/themes.py
rich/themes.py
from .default_styles import DEFAULT_STYLES from .theme import Theme DEFAULT = Theme(DEFAULT_STYLES)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/markdown.py
rich/markdown.py
from __future__ import annotations import sys from typing import ClassVar, Iterable, get_args from markdown_it import MarkdownIt from markdown_it.token import Token from rich.table import Table from . import box from ._loop import loop_first from ._stack import Stack from .console import Console, ConsoleOptions, JustifyMethod, RenderResult from .containers import Renderables from .jupyter import JupyterMixin from .panel import Panel from .rule import Rule from .segment import Segment from .style import Style, StyleStack from .syntax import Syntax from .text import Text, TextType class MarkdownElement: new_line: ClassVar[bool] = True @classmethod def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: """Factory to create markdown element, Args: markdown (Markdown): The parent Markdown object. token (Token): A node from markdown-it. Returns: MarkdownElement: A new markdown element """ return cls() def on_enter(self, context: MarkdownContext) -> None: """Called when the node is entered. Args: context (MarkdownContext): The markdown context. """ def on_text(self, context: MarkdownContext, text: TextType) -> None: """Called when text is parsed. Args: context (MarkdownContext): The markdown context. """ def on_leave(self, context: MarkdownContext) -> None: """Called when the parser leaves the element. Args: context (MarkdownContext): [description] """ def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: """Called when a child element is closed. This method allows a parent element to take over rendering of its children. Args: context (MarkdownContext): The markdown context. child (MarkdownElement): The child markdown element. Returns: bool: Return True to render the element, or False to not render the element. """ return True def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: return () class UnknownElement(MarkdownElement): """An unknown element. Hopefully there will be no unknown elements, and we will have a MarkdownElement for everything in the document. """ class TextElement(MarkdownElement): """Base class for elements that render text.""" style_name = "none" def on_enter(self, context: MarkdownContext) -> None: self.style = context.enter_style(self.style_name) self.text = Text(justify="left") def on_text(self, context: MarkdownContext, text: TextType) -> None: self.text.append(text, context.current_style if isinstance(text, str) else None) def on_leave(self, context: MarkdownContext) -> None: context.leave_style() class Paragraph(TextElement): """A Paragraph.""" style_name = "markdown.paragraph" justify: JustifyMethod @classmethod def create(cls, markdown: Markdown, token: Token) -> Paragraph: return cls(justify=markdown.justify or "left") def __init__(self, justify: JustifyMethod) -> None: self.justify = justify def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: self.text.justify = self.justify yield self.text class Heading(TextElement): """A heading.""" @classmethod def create(cls, markdown: Markdown, token: Token) -> Heading: return cls(token.tag) def on_enter(self, context: MarkdownContext) -> None: self.text = Text() context.enter_style(self.style_name) def __init__(self, tag: str) -> None: self.tag = tag self.style_name = f"markdown.{tag}" super().__init__() def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: text = self.text text.justify = "center" if self.tag == "h1": # Draw a border around h1s yield Panel( text, box=box.HEAVY, style="markdown.h1.border", ) else: # Styled text for h2 and beyond if self.tag == "h2": yield Text("") yield text class CodeBlock(TextElement): """A code block with syntax highlighting.""" style_name = "markdown.code_block" @classmethod def create(cls, markdown: Markdown, token: Token) -> CodeBlock: node_info = token.info or "" lexer_name = node_info.partition(" ")[0] return cls(lexer_name or "text", markdown.code_theme) def __init__(self, lexer_name: str, theme: str) -> None: self.lexer_name = lexer_name self.theme = theme def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: code = str(self.text).rstrip() syntax = Syntax( code, self.lexer_name, theme=self.theme, word_wrap=True, padding=1 ) yield syntax class BlockQuote(TextElement): """A block quote.""" style_name = "markdown.block_quote" def __init__(self) -> None: self.elements: Renderables = Renderables() def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: self.elements.append(child) return False def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: render_options = options.update(width=options.max_width - 4) lines = console.render_lines(self.elements, render_options, style=self.style) style = self.style new_line = Segment("\n") padding = Segment("▌ ", style) for line in lines: yield padding yield from line yield new_line class HorizontalRule(MarkdownElement): """A horizontal rule to divide sections.""" new_line = False def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: style = console.get_style("markdown.hr", default="none") yield Rule(style=style) class TableElement(MarkdownElement): """MarkdownElement corresponding to `table_open`.""" def __init__(self) -> None: self.header: TableHeaderElement | None = None self.body: TableBodyElement | None = None def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: if isinstance(child, TableHeaderElement): self.header = child elif isinstance(child, TableBodyElement): self.body = child else: raise RuntimeError("Couldn't process markdown table.") return False def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: table = Table(box=box.SIMPLE_HEAVY) if self.header is not None and self.header.row is not None: for column in self.header.row.cells: table.add_column(column.content) if self.body is not None: for row in self.body.rows: row_content = [element.content for element in row.cells] table.add_row(*row_content) yield table class TableHeaderElement(MarkdownElement): """MarkdownElement corresponding to `thead_open` and `thead_close`.""" def __init__(self) -> None: self.row: TableRowElement | None = None def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, TableRowElement) self.row = child return False class TableBodyElement(MarkdownElement): """MarkdownElement corresponding to `tbody_open` and `tbody_close`.""" def __init__(self) -> None: self.rows: list[TableRowElement] = [] def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, TableRowElement) self.rows.append(child) return False class TableRowElement(MarkdownElement): """MarkdownElement corresponding to `tr_open` and `tr_close`.""" def __init__(self) -> None: self.cells: list[TableDataElement] = [] def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, TableDataElement) self.cells.append(child) return False class TableDataElement(MarkdownElement): """MarkdownElement corresponding to `td_open` and `td_close` and `th_open` and `th_close`.""" @classmethod def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: style = str(token.attrs.get("style")) or "" justify: JustifyMethod if "text-align:right" in style: justify = "right" elif "text-align:center" in style: justify = "center" elif "text-align:left" in style: justify = "left" else: justify = "default" assert justify in get_args(JustifyMethod) return cls(justify=justify) def __init__(self, justify: JustifyMethod) -> None: self.content: Text = Text("", justify=justify) self.justify = justify def on_text(self, context: MarkdownContext, text: TextType) -> None: text = Text(text) if isinstance(text, str) else text text.stylize(context.current_style) self.content.append_text(text) class ListElement(MarkdownElement): """A list element.""" @classmethod def create(cls, markdown: Markdown, token: Token) -> ListElement: return cls(token.type, int(token.attrs.get("start", 1))) def __init__(self, list_type: str, list_start: int | None) -> None: self.items: list[ListItem] = [] self.list_type = list_type self.list_start = list_start def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, ListItem) self.items.append(child) return False def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: if self.list_type == "bullet_list_open": for item in self.items: yield from item.render_bullet(console, options) else: number = 1 if self.list_start is None else self.list_start last_number = number + len(self.items) for index, item in enumerate(self.items): yield from item.render_number( console, options, number + index, last_number ) class ListItem(TextElement): """An item in a list.""" style_name = "markdown.item" def __init__(self) -> None: self.elements: Renderables = Renderables() def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: self.elements.append(child) return False def render_bullet(self, console: Console, options: ConsoleOptions) -> RenderResult: render_options = options.update(width=options.max_width - 3) lines = console.render_lines(self.elements, render_options, style=self.style) bullet_style = console.get_style("markdown.item.bullet", default="none") bullet = Segment(" • ", bullet_style) padding = Segment(" " * 3, bullet_style) new_line = Segment("\n") for first, line in loop_first(lines): yield bullet if first else padding yield from line yield new_line def render_number( self, console: Console, options: ConsoleOptions, number: int, last_number: int ) -> RenderResult: number_width = len(str(last_number)) + 2 render_options = options.update(width=options.max_width - number_width) lines = console.render_lines(self.elements, render_options, style=self.style) number_style = console.get_style("markdown.item.number", default="none") new_line = Segment("\n") padding = Segment(" " * number_width, number_style) numeral = Segment(f"{number}".rjust(number_width - 1) + " ", number_style) for first, line in loop_first(lines): yield numeral if first else padding yield from line yield new_line class Link(TextElement): @classmethod def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: url = token.attrs.get("href", "#") return cls(token.content, str(url)) def __init__(self, text: str, href: str): self.text = Text(text) self.href = href class ImageItem(TextElement): """Renders a placeholder for an image.""" new_line = False @classmethod def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: """Factory to create markdown element, Args: markdown (Markdown): The parent Markdown object. token (Any): A token from markdown-it. Returns: MarkdownElement: A new markdown element """ return cls(str(token.attrs.get("src", "")), markdown.hyperlinks) def __init__(self, destination: str, hyperlinks: bool) -> None: self.destination = destination self.hyperlinks = hyperlinks self.link: str | None = None super().__init__() def on_enter(self, context: MarkdownContext) -> None: self.link = context.current_style.link self.text = Text(justify="left") super().on_enter(context) def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: link_style = Style(link=self.link or self.destination or None) title = self.text or Text(self.destination.strip("/").rsplit("/", 1)[-1]) if self.hyperlinks: title.stylize(link_style) text = Text.assemble("🌆 ", title, " ", end="") yield text class MarkdownContext: """Manages the console render state.""" def __init__( self, console: Console, options: ConsoleOptions, style: Style, inline_code_lexer: str | None = None, inline_code_theme: str = "monokai", ) -> None: self.console = console self.options = options self.style_stack: StyleStack = StyleStack(style) self.stack: Stack[MarkdownElement] = Stack() self._syntax: Syntax | None = None if inline_code_lexer is not None: self._syntax = Syntax("", inline_code_lexer, theme=inline_code_theme) @property def current_style(self) -> Style: """Current style which is the product of all styles on the stack.""" return self.style_stack.current def on_text(self, text: str, node_type: str) -> None: """Called when the parser visits text.""" if node_type in {"fence", "code_inline"} and self._syntax is not None: highlight_text = self._syntax.highlight(text) highlight_text.rstrip() self.stack.top.on_text( self, Text.assemble(highlight_text, style=self.style_stack.current) ) else: self.stack.top.on_text(self, text) def enter_style(self, style_name: str | Style) -> Style: """Enter a style context.""" style = self.console.get_style(style_name, default="none") self.style_stack.push(style) return self.current_style def leave_style(self) -> Style: """Leave a style context.""" style = self.style_stack.pop() return style class Markdown(JupyterMixin): """A Markdown renderable. Args: markup (str): A string containing markdown. code_theme (str, optional): Pygments theme for code blocks. Defaults to "monokai". See https://pygments.org/styles/ for code themes. justify (JustifyMethod, optional): Justify value for paragraphs. Defaults to None. style (Union[str, Style], optional): Optional style to apply to markdown. hyperlinks (bool, optional): Enable hyperlinks. Defaults to ``True``. inline_code_lexer: (str, optional): Lexer to use if inline code highlighting is enabled. Defaults to None. inline_code_theme: (Optional[str], optional): Pygments theme for inline code highlighting, or None for no highlighting. Defaults to None. """ elements: ClassVar[dict[str, type[MarkdownElement]]] = { "paragraph_open": Paragraph, "heading_open": Heading, "fence": CodeBlock, "code_block": CodeBlock, "blockquote_open": BlockQuote, "hr": HorizontalRule, "bullet_list_open": ListElement, "ordered_list_open": ListElement, "list_item_open": ListItem, "image": ImageItem, "table_open": TableElement, "tbody_open": TableBodyElement, "thead_open": TableHeaderElement, "tr_open": TableRowElement, "td_open": TableDataElement, "th_open": TableDataElement, } inlines = {"em", "strong", "code", "s"} def __init__( self, markup: str, code_theme: str = "monokai", justify: JustifyMethod | None = None, style: str | Style = "none", hyperlinks: bool = True, inline_code_lexer: str | None = None, inline_code_theme: str | None = None, ) -> None: parser = MarkdownIt().enable("strikethrough").enable("table") self.markup = markup self.parsed = parser.parse(markup) self.code_theme = code_theme self.justify: JustifyMethod | None = justify self.style = style self.hyperlinks = hyperlinks self.inline_code_lexer = inline_code_lexer self.inline_code_theme = inline_code_theme or code_theme def _flatten_tokens(self, tokens: Iterable[Token]) -> Iterable[Token]: """Flattens the token stream.""" for token in tokens: is_fence = token.type == "fence" is_image = token.tag == "img" if token.children and not (is_image or is_fence): yield from self._flatten_tokens(token.children) else: yield token def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: """Render markdown to the console.""" style = console.get_style(self.style, default="none") options = options.update(height=None) context = MarkdownContext( console, options, style, inline_code_lexer=self.inline_code_lexer, inline_code_theme=self.inline_code_theme, ) tokens = self.parsed inline_style_tags = self.inlines new_line = False _new_line_segment = Segment.line() for token in self._flatten_tokens(tokens): node_type = token.type tag = token.tag entering = token.nesting == 1 exiting = token.nesting == -1 self_closing = token.nesting == 0 if node_type == "text": context.on_text(token.content, node_type) elif node_type == "hardbreak": context.on_text("\n", node_type) elif node_type == "softbreak": context.on_text(" ", node_type) elif node_type == "link_open": href = str(token.attrs.get("href", "")) if self.hyperlinks: link_style = console.get_style("markdown.link_url", default="none") link_style += Style(link=href) context.enter_style(link_style) else: context.stack.push(Link.create(self, token)) elif node_type == "link_close": if self.hyperlinks: context.leave_style() else: element = context.stack.pop() assert isinstance(element, Link) link_style = console.get_style("markdown.link", default="none") context.enter_style(link_style) context.on_text(element.text.plain, node_type) context.leave_style() context.on_text(" (", node_type) link_url_style = console.get_style( "markdown.link_url", default="none" ) context.enter_style(link_url_style) context.on_text(element.href, node_type) context.leave_style() context.on_text(")", node_type) elif ( tag in inline_style_tags and node_type != "fence" and node_type != "code_block" ): if entering: # If it's an opening inline token e.g. strong, em, etc. # Then we move into a style context i.e. push to stack. context.enter_style(f"markdown.{tag}") elif exiting: # If it's a closing inline style, then we pop the style # off of the stack, to move out of the context of it... context.leave_style() else: # If it's a self-closing inline style e.g. `code_inline` context.enter_style(f"markdown.{tag}") if token.content: context.on_text(token.content, node_type) context.leave_style() else: # Map the markdown tag -> MarkdownElement renderable element_class = self.elements.get(token.type) or UnknownElement element = element_class.create(self, token) if entering or self_closing: context.stack.push(element) element.on_enter(context) if exiting: # CLOSING tag element = context.stack.pop() should_render = not context.stack or ( context.stack and context.stack.top.on_child_close(context, element) ) if should_render: if new_line: yield _new_line_segment yield from console.render(element, context.options) elif self_closing: # SELF-CLOSING tags (e.g. text, code, image) context.stack.pop() text = token.content if text is not None: element.on_text(context, text) should_render = ( not context.stack or context.stack and context.stack.top.on_child_close(context, element) ) if should_render: if new_line and node_type != "inline": yield _new_line_segment yield from console.render(element, context.options) if exiting or self_closing: element.on_leave(context) new_line = element.new_line if __name__ == "__main__": # pragma: no cover import argparse import sys parser = argparse.ArgumentParser( description="Render Markdown to the console with Rich" ) parser.add_argument( "path", metavar="PATH", help="path to markdown file, or - for stdin", ) parser.add_argument( "-c", "--force-color", dest="force_color", action="store_true", default=None, help="force color for non-terminals", ) parser.add_argument( "-t", "--code-theme", dest="code_theme", default="monokai", help="pygments code theme", ) parser.add_argument( "-i", "--inline-code-lexer", dest="inline_code_lexer", default=None, help="inline_code_lexer", ) parser.add_argument( "-y", "--hyperlinks", dest="hyperlinks", action="store_true", help="enable hyperlinks", ) parser.add_argument( "-w", "--width", type=int, dest="width", default=None, help="width of output (default will auto-detect)", ) parser.add_argument( "-j", "--justify", dest="justify", action="store_true", help="enable full text justify", ) parser.add_argument( "-p", "--page", dest="page", action="store_true", help="use pager to scroll output", ) args = parser.parse_args() from rich.console import Console if args.path == "-": markdown_body = sys.stdin.read() else: with open(args.path, encoding="utf-8") as markdown_file: markdown_body = markdown_file.read() markdown = Markdown( markdown_body, justify="full" if args.justify else "left", code_theme=args.code_theme, hyperlinks=args.hyperlinks, inline_code_lexer=args.inline_code_lexer, ) if args.page: import io import pydoc fileio = io.StringIO() console = Console( file=fileio, force_terminal=args.force_color, width=args.width ) console.print(markdown) pydoc.pager(fileio.getvalue()) else: console = Console( force_terminal=args.force_color, width=args.width, record=True ) console.print(markdown)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_windows.py
rich/_windows.py
import sys from dataclasses import dataclass @dataclass class WindowsConsoleFeatures: """Windows features available.""" vt: bool = False """The console supports VT codes.""" truecolor: bool = False """The console supports truecolor.""" try: import ctypes from ctypes import LibraryLoader if sys.platform == "win32": windll = LibraryLoader(ctypes.WinDLL) else: windll = None raise ImportError("Not windows") from rich._win32_console import ( ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, LegacyWindowsError, ) except (AttributeError, ImportError, ValueError): # Fallback if we can't load the Windows DLL def get_windows_console_features() -> WindowsConsoleFeatures: features = WindowsConsoleFeatures() return features else: def get_windows_console_features() -> WindowsConsoleFeatures: """Get windows console features. Returns: WindowsConsoleFeatures: An instance of WindowsConsoleFeatures. """ handle = GetStdHandle() try: console_mode = GetConsoleMode(handle) success = True except LegacyWindowsError: console_mode = 0 success = False vt = bool(success and console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) truecolor = False if vt: win_version = sys.getwindowsversion() truecolor = win_version.major > 10 or ( win_version.major == 10 and win_version.build >= 15063 ) features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor) return features if __name__ == "__main__": import platform features = get_windows_console_features() from rich import print print(f'platform="{platform.system()}"') print(repr(features))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_ratio.py
rich/_ratio.py
from fractions import Fraction from math import ceil from typing import cast, List, Optional, Sequence, Protocol class Edge(Protocol): """Any object that defines an edge (such as Layout).""" size: Optional[int] = None ratio: int = 1 minimum_size: int = 1 def ratio_resolve(total: int, edges: Sequence[Edge]) -> List[int]: """Divide total space to satisfy size, ratio, and minimum_size, constraints. The returned list of integers should add up to total in most cases, unless it is impossible to satisfy all the constraints. For instance, if there are two edges with a minimum size of 20 each and `total` is 30 then the returned list will be greater than total. In practice, this would mean that a Layout object would clip the rows that would overflow the screen height. Args: total (int): Total number of characters. edges (List[Edge]): Edges within total space. Returns: List[int]: Number of characters for each edge. """ # Size of edge or None for yet to be determined sizes = [(edge.size or None) for edge in edges] _Fraction = Fraction # While any edges haven't been calculated while None in sizes: # Get flexible edges and index to map these back on to sizes list flexible_edges = [ (index, edge) for index, (size, edge) in enumerate(zip(sizes, edges)) if size is None ] # Remaining space in total remaining = total - sum(size or 0 for size in sizes) if remaining <= 0: # No room for flexible edges return [ ((edge.minimum_size or 1) if size is None else size) for size, edge in zip(sizes, edges) ] # Calculate number of characters in a ratio portion portion = _Fraction( remaining, sum((edge.ratio or 1) for _, edge in flexible_edges) ) # If any edges will be less than their minimum, replace size with the minimum for index, edge in flexible_edges: if portion * edge.ratio <= edge.minimum_size: sizes[index] = edge.minimum_size # New fixed size will invalidate calculations, so we need to repeat the process break else: # Distribute flexible space and compensate for rounding error # Since edge sizes can only be integers we need to add the remainder # to the following line remainder = _Fraction(0) for index, edge in flexible_edges: size, remainder = divmod(portion * edge.ratio + remainder, 1) sizes[index] = size break # Sizes now contains integers only return cast(List[int], sizes) def ratio_reduce( total: int, ratios: List[int], maximums: List[int], values: List[int] ) -> List[int]: """Divide an integer total in to parts based on ratios. Args: total (int): The total to divide. ratios (List[int]): A list of integer ratios. maximums (List[int]): List of maximums values for each slot. values (List[int]): List of values Returns: List[int]: A list of integers guaranteed to sum to total. """ ratios = [ratio if _max else 0 for ratio, _max in zip(ratios, maximums)] total_ratio = sum(ratios) if not total_ratio: return values[:] total_remaining = total result: List[int] = [] append = result.append for ratio, maximum, value in zip(ratios, maximums, values): if ratio and total_ratio > 0: distributed = min(maximum, round(ratio * total_remaining / total_ratio)) append(value - distributed) total_remaining -= distributed total_ratio -= ratio else: append(value) return result def ratio_distribute( total: int, ratios: List[int], minimums: Optional[List[int]] = None ) -> List[int]: """Distribute an integer total in to parts based on ratios. Args: total (int): The total to divide. ratios (List[int]): A list of integer ratios. minimums (List[int]): List of minimum values for each slot. Returns: List[int]: A list of integers guaranteed to sum to total. """ if minimums: ratios = [ratio if _min else 0 for ratio, _min in zip(ratios, minimums)] total_ratio = sum(ratios) assert total_ratio > 0, "Sum of ratios must be > 0" total_remaining = total distributed_total: List[int] = [] append = distributed_total.append if minimums is None: _minimums = [0] * len(ratios) else: _minimums = minimums for ratio, minimum in zip(ratios, _minimums): if total_ratio > 0: distributed = max(minimum, ceil(ratio * total_remaining / total_ratio)) else: distributed = total_remaining append(distributed) total_ratio -= ratio total_remaining -= distributed return distributed_total if __name__ == "__main__": from dataclasses import dataclass @dataclass class E: size: Optional[int] = None ratio: int = 1 minimum_size: int = 1 resolved = ratio_resolve(110, [E(None, 1, 1), E(None, 1, 1), E(None, 1, 1)]) print(sum(resolved))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/bar.py
rich/bar.py
from typing import Optional, Union from .color import Color from .console import Console, ConsoleOptions, RenderResult from .jupyter import JupyterMixin from .measure import Measurement from .segment import Segment from .style import Style # There are left-aligned characters for 1/8 to 7/8, but # the right-aligned characters exist only for 1/8 and 4/8. BEGIN_BLOCK_ELEMENTS = ["█", "█", "█", "▐", "▐", "▐", "▕", "▕"] END_BLOCK_ELEMENTS = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"] FULL_BLOCK = "█" class Bar(JupyterMixin): """Renders a solid block bar. Args: size (float): Value for the end of the bar. begin (float): Begin point (between 0 and size, inclusive). end (float): End point (between 0 and size, inclusive). width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None. color (Union[Color, str], optional): Color of the bar. Defaults to "default". bgcolor (Union[Color, str], optional): Color of bar background. Defaults to "default". """ def __init__( self, size: float, begin: float, end: float, *, width: Optional[int] = None, color: Union[Color, str] = "default", bgcolor: Union[Color, str] = "default", ): self.size = size self.begin = max(begin, 0) self.end = min(end, size) self.width = width self.style = Style(color=color, bgcolor=bgcolor) def __repr__(self) -> str: return f"Bar({self.size}, {self.begin}, {self.end})" def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: width = min( self.width if self.width is not None else options.max_width, options.max_width, ) if self.begin >= self.end: yield Segment(" " * width, self.style) yield Segment.line() return prefix_complete_eights = int(width * 8 * self.begin / self.size) prefix_bar_count = prefix_complete_eights // 8 prefix_eights_count = prefix_complete_eights % 8 body_complete_eights = int(width * 8 * self.end / self.size) body_bar_count = body_complete_eights // 8 body_eights_count = body_complete_eights % 8 # When start and end fall into the same cell, we ideally should render # a symbol that's "center-aligned", but there is no good symbol in Unicode. # In this case, we fall back to right-aligned block symbol for simplicity. prefix = " " * prefix_bar_count if prefix_eights_count: prefix += BEGIN_BLOCK_ELEMENTS[prefix_eights_count] body = FULL_BLOCK * body_bar_count if body_eights_count: body += END_BLOCK_ELEMENTS[body_eights_count] suffix = " " * (width - len(body)) yield Segment(prefix + body[len(prefix) :] + suffix, self.style) yield Segment.line() def __rich_measure__( self, console: Console, options: ConsoleOptions ) -> Measurement: return ( Measurement(self.width, self.width) if self.width is not None else Measurement(4, options.max_width) )
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/live.py
rich/live.py
from __future__ import annotations import sys from threading import Event, RLock, Thread from types import TracebackType from typing import IO, TYPE_CHECKING, Any, Callable, List, Optional, TextIO, Type, cast from . import get_console from .console import Console, ConsoleRenderable, Group, RenderableType, RenderHook from .control import Control from .file_proxy import FileProxy from .jupyter import JupyterMixin from .live_render import LiveRender, VerticalOverflowMethod from .screen import Screen from .text import Text if TYPE_CHECKING: # Can be replaced with `from typing import Self` in Python 3.11+ from typing_extensions import Self # pragma: no cover class _RefreshThread(Thread): """A thread that calls refresh() at regular intervals.""" def __init__(self, live: "Live", refresh_per_second: float) -> None: self.live = live self.refresh_per_second = refresh_per_second self.done = Event() super().__init__(daemon=True) def stop(self) -> None: self.done.set() def run(self) -> None: while not self.done.wait(1 / self.refresh_per_second): with self.live._lock: if not self.done.is_set(): self.live.refresh() class Live(JupyterMixin, RenderHook): """Renders an auto-updating live display of any given renderable. Args: renderable (RenderableType, optional): The renderable to live display. Defaults to displaying nothing. console (Console, optional): Optional Console instance. Defaults to an internal Console instance writing to stdout. screen (bool, optional): Enable alternate screen mode. Defaults to False. auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()` or `update()` with refresh flag. Defaults to True refresh_per_second (float, optional): Number of times per second to refresh the live display. Defaults to 4. transient (bool, optional): Clear the renderable on exit (has no effect when screen=True). Defaults to False. redirect_stdout (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True. redirect_stderr (bool, optional): Enable redirection of stderr. Defaults to True. vertical_overflow (VerticalOverflowMethod, optional): How to handle renderable when it is too tall for the console. Defaults to "ellipsis". get_renderable (Callable[[], RenderableType], optional): Optional callable to get renderable. Defaults to None. """ def __init__( self, renderable: Optional[RenderableType] = None, *, console: Optional[Console] = None, screen: bool = False, auto_refresh: bool = True, refresh_per_second: float = 4, transient: bool = False, redirect_stdout: bool = True, redirect_stderr: bool = True, vertical_overflow: VerticalOverflowMethod = "ellipsis", get_renderable: Optional[Callable[[], RenderableType]] = None, ) -> None: assert refresh_per_second > 0, "refresh_per_second must be > 0" self._renderable = renderable self.console = console if console is not None else get_console() self._screen = screen self._alt_screen = False self._redirect_stdout = redirect_stdout self._redirect_stderr = redirect_stderr self._restore_stdout: Optional[IO[str]] = None self._restore_stderr: Optional[IO[str]] = None self._lock = RLock() self.ipy_widget: Optional[Any] = None self.auto_refresh = auto_refresh self._started: bool = False self.transient = True if screen else transient self._refresh_thread: Optional[_RefreshThread] = None self.refresh_per_second = refresh_per_second self.vertical_overflow = vertical_overflow self._get_renderable = get_renderable self._live_render = LiveRender( self.get_renderable(), vertical_overflow=vertical_overflow ) self._nested = False @property def is_started(self) -> bool: """Check if live display has been started.""" return self._started def get_renderable(self) -> RenderableType: renderable = ( self._get_renderable() if self._get_renderable is not None else self._renderable ) return renderable or "" def start(self, refresh: bool = False) -> None: """Start live rendering display. Args: refresh (bool, optional): Also refresh. Defaults to False. """ with self._lock: if self._started: return self._started = True if not self.console.set_live(self): self._nested = True return if self._screen: self._alt_screen = self.console.set_alt_screen(True) self.console.show_cursor(False) self._enable_redirect_io() self.console.push_render_hook(self) if refresh: try: self.refresh() except Exception: # If refresh fails, we want to stop the redirection of sys.stderr, # so the error stacktrace is properly displayed in the terminal. # (or, if the code that calls Rich captures the exception and wants to display something, # let this be displayed in the terminal). self.stop() raise if self.auto_refresh: self._refresh_thread = _RefreshThread(self, self.refresh_per_second) self._refresh_thread.start() def stop(self) -> None: """Stop live rendering display.""" with self._lock: if not self._started: return self._started = False self.console.clear_live() if self._nested: if not self.transient: self.console.print(self.renderable) return if self.auto_refresh and self._refresh_thread is not None: self._refresh_thread.stop() self._refresh_thread = None # allow it to fully render on the last even if overflow self.vertical_overflow = "visible" with self.console: try: if not self._alt_screen and not self.console.is_jupyter: self.refresh() finally: self._disable_redirect_io() self.console.pop_render_hook() if not self._alt_screen and self.console.is_terminal: self.console.line() self.console.show_cursor(True) if self._alt_screen: self.console.set_alt_screen(False) if self.transient and not self._alt_screen: self.console.control(self._live_render.restore_cursor()) if self.ipy_widget is not None and self.transient: self.ipy_widget.close() # pragma: no cover def __enter__(self) -> Self: self.start(refresh=self._renderable is not None) return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.stop() def _enable_redirect_io(self) -> None: """Enable redirecting of stdout / stderr.""" if self.console.is_terminal or self.console.is_jupyter: if self._redirect_stdout and not isinstance(sys.stdout, FileProxy): self._restore_stdout = sys.stdout sys.stdout = cast("TextIO", FileProxy(self.console, sys.stdout)) if self._redirect_stderr and not isinstance(sys.stderr, FileProxy): self._restore_stderr = sys.stderr sys.stderr = cast("TextIO", FileProxy(self.console, sys.stderr)) def _disable_redirect_io(self) -> None: """Disable redirecting of stdout / stderr.""" if self._restore_stdout: sys.stdout = cast("TextIO", self._restore_stdout) self._restore_stdout = None if self._restore_stderr: sys.stderr = cast("TextIO", self._restore_stderr) self._restore_stderr = None @property def renderable(self) -> RenderableType: """Get the renderable that is being displayed Returns: RenderableType: Displayed renderable. """ live_stack = self.console._live_stack renderable: RenderableType if live_stack and self is live_stack[0]: # The first Live instance will render everything in the Live stack renderable = Group(*[live.get_renderable() for live in live_stack]) else: renderable = self.get_renderable() return Screen(renderable) if self._alt_screen else renderable def update(self, renderable: RenderableType, *, refresh: bool = False) -> None: """Update the renderable that is being displayed Args: renderable (RenderableType): New renderable to use. refresh (bool, optional): Refresh the display. Defaults to False. """ if isinstance(renderable, str): renderable = self.console.render_str(renderable) with self._lock: self._renderable = renderable if refresh: self.refresh() def refresh(self) -> None: """Update the display of the Live Render.""" with self._lock: self._live_render.set_renderable(self.renderable) if self._nested: if self.console._live_stack: self.console._live_stack[0].refresh() return if self.console.is_jupyter: # pragma: no cover try: from IPython.display import display from ipywidgets import Output except ImportError: import warnings warnings.warn('install "ipywidgets" for Jupyter support') else: if self.ipy_widget is None: self.ipy_widget = Output() display(self.ipy_widget) with self.ipy_widget: self.ipy_widget.clear_output(wait=True) self.console.print(self._live_render.renderable) elif self.console.is_terminal and not self.console.is_dumb_terminal: with self.console: self.console.print(Control()) elif ( not self._started and not self.transient ): # if it is finished allow files or dumb-terminals to see final result with self.console: self.console.print(Control()) def process_renderables( self, renderables: List[ConsoleRenderable] ) -> List[ConsoleRenderable]: """Process renderables to restore cursor and display progress.""" self._live_render.vertical_overflow = self.vertical_overflow if self.console.is_interactive: # lock needs acquiring as user can modify live_render renderable at any time unlike in Progress. with self._lock: reset = ( Control.home() if self._alt_screen else self._live_render.position_cursor() ) renderables = [reset, *renderables, self._live_render] elif ( not self._started and not self.transient ): # if it is finished render the final output for files or dumb_terminals renderables = [*renderables, self._live_render] return renderables if __name__ == "__main__": # pragma: no cover import random import time from itertools import cycle from typing import Dict, List, Tuple from .align import Align from .console import Console from .live import Live as Live from .panel import Panel from .rule import Rule from .syntax import Syntax from .table import Table console = Console() syntax = Syntax( '''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: """Iterate and generate a tuple with a flag for last value.""" iter_values = iter(values) try: previous_value = next(iter_values) except StopIteration: return for value in iter_values: yield False, previous_value previous_value = value yield True, previous_value''', "python", line_numbers=True, ) table = Table("foo", "bar", "baz") table.add_row("1", "2", "3") progress_renderables = [ "You can make the terminal shorter and taller to see the live table hide" "Text may be printed while the progress bars are rendering.", Panel("In fact, [i]any[/i] renderable will work"), "Such as [magenta]tables[/]...", table, "Pretty printed structures...", {"type": "example", "text": "Pretty printed"}, "Syntax...", syntax, Rule("Give it a try!"), ] examples = cycle(progress_renderables) exchanges = [ "SGD", "MYR", "EUR", "USD", "AUD", "JPY", "CNH", "HKD", "CAD", "INR", "DKK", "GBP", "RUB", "NZD", "MXN", "IDR", "TWD", "THB", "VND", ] with Live(console=console) as live_table: exchange_rate_dict: Dict[Tuple[str, str], float] = {} for index in range(100): select_exchange = exchanges[index % len(exchanges)] for exchange in exchanges: if exchange == select_exchange: continue time.sleep(0.4) if random.randint(0, 10) < 1: console.log(next(examples)) exchange_rate_dict[(select_exchange, exchange)] = 200 / ( (random.random() * 320) + 1 ) if len(exchange_rate_dict) > len(exchanges) - 1: exchange_rate_dict.pop(list(exchange_rate_dict.keys())[0]) table = Table(title="Exchange Rates") table.add_column("Source Currency") table.add_column("Destination Currency") table.add_column("Exchange Rate") for (source, dest), exchange_rate in exchange_rate_dict.items(): table.add_row( source, dest, Text( f"{exchange_rate:.4f}", style="red" if exchange_rate < 1.0 else "green", ), ) live_table.update(Align.center(table))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/control.py
rich/control.py
import time from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Union, Final from .segment import ControlCode, ControlType, Segment if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderResult STRIP_CONTROL_CODES: Final = [ 7, # Bell 8, # Backspace 11, # Vertical tab 12, # Form feed 13, # Carriage return ] _CONTROL_STRIP_TRANSLATE: Final = { _codepoint: None for _codepoint in STRIP_CONTROL_CODES } CONTROL_ESCAPE: Final = { 7: "\\a", 8: "\\b", 11: "\\v", 12: "\\f", 13: "\\r", } CONTROL_CODES_FORMAT: Dict[int, Callable[..., str]] = { ControlType.BELL: lambda: "\x07", ControlType.CARRIAGE_RETURN: lambda: "\r", ControlType.HOME: lambda: "\x1b[H", ControlType.CLEAR: lambda: "\x1b[2J", ControlType.ENABLE_ALT_SCREEN: lambda: "\x1b[?1049h", ControlType.DISABLE_ALT_SCREEN: lambda: "\x1b[?1049l", ControlType.SHOW_CURSOR: lambda: "\x1b[?25h", ControlType.HIDE_CURSOR: lambda: "\x1b[?25l", ControlType.CURSOR_UP: lambda param: f"\x1b[{param}A", ControlType.CURSOR_DOWN: lambda param: f"\x1b[{param}B", ControlType.CURSOR_FORWARD: lambda param: f"\x1b[{param}C", ControlType.CURSOR_BACKWARD: lambda param: f"\x1b[{param}D", ControlType.CURSOR_MOVE_TO_COLUMN: lambda param: f"\x1b[{param+1}G", ControlType.ERASE_IN_LINE: lambda param: f"\x1b[{param}K", ControlType.CURSOR_MOVE_TO: lambda x, y: f"\x1b[{y+1};{x+1}H", ControlType.SET_WINDOW_TITLE: lambda title: f"\x1b]0;{title}\x07", } class Control: """A renderable that inserts a control code (non printable but may move cursor). Args: *codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a tuple of ControlType and an integer parameter """ __slots__ = ["segment"] def __init__(self, *codes: Union[ControlType, ControlCode]) -> None: control_codes: List[ControlCode] = [ (code,) if isinstance(code, ControlType) else code for code in codes ] _format_map = CONTROL_CODES_FORMAT rendered_codes = "".join( _format_map[code](*parameters) for code, *parameters in control_codes ) self.segment = Segment(rendered_codes, None, control_codes) @classmethod def bell(cls) -> "Control": """Ring the 'bell'.""" return cls(ControlType.BELL) @classmethod def home(cls) -> "Control": """Move cursor to 'home' position.""" return cls(ControlType.HOME) @classmethod def move(cls, x: int = 0, y: int = 0) -> "Control": """Move cursor relative to current position. Args: x (int): X offset. y (int): Y offset. Returns: ~Control: Control object. """ def get_codes() -> Iterable[ControlCode]: control = ControlType if x: yield ( control.CURSOR_FORWARD if x > 0 else control.CURSOR_BACKWARD, abs(x), ) if y: yield ( control.CURSOR_DOWN if y > 0 else control.CURSOR_UP, abs(y), ) control = cls(*get_codes()) return control @classmethod def move_to_column(cls, x: int, y: int = 0) -> "Control": """Move to the given column, optionally add offset to row. Returns: x (int): absolute x (column) y (int): optional y offset (row) Returns: ~Control: Control object. """ return ( cls( (ControlType.CURSOR_MOVE_TO_COLUMN, x), ( ControlType.CURSOR_DOWN if y > 0 else ControlType.CURSOR_UP, abs(y), ), ) if y else cls((ControlType.CURSOR_MOVE_TO_COLUMN, x)) ) @classmethod def move_to(cls, x: int, y: int) -> "Control": """Move cursor to absolute position. Args: x (int): x offset (column) y (int): y offset (row) Returns: ~Control: Control object. """ return cls((ControlType.CURSOR_MOVE_TO, x, y)) @classmethod def clear(cls) -> "Control": """Clear the screen.""" return cls(ControlType.CLEAR) @classmethod def show_cursor(cls, show: bool) -> "Control": """Show or hide the cursor.""" return cls(ControlType.SHOW_CURSOR if show else ControlType.HIDE_CURSOR) @classmethod def alt_screen(cls, enable: bool) -> "Control": """Enable or disable alt screen.""" if enable: return cls(ControlType.ENABLE_ALT_SCREEN, ControlType.HOME) else: return cls(ControlType.DISABLE_ALT_SCREEN) @classmethod def title(cls, title: str) -> "Control": """Set the terminal window title Args: title (str): The new terminal window title """ return cls((ControlType.SET_WINDOW_TITLE, title)) def __str__(self) -> str: return self.segment.text def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": if self.segment.text: yield self.segment def strip_control_codes( text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE ) -> str: """Remove control codes from text. Args: text (str): A string possibly contain control codes. Returns: str: String with control codes removed. """ return text.translate(_translate_table) def escape_control_codes( text: str, _translate_table: Dict[int, str] = CONTROL_ESCAPE, ) -> str: """Replace control codes with their "escaped" equivalent in the given text. (e.g. "\b" becomes "\\b") Args: text (str): A string possibly containing control codes. Returns: str: String with control codes replaced with their escaped version. """ return text.translate(_translate_table) if __name__ == "__main__": # pragma: no cover from rich.console import Console console = Console() console.print("Look at the title of your terminal window ^") # console.print(Control((ControlType.SET_WINDOW_TITLE, "Hello, world!"))) for i in range(10): console.set_window_title("🚀 Loading" + "." * i) time.sleep(0.5)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_windows_renderer.py
rich/_windows_renderer.py
from typing import Iterable, Sequence, Tuple, cast from rich._win32_console import LegacyWindowsTerm, WindowsCoordinates from rich.segment import ControlCode, ControlType, Segment def legacy_windows_render(buffer: Iterable[Segment], term: LegacyWindowsTerm) -> None: """Makes appropriate Windows Console API calls based on the segments in the buffer. Args: buffer (Iterable[Segment]): Iterable of Segments to convert to Win32 API calls. term (LegacyWindowsTerm): Used to call the Windows Console API. """ for text, style, control in buffer: if not control: if style: term.write_styled(text, style) else: term.write_text(text) else: control_codes: Sequence[ControlCode] = control for control_code in control_codes: control_type = control_code[0] if control_type == ControlType.CURSOR_MOVE_TO: _, x, y = cast(Tuple[ControlType, int, int], control_code) term.move_cursor_to(WindowsCoordinates(row=y - 1, col=x - 1)) elif control_type == ControlType.CARRIAGE_RETURN: term.write_text("\r") elif control_type == ControlType.HOME: term.move_cursor_to(WindowsCoordinates(0, 0)) elif control_type == ControlType.CURSOR_UP: term.move_cursor_up() elif control_type == ControlType.CURSOR_DOWN: term.move_cursor_down() elif control_type == ControlType.CURSOR_FORWARD: term.move_cursor_forward() elif control_type == ControlType.CURSOR_BACKWARD: term.move_cursor_backward() elif control_type == ControlType.CURSOR_MOVE_TO_COLUMN: _, column = cast(Tuple[ControlType, int], control_code) term.move_cursor_to_column(column - 1) elif control_type == ControlType.HIDE_CURSOR: term.hide_cursor() elif control_type == ControlType.SHOW_CURSOR: term.show_cursor() elif control_type == ControlType.ERASE_IN_LINE: _, mode = cast(Tuple[ControlType, int], control_code) if mode == 0: term.erase_end_of_line() elif mode == 1: term.erase_start_of_line() elif mode == 2: term.erase_line() elif control_type == ControlType.SET_WINDOW_TITLE: _, title = cast(Tuple[ControlType, str], control_code) term.set_title(title)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/file_proxy.py
rich/file_proxy.py
import io from typing import IO, TYPE_CHECKING, Any, List from .ansi import AnsiDecoder from .text import Text if TYPE_CHECKING: from .console import Console class FileProxy(io.TextIOBase): """Wraps a file (e.g. sys.stdout) and redirects writes to a console.""" def __init__(self, console: "Console", file: IO[str]) -> None: self.__console = console self.__file = file self.__buffer: List[str] = [] self.__ansi_decoder = AnsiDecoder() @property def rich_proxied_file(self) -> IO[str]: """Get proxied file.""" return self.__file def __getattr__(self, name: str) -> Any: return getattr(self.__file, name) def write(self, text: str) -> int: if not isinstance(text, str): raise TypeError(f"write() argument must be str, not {type(text).__name__}") buffer = self.__buffer lines: List[str] = [] while text: line, new_line, text = text.partition("\n") if new_line: lines.append("".join(buffer) + line) buffer.clear() else: buffer.append(line) break if lines: console = self.__console with console: output = Text("\n").join( self.__ansi_decoder.decode_line(line) for line in lines ) console.print(output) return len(text) def flush(self) -> None: output = "".join(self.__buffer) if output: self.__console.print(output) del self.__buffer[:] def fileno(self) -> int: return self.__file.fileno()
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/color_triplet.py
rich/color_triplet.py
from typing import NamedTuple, Tuple class ColorTriplet(NamedTuple): """The red, green, and blue components of a color.""" red: int """Red component in 0 to 255 range.""" green: int """Green component in 0 to 255 range.""" blue: int """Blue component in 0 to 255 range.""" @property def hex(self) -> str: """get the color triplet in CSS style.""" red, green, blue = self return f"#{red:02x}{green:02x}{blue:02x}" @property def rgb(self) -> str: """The color in RGB format. Returns: str: An rgb color, e.g. ``"rgb(100,23,255)"``. """ red, green, blue = self return f"rgb({red},{green},{blue})" @property def normalized(self) -> Tuple[float, float, float]: """Convert components into floats between 0 and 1. Returns: Tuple[float, float, float]: A tuple of three normalized colour components. """ red, green, blue = self return red / 255.0, green / 255.0, blue / 255.0
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/measure.py
rich/measure.py
from operator import itemgetter from typing import TYPE_CHECKING, Callable, NamedTuple, Optional, Sequence from . import errors from .protocol import is_renderable, rich_cast if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderableType class Measurement(NamedTuple): """Stores the minimum and maximum widths (in characters) required to render an object.""" minimum: int """Minimum number of cells required to render.""" maximum: int """Maximum number of cells required to render.""" @property def span(self) -> int: """Get difference between maximum and minimum.""" return self.maximum - self.minimum def normalize(self) -> "Measurement": """Get measurement that ensures that minimum <= maximum and minimum >= 0 Returns: Measurement: A normalized measurement. """ minimum, maximum = self minimum = min(max(0, minimum), maximum) return Measurement(max(0, minimum), max(0, max(minimum, maximum))) def with_maximum(self, width: int) -> "Measurement": """Get a RenderableWith where the widths are <= width. Args: width (int): Maximum desired width. Returns: Measurement: New Measurement object. """ minimum, maximum = self return Measurement(min(minimum, width), min(maximum, width)) def with_minimum(self, width: int) -> "Measurement": """Get a RenderableWith where the widths are >= width. Args: width (int): Minimum desired width. Returns: Measurement: New Measurement object. """ minimum, maximum = self width = max(0, width) return Measurement(max(minimum, width), max(maximum, width)) def clamp( self, min_width: Optional[int] = None, max_width: Optional[int] = None ) -> "Measurement": """Clamp a measurement within the specified range. Args: min_width (int): Minimum desired width, or ``None`` for no minimum. Defaults to None. max_width (int): Maximum desired width, or ``None`` for no maximum. Defaults to None. Returns: Measurement: New Measurement object. """ measurement = self if min_width is not None: measurement = measurement.with_minimum(min_width) if max_width is not None: measurement = measurement.with_maximum(max_width) return measurement @classmethod def get( cls, console: "Console", options: "ConsoleOptions", renderable: "RenderableType" ) -> "Measurement": """Get a measurement for a renderable. Args: console (~rich.console.Console): Console instance. options (~rich.console.ConsoleOptions): Console options. renderable (RenderableType): An object that may be rendered with Rich. Raises: errors.NotRenderableError: If the object is not renderable. Returns: Measurement: Measurement object containing range of character widths required to render the object. """ _max_width = options.max_width if _max_width < 1: return Measurement(0, 0) if isinstance(renderable, str): renderable = console.render_str( renderable, markup=options.markup, highlight=False ) renderable = rich_cast(renderable) if is_renderable(renderable): get_console_width: Optional[ Callable[["Console", "ConsoleOptions"], "Measurement"] ] = getattr(renderable, "__rich_measure__", None) if get_console_width is not None: render_width = ( get_console_width(console, options) .normalize() .with_maximum(_max_width) ) if render_width.maximum < 1: return Measurement(0, 0) return render_width.normalize() else: return Measurement(0, _max_width) else: raise errors.NotRenderableError( f"Unable to get render width for {renderable!r}; " "a str, Segment, or object with __rich_console__ method is required" ) def measure_renderables( console: "Console", options: "ConsoleOptions", renderables: Sequence["RenderableType"], ) -> "Measurement": """Get a measurement that would fit a number of renderables. Args: console (~rich.console.Console): Console instance. options (~rich.console.ConsoleOptions): Console options. renderables (Iterable[RenderableType]): One or more renderable objects. Returns: Measurement: Measurement object containing range of character widths required to contain all given renderables. """ if not renderables: return Measurement(0, 0) get_measurement = Measurement.get measurements = [ get_measurement(console, options, renderable) for renderable in renderables ] measured_width = Measurement( max(measurements, key=itemgetter(0)).minimum, max(measurements, key=itemgetter(1)).maximum, ) return measured_width
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_win32_console.py
rich/_win32_console.py
"""Light wrapper around the Win32 Console API - this module should only be imported on Windows The API that this module wraps is documented at https://docs.microsoft.com/en-us/windows/console/console-functions """ import ctypes import sys from typing import Any windll: Any = None if sys.platform == "win32": windll = ctypes.LibraryLoader(ctypes.WinDLL) else: raise ImportError(f"{__name__} can only be imported on Windows") import time from ctypes import Structure, byref, wintypes from typing import IO, NamedTuple, Type, cast from rich.color import ColorSystem from rich.style import Style STDOUT = -11 ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4 COORD = wintypes._COORD class LegacyWindowsError(Exception): pass class WindowsCoordinates(NamedTuple): """Coordinates in the Windows Console API are (y, x), not (x, y). This class is intended to prevent that confusion. Rows and columns are indexed from 0. This class can be used in place of wintypes._COORD in arguments and argtypes. """ row: int col: int @classmethod def from_param(cls, value: "WindowsCoordinates") -> COORD: """Converts a WindowsCoordinates into a wintypes _COORD structure. This classmethod is internally called by ctypes to perform the conversion. Args: value (WindowsCoordinates): The input coordinates to convert. Returns: wintypes._COORD: The converted coordinates struct. """ return COORD(value.col, value.row) class CONSOLE_SCREEN_BUFFER_INFO(Structure): _fields_ = [ ("dwSize", COORD), ("dwCursorPosition", COORD), ("wAttributes", wintypes.WORD), ("srWindow", wintypes.SMALL_RECT), ("dwMaximumWindowSize", COORD), ] class CONSOLE_CURSOR_INFO(ctypes.Structure): _fields_ = [("dwSize", wintypes.DWORD), ("bVisible", wintypes.BOOL)] _GetStdHandle = windll.kernel32.GetStdHandle _GetStdHandle.argtypes = [ wintypes.DWORD, ] _GetStdHandle.restype = wintypes.HANDLE def GetStdHandle(handle: int = STDOUT) -> wintypes.HANDLE: """Retrieves a handle to the specified standard device (standard input, standard output, or standard error). Args: handle (int): Integer identifier for the handle. Defaults to -11 (stdout). Returns: wintypes.HANDLE: The handle """ return cast(wintypes.HANDLE, _GetStdHandle(handle)) _GetConsoleMode = windll.kernel32.GetConsoleMode _GetConsoleMode.argtypes = [wintypes.HANDLE, wintypes.LPDWORD] _GetConsoleMode.restype = wintypes.BOOL def GetConsoleMode(std_handle: wintypes.HANDLE) -> int: """Retrieves the current input mode of a console's input buffer or the current output mode of a console screen buffer. Args: std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. Raises: LegacyWindowsError: If any error occurs while calling the Windows console API. Returns: int: Value representing the current console mode as documented at https://docs.microsoft.com/en-us/windows/console/getconsolemode#parameters """ console_mode = wintypes.DWORD() success = bool(_GetConsoleMode(std_handle, console_mode)) if not success: raise LegacyWindowsError("Unable to get legacy Windows Console Mode") return console_mode.value _FillConsoleOutputCharacterW = windll.kernel32.FillConsoleOutputCharacterW _FillConsoleOutputCharacterW.argtypes = [ wintypes.HANDLE, ctypes.c_char, wintypes.DWORD, cast(Type[COORD], WindowsCoordinates), ctypes.POINTER(wintypes.DWORD), ] _FillConsoleOutputCharacterW.restype = wintypes.BOOL def FillConsoleOutputCharacter( std_handle: wintypes.HANDLE, char: str, length: int, start: WindowsCoordinates, ) -> int: """Writes a character to the console screen buffer a specified number of times, beginning at the specified coordinates. Args: std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. char (str): The character to write. Must be a string of length 1. length (int): The number of times to write the character. start (WindowsCoordinates): The coordinates to start writing at. Returns: int: The number of characters written. """ character = ctypes.c_char(char.encode()) num_characters = wintypes.DWORD(length) num_written = wintypes.DWORD(0) _FillConsoleOutputCharacterW( std_handle, character, num_characters, start, byref(num_written), ) return num_written.value _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute _FillConsoleOutputAttribute.argtypes = [ wintypes.HANDLE, wintypes.WORD, wintypes.DWORD, cast(Type[COORD], WindowsCoordinates), ctypes.POINTER(wintypes.DWORD), ] _FillConsoleOutputAttribute.restype = wintypes.BOOL def FillConsoleOutputAttribute( std_handle: wintypes.HANDLE, attributes: int, length: int, start: WindowsCoordinates, ) -> int: """Sets the character attributes for a specified number of character cells, beginning at the specified coordinates in a screen buffer. Args: std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. attributes (int): Integer value representing the foreground and background colours of the cells. length (int): The number of cells to set the output attribute of. start (WindowsCoordinates): The coordinates of the first cell whose attributes are to be set. Returns: int: The number of cells whose attributes were actually set. """ num_cells = wintypes.DWORD(length) style_attrs = wintypes.WORD(attributes) num_written = wintypes.DWORD(0) _FillConsoleOutputAttribute( std_handle, style_attrs, num_cells, start, byref(num_written) ) return num_written.value _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute _SetConsoleTextAttribute.argtypes = [ wintypes.HANDLE, wintypes.WORD, ] _SetConsoleTextAttribute.restype = wintypes.BOOL def SetConsoleTextAttribute( std_handle: wintypes.HANDLE, attributes: wintypes.WORD ) -> bool: """Set the colour attributes for all text written after this function is called. Args: std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. attributes (int): Integer value representing the foreground and background colours. Returns: bool: True if the attribute was set successfully, otherwise False. """ return bool(_SetConsoleTextAttribute(std_handle, attributes)) _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo _GetConsoleScreenBufferInfo.argtypes = [ wintypes.HANDLE, ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO), ] _GetConsoleScreenBufferInfo.restype = wintypes.BOOL def GetConsoleScreenBufferInfo( std_handle: wintypes.HANDLE, ) -> CONSOLE_SCREEN_BUFFER_INFO: """Retrieves information about the specified console screen buffer. Args: std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. Returns: CONSOLE_SCREEN_BUFFER_INFO: A CONSOLE_SCREEN_BUFFER_INFO ctype struct contain information about screen size, cursor position, colour attributes, and more.""" console_screen_buffer_info = CONSOLE_SCREEN_BUFFER_INFO() _GetConsoleScreenBufferInfo(std_handle, byref(console_screen_buffer_info)) return console_screen_buffer_info _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition _SetConsoleCursorPosition.argtypes = [ wintypes.HANDLE, cast(Type[COORD], WindowsCoordinates), ] _SetConsoleCursorPosition.restype = wintypes.BOOL def SetConsoleCursorPosition( std_handle: wintypes.HANDLE, coords: WindowsCoordinates ) -> bool: """Set the position of the cursor in the console screen Args: std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. coords (WindowsCoordinates): The coordinates to move the cursor to. Returns: bool: True if the function succeeds, otherwise False. """ return bool(_SetConsoleCursorPosition(std_handle, coords)) _GetConsoleCursorInfo = windll.kernel32.GetConsoleCursorInfo _GetConsoleCursorInfo.argtypes = [ wintypes.HANDLE, ctypes.POINTER(CONSOLE_CURSOR_INFO), ] _GetConsoleCursorInfo.restype = wintypes.BOOL def GetConsoleCursorInfo( std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO ) -> bool: """Get the cursor info - used to get cursor visibility and width Args: std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct that receives information about the console's cursor. Returns: bool: True if the function succeeds, otherwise False. """ return bool(_GetConsoleCursorInfo(std_handle, byref(cursor_info))) _SetConsoleCursorInfo = windll.kernel32.SetConsoleCursorInfo _SetConsoleCursorInfo.argtypes = [ wintypes.HANDLE, ctypes.POINTER(CONSOLE_CURSOR_INFO), ] _SetConsoleCursorInfo.restype = wintypes.BOOL def SetConsoleCursorInfo( std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO ) -> bool: """Set the cursor info - used for adjusting cursor visibility and width Args: std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct containing the new cursor info. Returns: bool: True if the function succeeds, otherwise False. """ return bool(_SetConsoleCursorInfo(std_handle, byref(cursor_info))) _SetConsoleTitle = windll.kernel32.SetConsoleTitleW _SetConsoleTitle.argtypes = [wintypes.LPCWSTR] _SetConsoleTitle.restype = wintypes.BOOL def SetConsoleTitle(title: str) -> bool: """Sets the title of the current console window Args: title (str): The new title of the console window. Returns: bool: True if the function succeeds, otherwise False. """ return bool(_SetConsoleTitle(title)) class LegacyWindowsTerm: """This class allows interaction with the legacy Windows Console API. It should only be used in the context of environments where virtual terminal processing is not available. However, if it is used in a Windows environment, the entire API should work. Args: file (IO[str]): The file which the Windows Console API HANDLE is retrieved from, defaults to sys.stdout. """ BRIGHT_BIT = 8 # Indices are ANSI color numbers, values are the corresponding Windows Console API color numbers ANSI_TO_WINDOWS = [ 0, # black The Windows colours are defined in wincon.h as follows: 4, # red define FOREGROUND_BLUE 0x0001 -- 0000 0001 2, # green define FOREGROUND_GREEN 0x0002 -- 0000 0010 6, # yellow define FOREGROUND_RED 0x0004 -- 0000 0100 1, # blue define FOREGROUND_INTENSITY 0x0008 -- 0000 1000 5, # magenta define BACKGROUND_BLUE 0x0010 -- 0001 0000 3, # cyan define BACKGROUND_GREEN 0x0020 -- 0010 0000 7, # white define BACKGROUND_RED 0x0040 -- 0100 0000 8, # bright black (grey) define BACKGROUND_INTENSITY 0x0080 -- 1000 0000 12, # bright red 10, # bright green 14, # bright yellow 9, # bright blue 13, # bright magenta 11, # bright cyan 15, # bright white ] def __init__(self, file: "IO[str]") -> None: handle = GetStdHandle(STDOUT) self._handle = handle default_text = GetConsoleScreenBufferInfo(handle).wAttributes self._default_text = default_text self._default_fore = default_text & 7 self._default_back = (default_text >> 4) & 7 self._default_attrs = self._default_fore | (self._default_back << 4) self._file = file self.write = file.write self.flush = file.flush @property def cursor_position(self) -> WindowsCoordinates: """Returns the current position of the cursor (0-based) Returns: WindowsCoordinates: The current cursor position. """ coord: COORD = GetConsoleScreenBufferInfo(self._handle).dwCursorPosition return WindowsCoordinates(row=coord.Y, col=coord.X) @property def screen_size(self) -> WindowsCoordinates: """Returns the current size of the console screen buffer, in character columns and rows Returns: WindowsCoordinates: The width and height of the screen as WindowsCoordinates. """ screen_size: COORD = GetConsoleScreenBufferInfo(self._handle).dwSize return WindowsCoordinates(row=screen_size.Y, col=screen_size.X) def write_text(self, text: str) -> None: """Write text directly to the terminal without any modification of styles Args: text (str): The text to write to the console """ self.write(text) self.flush() def write_styled(self, text: str, style: Style) -> None: """Write styled text to the terminal. Args: text (str): The text to write style (Style): The style of the text """ color = style.color bgcolor = style.bgcolor if style.reverse: color, bgcolor = bgcolor, color if color: fore = color.downgrade(ColorSystem.WINDOWS).number fore = fore if fore is not None else 7 # Default to ANSI 7: White if style.bold: fore = fore | self.BRIGHT_BIT if style.dim: fore = fore & ~self.BRIGHT_BIT fore = self.ANSI_TO_WINDOWS[fore] else: fore = self._default_fore if bgcolor: back = bgcolor.downgrade(ColorSystem.WINDOWS).number back = back if back is not None else 0 # Default to ANSI 0: Black back = self.ANSI_TO_WINDOWS[back] else: back = self._default_back assert fore is not None assert back is not None SetConsoleTextAttribute( self._handle, attributes=ctypes.c_ushort(fore | (back << 4)) ) self.write_text(text) SetConsoleTextAttribute(self._handle, attributes=self._default_text) def move_cursor_to(self, new_position: WindowsCoordinates) -> None: """Set the position of the cursor Args: new_position (WindowsCoordinates): The WindowsCoordinates representing the new position of the cursor. """ if new_position.col < 0 or new_position.row < 0: return SetConsoleCursorPosition(self._handle, coords=new_position) def erase_line(self) -> None: """Erase all content on the line the cursor is currently located at""" screen_size = self.screen_size cursor_position = self.cursor_position cells_to_erase = screen_size.col start_coordinates = WindowsCoordinates(row=cursor_position.row, col=0) FillConsoleOutputCharacter( self._handle, " ", length=cells_to_erase, start=start_coordinates ) FillConsoleOutputAttribute( self._handle, self._default_attrs, length=cells_to_erase, start=start_coordinates, ) def erase_end_of_line(self) -> None: """Erase all content from the cursor position to the end of that line""" cursor_position = self.cursor_position cells_to_erase = self.screen_size.col - cursor_position.col FillConsoleOutputCharacter( self._handle, " ", length=cells_to_erase, start=cursor_position ) FillConsoleOutputAttribute( self._handle, self._default_attrs, length=cells_to_erase, start=cursor_position, ) def erase_start_of_line(self) -> None: """Erase all content from the cursor position to the start of that line""" row, col = self.cursor_position start = WindowsCoordinates(row, 0) FillConsoleOutputCharacter(self._handle, " ", length=col, start=start) FillConsoleOutputAttribute( self._handle, self._default_attrs, length=col, start=start ) def move_cursor_up(self) -> None: """Move the cursor up a single cell""" cursor_position = self.cursor_position SetConsoleCursorPosition( self._handle, coords=WindowsCoordinates( row=cursor_position.row - 1, col=cursor_position.col ), ) def move_cursor_down(self) -> None: """Move the cursor down a single cell""" cursor_position = self.cursor_position SetConsoleCursorPosition( self._handle, coords=WindowsCoordinates( row=cursor_position.row + 1, col=cursor_position.col, ), ) def move_cursor_forward(self) -> None: """Move the cursor forward a single cell. Wrap to the next line if required.""" row, col = self.cursor_position if col == self.screen_size.col - 1: row += 1 col = 0 else: col += 1 SetConsoleCursorPosition( self._handle, coords=WindowsCoordinates(row=row, col=col) ) def move_cursor_to_column(self, column: int) -> None: """Move cursor to the column specified by the zero-based column index, staying on the same row Args: column (int): The zero-based column index to move the cursor to. """ row, _ = self.cursor_position SetConsoleCursorPosition(self._handle, coords=WindowsCoordinates(row, column)) def move_cursor_backward(self) -> None: """Move the cursor backward a single cell. Wrap to the previous line if required.""" row, col = self.cursor_position if col == 0: row -= 1 col = self.screen_size.col - 1 else: col -= 1 SetConsoleCursorPosition( self._handle, coords=WindowsCoordinates(row=row, col=col) ) def hide_cursor(self) -> None: """Hide the cursor""" current_cursor_size = self._get_cursor_size() invisible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=0) SetConsoleCursorInfo(self._handle, cursor_info=invisible_cursor) def show_cursor(self) -> None: """Show the cursor""" current_cursor_size = self._get_cursor_size() visible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=1) SetConsoleCursorInfo(self._handle, cursor_info=visible_cursor) def set_title(self, title: str) -> None: """Set the title of the terminal window Args: title (str): The new title of the console window """ assert len(title) < 255, "Console title must be less than 255 characters" SetConsoleTitle(title) def _get_cursor_size(self) -> int: """Get the percentage of the character cell that is filled by the cursor""" cursor_info = CONSOLE_CURSOR_INFO() GetConsoleCursorInfo(self._handle, cursor_info=cursor_info) return int(cursor_info.dwSize) if __name__ == "__main__": handle = GetStdHandle() from rich.console import Console console = Console() term = LegacyWindowsTerm(sys.stdout) term.set_title("Win32 Console Examples") style = Style(color="black", bgcolor="red") heading = Style.parse("black on green") # Check colour output console.rule("Checking colour output") console.print("[on red]on red!") console.print("[blue]blue!") console.print("[yellow]yellow!") console.print("[bold yellow]bold yellow!") console.print("[bright_yellow]bright_yellow!") console.print("[dim bright_yellow]dim bright_yellow!") console.print("[italic cyan]italic cyan!") console.print("[bold white on blue]bold white on blue!") console.print("[reverse bold white on blue]reverse bold white on blue!") console.print("[bold black on cyan]bold black on cyan!") console.print("[black on green]black on green!") console.print("[blue on green]blue on green!") console.print("[white on black]white on black!") console.print("[black on white]black on white!") console.print("[#1BB152 on #DA812D]#1BB152 on #DA812D!") # Check cursor movement console.rule("Checking cursor movement") console.print() term.move_cursor_backward() term.move_cursor_backward() term.write_text("went back and wrapped to prev line") time.sleep(1) term.move_cursor_up() term.write_text("we go up") time.sleep(1) term.move_cursor_down() term.write_text("and down") time.sleep(1) term.move_cursor_up() term.move_cursor_backward() term.move_cursor_backward() term.write_text("we went up and back 2") time.sleep(1) term.move_cursor_down() term.move_cursor_backward() term.move_cursor_backward() term.write_text("we went down and back 2") time.sleep(1) # Check erasing of lines term.hide_cursor() console.print() console.rule("Checking line erasing") console.print("\n...Deleting to the start of the line...") term.write_text("The red arrow shows the cursor location, and direction of erase") time.sleep(1) term.move_cursor_to_column(16) term.write_styled("<", Style.parse("black on red")) term.move_cursor_backward() time.sleep(1) term.erase_start_of_line() time.sleep(1) console.print("\n\n...And to the end of the line...") term.write_text("The red arrow shows the cursor location, and direction of erase") time.sleep(1) term.move_cursor_to_column(16) term.write_styled(">", Style.parse("black on red")) time.sleep(1) term.erase_end_of_line() time.sleep(1) console.print("\n\n...Now the whole line will be erased...") term.write_styled("I'm going to disappear!", style=Style.parse("black on cyan")) time.sleep(1) term.erase_line() term.show_cursor() print("\n")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/pager.py
rich/pager.py
from abc import ABC, abstractmethod from typing import Any class Pager(ABC): """Base class for a pager.""" @abstractmethod def show(self, content: str) -> None: """Show content in pager. Args: content (str): Content to be displayed. """ class SystemPager(Pager): """Uses the pager installed on the system.""" def _pager(self, content: str) -> Any: #  pragma: no cover return __import__("pydoc").pager(content) def show(self, content: str) -> None: """Use the same pager used by pydoc.""" self._pager(content) if __name__ == "__main__": # pragma: no cover from .__main__ import make_test_card from .console import Console console = Console() with console.pager(styles=True): console.print(make_test_card())
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/console.py
rich/console.py
import inspect import os import sys import threading import zlib from abc import ABC, abstractmethod from dataclasses import dataclass, field from datetime import datetime from functools import wraps from getpass import getpass from html import escape from inspect import isclass from itertools import islice from math import ceil from time import monotonic from types import FrameType, ModuleType, TracebackType from typing import ( IO, TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Literal, Mapping, NamedTuple, Optional, Protocol, TextIO, Tuple, Type, Union, cast, runtime_checkable, ) from rich._null_file import NULL_FILE from . import errors, themes from ._emoji_replace import _emoji_replace from ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT from ._fileno import get_fileno from ._log_render import FormatTimeCallable, LogRender from .align import Align, AlignMethod from .color import ColorSystem, blend_rgb from .control import Control from .emoji import EmojiVariant from .highlighter import NullHighlighter, ReprHighlighter from .markup import render as render_markup from .measure import Measurement, measure_renderables from .pager import Pager, SystemPager from .pretty import Pretty, is_expandable from .protocol import rich_cast from .region import Region from .scope import render_scope from .screen import Screen from .segment import Segment from .style import Style, StyleType from .styled import Styled from .terminal_theme import DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme from .text import Text, TextType from .theme import Theme, ThemeStack if TYPE_CHECKING: from ._windows import WindowsConsoleFeatures from .live import Live from .status import Status JUPYTER_DEFAULT_COLUMNS = 115 JUPYTER_DEFAULT_LINES = 100 WINDOWS = sys.platform == "win32" HighlighterType = Callable[[Union[str, "Text"]], "Text"] JustifyMethod = Literal["default", "left", "center", "right", "full"] OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"] class NoChange: pass NO_CHANGE = NoChange() try: _STDIN_FILENO = sys.__stdin__.fileno() # type: ignore[union-attr] except Exception: _STDIN_FILENO = 0 try: _STDOUT_FILENO = sys.__stdout__.fileno() # type: ignore[union-attr] except Exception: _STDOUT_FILENO = 1 try: _STDERR_FILENO = sys.__stderr__.fileno() # type: ignore[union-attr] except Exception: _STDERR_FILENO = 2 _STD_STREAMS = (_STDIN_FILENO, _STDOUT_FILENO, _STDERR_FILENO) _STD_STREAMS_OUTPUT = (_STDOUT_FILENO, _STDERR_FILENO) _TERM_COLORS = { "kitty": ColorSystem.EIGHT_BIT, "256color": ColorSystem.EIGHT_BIT, "16color": ColorSystem.STANDARD, } class ConsoleDimensions(NamedTuple): """Size of the terminal.""" width: int """The width of the console in 'cells'.""" height: int """The height of the console in lines.""" @dataclass class ConsoleOptions: """Options for __rich_console__ method.""" size: ConsoleDimensions """Size of console.""" legacy_windows: bool """legacy_windows: flag for legacy windows.""" min_width: int """Minimum width of renderable.""" max_width: int """Maximum width of renderable.""" is_terminal: bool """True if the target is a terminal, otherwise False.""" encoding: str """Encoding of terminal.""" max_height: int """Height of container (starts as terminal)""" justify: Optional[JustifyMethod] = None """Justify value override for renderable.""" overflow: Optional[OverflowMethod] = None """Overflow value override for renderable.""" no_wrap: Optional[bool] = False """Disable wrapping for text.""" highlight: Optional[bool] = None """Highlight override for render_str.""" markup: Optional[bool] = None """Enable markup when rendering strings.""" height: Optional[int] = None @property def ascii_only(self) -> bool: """Check if renderables should use ascii only.""" return not self.encoding.startswith("utf") def copy(self) -> "ConsoleOptions": """Return a copy of the options. Returns: ConsoleOptions: a copy of self. """ options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions) options.__dict__ = self.__dict__.copy() return options def update( self, *, width: Union[int, NoChange] = NO_CHANGE, min_width: Union[int, NoChange] = NO_CHANGE, max_width: Union[int, NoChange] = NO_CHANGE, justify: Union[Optional[JustifyMethod], NoChange] = NO_CHANGE, overflow: Union[Optional[OverflowMethod], NoChange] = NO_CHANGE, no_wrap: Union[Optional[bool], NoChange] = NO_CHANGE, highlight: Union[Optional[bool], NoChange] = NO_CHANGE, markup: Union[Optional[bool], NoChange] = NO_CHANGE, height: Union[Optional[int], NoChange] = NO_CHANGE, ) -> "ConsoleOptions": """Update values, return a copy.""" options = self.copy() if not isinstance(width, NoChange): options.min_width = options.max_width = max(0, width) if not isinstance(min_width, NoChange): options.min_width = min_width if not isinstance(max_width, NoChange): options.max_width = max_width if not isinstance(justify, NoChange): options.justify = justify if not isinstance(overflow, NoChange): options.overflow = overflow if not isinstance(no_wrap, NoChange): options.no_wrap = no_wrap if not isinstance(highlight, NoChange): options.highlight = highlight if not isinstance(markup, NoChange): options.markup = markup if not isinstance(height, NoChange): if height is not None: options.max_height = height options.height = None if height is None else max(0, height) return options def update_width(self, width: int) -> "ConsoleOptions": """Update just the width, return a copy. Args: width (int): New width (sets both min_width and max_width) Returns: ~ConsoleOptions: New console options instance. """ options = self.copy() options.min_width = options.max_width = max(0, width) return options def update_height(self, height: int) -> "ConsoleOptions": """Update the height, and return a copy. Args: height (int): New height Returns: ~ConsoleOptions: New Console options instance. """ options = self.copy() options.max_height = options.height = height return options def reset_height(self) -> "ConsoleOptions": """Return a copy of the options with height set to ``None``. Returns: ~ConsoleOptions: New console options instance. """ options = self.copy() options.height = None return options def update_dimensions(self, width: int, height: int) -> "ConsoleOptions": """Update the width and height, and return a copy. Args: width (int): New width (sets both min_width and max_width). height (int): New height. Returns: ~ConsoleOptions: New console options instance. """ options = self.copy() options.min_width = options.max_width = max(0, width) options.height = options.max_height = height return options @runtime_checkable class RichCast(Protocol): """An object that may be 'cast' to a console renderable.""" def __rich__( self, ) -> Union["ConsoleRenderable", "RichCast", str]: # pragma: no cover ... @runtime_checkable class ConsoleRenderable(Protocol): """An object that supports the console protocol.""" def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": # pragma: no cover ... # A type that may be rendered by Console. RenderableType = Union[ConsoleRenderable, RichCast, str] """A string or any object that may be rendered by Rich.""" # The result of calling a __rich_console__ method. RenderResult = Iterable[Union[RenderableType, Segment]] _null_highlighter = NullHighlighter() class CaptureError(Exception): """An error in the Capture context manager.""" class NewLine: """A renderable to generate new line(s)""" def __init__(self, count: int = 1) -> None: self.count = count def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> Iterable[Segment]: yield Segment("\n" * self.count) class ScreenUpdate: """Render a list of lines at a given offset.""" def __init__(self, lines: List[List[Segment]], x: int, y: int) -> None: self._lines = lines self.x = x self.y = y def __rich_console__( self, console: "Console", options: ConsoleOptions ) -> RenderResult: x = self.x move_to = Control.move_to for offset, line in enumerate(self._lines, self.y): yield move_to(x, offset) yield from line class Capture: """Context manager to capture the result of printing to the console. See :meth:`~rich.console.Console.capture` for how to use. Args: console (Console): A console instance to capture output. """ def __init__(self, console: "Console") -> None: self._console = console self._result: Optional[str] = None def __enter__(self) -> "Capture": self._console.begin_capture() return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self._result = self._console.end_capture() def get(self) -> str: """Get the result of the capture.""" if self._result is None: raise CaptureError( "Capture result is not available until context manager exits." ) return self._result class ThemeContext: """A context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage.""" def __init__(self, console: "Console", theme: Theme, inherit: bool = True) -> None: self.console = console self.theme = theme self.inherit = inherit def __enter__(self) -> "ThemeContext": self.console.push_theme(self.theme) return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.console.pop_theme() class PagerContext: """A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage.""" def __init__( self, console: "Console", pager: Optional[Pager] = None, styles: bool = False, links: bool = False, ) -> None: self._console = console self.pager = SystemPager() if pager is None else pager self.styles = styles self.links = links def __enter__(self) -> "PagerContext": self._console._enter_buffer() return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: if exc_type is None: with self._console._lock: buffer: List[Segment] = self._console._buffer[:] del self._console._buffer[:] segments: Iterable[Segment] = buffer if not self.styles: segments = Segment.strip_styles(segments) elif not self.links: segments = Segment.strip_links(segments) content = self._console._render_buffer(segments) self.pager.show(content) self._console._exit_buffer() class ScreenContext: """A context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage.""" def __init__( self, console: "Console", hide_cursor: bool, style: StyleType = "" ) -> None: self.console = console self.hide_cursor = hide_cursor self.screen = Screen(style=style) self._changed = False def update( self, *renderables: RenderableType, style: Optional[StyleType] = None ) -> None: """Update the screen. Args: renderable (RenderableType, optional): Optional renderable to replace current renderable, or None for no change. Defaults to None. style: (Style, optional): Replacement style, or None for no change. Defaults to None. """ if renderables: self.screen.renderable = ( Group(*renderables) if len(renderables) > 1 else renderables[0] ) if style is not None: self.screen.style = style self.console.print(self.screen, end="") def __enter__(self) -> "ScreenContext": self._changed = self.console.set_alt_screen(True) if self._changed and self.hide_cursor: self.console.show_cursor(False) return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: if self._changed: self.console.set_alt_screen(False) if self.hide_cursor: self.console.show_cursor(True) class Group: """Takes a group of renderables and returns a renderable object that renders the group. Args: renderables (Iterable[RenderableType]): An iterable of renderable objects. fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True. """ def __init__(self, *renderables: "RenderableType", fit: bool = True) -> None: self._renderables = renderables self.fit = fit self._render: Optional[List[RenderableType]] = None @property def renderables(self) -> List["RenderableType"]: if self._render is None: self._render = list(self._renderables) return self._render def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> "Measurement": if self.fit: return measure_renderables(console, options, self.renderables) else: return Measurement(options.max_width, options.max_width) def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> RenderResult: yield from self.renderables def group(fit: bool = True) -> Callable[..., Callable[..., Group]]: """A decorator that turns an iterable of renderables in to a group. Args: fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True. """ def decorator( method: Callable[..., Iterable[RenderableType]], ) -> Callable[..., Group]: """Convert a method that returns an iterable of renderables in to a Group.""" @wraps(method) def _replace(*args: Any, **kwargs: Any) -> Group: renderables = method(*args, **kwargs) return Group(*renderables, fit=fit) return _replace return decorator def _is_jupyter() -> bool: # pragma: no cover """Check if we're running in a Jupyter notebook.""" try: get_ipython # type: ignore[name-defined] except NameError: return False ipython = get_ipython() # type: ignore[name-defined] shell = ipython.__class__.__name__ if ( "google.colab" in str(ipython.__class__) or os.getenv("DATABRICKS_RUNTIME_VERSION") or shell == "ZMQInteractiveShell" ): return True # Jupyter notebook or qtconsole elif shell == "TerminalInteractiveShell": return False # Terminal running IPython else: return False # Other type (?) COLOR_SYSTEMS = { "standard": ColorSystem.STANDARD, "256": ColorSystem.EIGHT_BIT, "truecolor": ColorSystem.TRUECOLOR, "windows": ColorSystem.WINDOWS, } _COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()} @dataclass class ConsoleThreadLocals(threading.local): """Thread local values for Console context.""" theme_stack: ThemeStack buffer: List[Segment] = field(default_factory=list) buffer_index: int = 0 class RenderHook(ABC): """Provides hooks in to the render process.""" @abstractmethod def process_renderables( self, renderables: List[ConsoleRenderable] ) -> List[ConsoleRenderable]: """Called with a list of objects to render. This method can return a new list of renderables, or modify and return the same list. Args: renderables (List[ConsoleRenderable]): A number of renderable objects. Returns: List[ConsoleRenderable]: A replacement list of renderables. """ _windows_console_features: Optional["WindowsConsoleFeatures"] = None def get_windows_console_features() -> "WindowsConsoleFeatures": # pragma: no cover global _windows_console_features if _windows_console_features is not None: return _windows_console_features from ._windows import get_windows_console_features _windows_console_features = get_windows_console_features() return _windows_console_features def detect_legacy_windows() -> bool: """Detect legacy Windows.""" return WINDOWS and not get_windows_console_features().vt class Console: """A high level console interface. Args: color_system (str, optional): The color system supported by your terminal, either ``"standard"``, ``"256"`` or ``"truecolor"``. Leave as ``"auto"`` to autodetect. force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None. force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None. force_interactive (Optional[bool], optional): Enable/disable interactive mode, or None to auto detect. Defaults to None. soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False. theme (Theme, optional): An optional style theme object, or ``None`` for default theme. stderr (bool, optional): Use stderr rather than stdout if ``file`` is not specified. Defaults to False. file (IO, optional): A file object where the console should write to. Defaults to stdout. quiet (bool, Optional): Boolean to suppress all output. Defaults to False. width (int, optional): The width of the terminal. Leave as default to auto-detect width. height (int, optional): The height of the terminal. Leave as default to auto-detect height. style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None. no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None. tab_size (int, optional): Number of spaces used to replace a tab character. Defaults to 8. record (bool, optional): Boolean to enable recording of terminal output, required to call :meth:`export_html`, :meth:`export_svg`, and :meth:`export_text`. Defaults to False. markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True. emoji (bool, optional): Enable emoji code. Defaults to True. emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None. highlight (bool, optional): Enable automatic highlighting. Defaults to True. log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True. log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True. log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%X] ". highlighter (HighlighterType, optional): Default highlighter. legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``. safe_box (bool, optional): Restrict box options that don't render on legacy Windows. get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log), or None for datetime.now. get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic. """ _environ: Mapping[str, str] = os.environ def __init__( self, *, color_system: Optional[ Literal["auto", "standard", "256", "truecolor", "windows"] ] = "auto", force_terminal: Optional[bool] = None, force_jupyter: Optional[bool] = None, force_interactive: Optional[bool] = None, soft_wrap: bool = False, theme: Optional[Theme] = None, stderr: bool = False, file: Optional[IO[str]] = None, quiet: bool = False, width: Optional[int] = None, height: Optional[int] = None, style: Optional[StyleType] = None, no_color: Optional[bool] = None, tab_size: int = 8, record: bool = False, markup: bool = True, emoji: bool = True, emoji_variant: Optional[EmojiVariant] = None, highlight: bool = True, log_time: bool = True, log_path: bool = True, log_time_format: Union[str, FormatTimeCallable] = "[%X]", highlighter: Optional["HighlighterType"] = ReprHighlighter(), legacy_windows: Optional[bool] = None, safe_box: bool = True, get_datetime: Optional[Callable[[], datetime]] = None, get_time: Optional[Callable[[], float]] = None, _environ: Optional[Mapping[str, str]] = None, ): # Copy of os.environ allows us to replace it for testing if _environ is not None: self._environ = _environ self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter if self.is_jupyter: if width is None: jupyter_columns = self._environ.get("JUPYTER_COLUMNS") if jupyter_columns is not None and jupyter_columns.isdigit(): width = int(jupyter_columns) else: width = JUPYTER_DEFAULT_COLUMNS if height is None: jupyter_lines = self._environ.get("JUPYTER_LINES") if jupyter_lines is not None and jupyter_lines.isdigit(): height = int(jupyter_lines) else: height = JUPYTER_DEFAULT_LINES self.tab_size = tab_size self.record = record self._markup = markup self._emoji = emoji self._emoji_variant: Optional[EmojiVariant] = emoji_variant self._highlight = highlight self.legacy_windows: bool = ( (detect_legacy_windows() and not self.is_jupyter) if legacy_windows is None else legacy_windows ) if width is None: columns = self._environ.get("COLUMNS") if columns is not None and columns.isdigit(): width = int(columns) - self.legacy_windows if height is None: lines = self._environ.get("LINES") if lines is not None and lines.isdigit(): height = int(lines) self.soft_wrap = soft_wrap self._width = width self._height = height self._color_system: Optional[ColorSystem] self._force_terminal = None if force_terminal is not None: self._force_terminal = force_terminal self._file = file self.quiet = quiet self.stderr = stderr if color_system is None: self._color_system = None elif color_system == "auto": self._color_system = self._detect_color_system() else: self._color_system = COLOR_SYSTEMS[color_system] self._lock = threading.RLock() self._log_render = LogRender( show_time=log_time, show_path=log_path, time_format=log_time_format, ) self.highlighter: HighlighterType = highlighter or _null_highlighter self.safe_box = safe_box self.get_datetime = get_datetime or datetime.now self.get_time = get_time or monotonic self.style = style self.no_color = ( no_color if no_color is not None else self._environ.get("NO_COLOR", "") != "" ) if force_interactive is None: tty_interactive = self._environ.get("TTY_INTERACTIVE", None) if tty_interactive is not None: if tty_interactive == "0": force_interactive = False elif tty_interactive == "1": force_interactive = True self.is_interactive = ( (self.is_terminal and not self.is_dumb_terminal) if force_interactive is None else force_interactive ) self._record_buffer_lock = threading.RLock() self._thread_locals = ConsoleThreadLocals( theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme) ) self._record_buffer: List[Segment] = [] self._render_hooks: List[RenderHook] = [] self._live_stack: List[Live] = [] self._is_alt_screen = False def __repr__(self) -> str: return f"<console width={self.width} {self._color_system!s}>" @property def file(self) -> IO[str]: """Get the file object to write to.""" file = self._file or (sys.stderr if self.stderr else sys.stdout) file = getattr(file, "rich_proxied_file", file) if file is None: file = NULL_FILE return file @file.setter def file(self, new_file: IO[str]) -> None: """Set a new file object.""" self._file = new_file @property def _buffer(self) -> List[Segment]: """Get a thread local buffer.""" return self._thread_locals.buffer @property def _buffer_index(self) -> int: """Get a thread local buffer.""" return self._thread_locals.buffer_index @_buffer_index.setter def _buffer_index(self, value: int) -> None: self._thread_locals.buffer_index = value @property def _theme_stack(self) -> ThemeStack: """Get the thread local theme stack.""" return self._thread_locals.theme_stack def _detect_color_system(self) -> Optional[ColorSystem]: """Detect color system from env vars.""" if self.is_jupyter: return ColorSystem.TRUECOLOR if not self.is_terminal or self.is_dumb_terminal: return None if WINDOWS: # pragma: no cover if self.legacy_windows: # pragma: no cover return ColorSystem.WINDOWS windows_console_features = get_windows_console_features() return ( ColorSystem.TRUECOLOR if windows_console_features.truecolor else ColorSystem.EIGHT_BIT ) else: color_term = self._environ.get("COLORTERM", "").strip().lower() if color_term in ("truecolor", "24bit"): return ColorSystem.TRUECOLOR term = self._environ.get("TERM", "").strip().lower() _term_name, _hyphen, colors = term.rpartition("-") color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD) return color_system def _enter_buffer(self) -> None: """Enter in to a buffer context, and buffer all output.""" self._buffer_index += 1 def _exit_buffer(self) -> None: """Leave buffer context, and render content if required.""" self._buffer_index -= 1 self._check_buffer() def set_live(self, live: "Live") -> bool: """Set Live instance. Used by Live context manager (no need to call directly). Args: live (Live): Live instance using this Console. Returns: Boolean that indicates if the live is the topmost of the stack. Raises: errors.LiveError: If this Console has a Live context currently active. """ with self._lock: self._live_stack.append(live) return len(self._live_stack) == 1 def clear_live(self) -> None: """Clear the Live instance. Used by the Live context manager (no need to call directly).""" with self._lock: self._live_stack.pop() def push_render_hook(self, hook: RenderHook) -> None: """Add a new render hook to the stack. Args: hook (RenderHook): Render hook instance. """ with self._lock: self._render_hooks.append(hook) def pop_render_hook(self) -> None: """Pop the last renderhook from the stack.""" with self._lock: self._render_hooks.pop() def __enter__(self) -> "Console": """Own context manager to enter buffer context.""" self._enter_buffer() return self def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: """Exit buffer context.""" self._exit_buffer() def begin_capture(self) -> None: """Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output.""" self._enter_buffer() def end_capture(self) -> str: """End capture mode and return captured string. Returns: str: Console output. """ render_result = self._render_buffer(self._buffer) del self._buffer[:] self._exit_buffer() return render_result def push_theme(self, theme: Theme, *, inherit: bool = True) -> None: """Push a new theme on to the top of the stack, replacing the styles from the previous theme. Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather than calling this method directly. Args: theme (Theme): A theme instance. inherit (bool, optional): Inherit existing styles. Defaults to True. """ self._theme_stack.push_theme(theme, inherit=inherit) def pop_theme(self) -> None: """Remove theme from top of stack, restoring previous theme.""" self._theme_stack.pop_theme() def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext: """Use a different theme for the duration of the context manager. Args: theme (Theme): Theme instance to user. inherit (bool, optional): Inherit existing console styles. Defaults to True. Returns: ThemeContext: [description] """ return ThemeContext(self, theme, inherit) @property def color_system(self) -> Optional[str]: """Get color system string. Returns: Optional[str]: "standard", "256" or "truecolor". """ if self._color_system is not None: return _COLOR_SYSTEMS_NAMES[self._color_system] else: return None @property def encoding(self) -> str: """Get the encoding of the console file, e.g. ``"utf-8"``. Returns: str: A standard encoding string. """ return (getattr(self.file, "encoding", "utf-8") or "utf-8").lower() @property def is_terminal(self) -> bool: """Check if the console is writing to a terminal. Returns: bool: True if the console writing to a device capable of understanding escape sequences, otherwise False. """ # If dev has explicitly set this value, return it if self._force_terminal is not None: return self._force_terminal # Fudge for Idle if hasattr(sys.stdin, "__module__") and sys.stdin.__module__.startswith( "idlelib" ):
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
true
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/styled.py
rich/styled.py
from typing import TYPE_CHECKING from .measure import Measurement from .segment import Segment from .style import StyleType if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderResult, RenderableType class Styled: """Apply a style to a renderable. Args: renderable (RenderableType): Any renderable. style (StyleType): A style to apply across the entire renderable. """ def __init__(self, renderable: "RenderableType", style: "StyleType") -> None: self.renderable = renderable self.style = style def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": style = console.get_style(self.style) rendered_segments = console.render(self.renderable, options) segments = Segment.apply_style(rendered_segments, style) return segments def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> Measurement: return Measurement.get(console, options, self.renderable) if __name__ == "__main__": # pragma: no cover from rich import print from rich.panel import Panel panel = Styled(Panel("hello"), "on blue") print(panel)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/cells.py
rich/cells.py
from __future__ import annotations from functools import lru_cache from typing import Callable from ._cell_widths import CELL_WIDTHS # Ranges of unicode ordinals that produce a 1-cell wide character # This is non-exhaustive, but covers most common Western characters _SINGLE_CELL_UNICODE_RANGES: list[tuple[int, int]] = [ (0x20, 0x7E), # Latin (excluding non-printable) (0xA0, 0xAC), (0xAE, 0x002FF), (0x00370, 0x00482), # Greek / Cyrillic (0x02500, 0x025FC), # Box drawing, box elements, geometric shapes (0x02800, 0x028FF), # Braille ] # A set of characters that are a single cell wide _SINGLE_CELLS = frozenset( [ character for _start, _end in _SINGLE_CELL_UNICODE_RANGES for character in map(chr, range(_start, _end + 1)) ] ) # When called with a string this will return True if all # characters are single-cell, otherwise False _is_single_cell_widths: Callable[[str], bool] = _SINGLE_CELLS.issuperset @lru_cache(4096) def cached_cell_len(text: str) -> int: """Get the number of cells required to display text. This method always caches, which may use up a lot of memory. It is recommended to use `cell_len` over this method. Args: text (str): Text to display. Returns: int: Get the number of cells required to display text. """ if _is_single_cell_widths(text): return len(text) return sum(map(get_character_cell_size, text)) def cell_len(text: str, _cell_len: Callable[[str], int] = cached_cell_len) -> int: """Get the number of cells required to display text. Args: text (str): Text to display. Returns: int: Get the number of cells required to display text. """ if len(text) < 512: return _cell_len(text) if _is_single_cell_widths(text): return len(text) return sum(map(get_character_cell_size, text)) @lru_cache(maxsize=4096) def get_character_cell_size(character: str) -> int: """Get the cell size of a character. Args: character (str): A single character. Returns: int: Number of cells (0, 1 or 2) occupied by that character. """ codepoint = ord(character) _table = CELL_WIDTHS lower_bound = 0 upper_bound = len(_table) - 1 index = (lower_bound + upper_bound) // 2 while True: start, end, width = _table[index] if codepoint < start: upper_bound = index - 1 elif codepoint > end: lower_bound = index + 1 else: return 0 if width == -1 else width if upper_bound < lower_bound: break index = (lower_bound + upper_bound) // 2 return 1 def set_cell_size(text: str, total: int) -> str: """Set the length of a string to fit within given number of cells.""" if _is_single_cell_widths(text): size = len(text) if size < total: return text + " " * (total - size) return text[:total] if total <= 0: return "" cell_size = cell_len(text) if cell_size == total: return text if cell_size < total: return text + " " * (total - cell_size) start = 0 end = len(text) # Binary search until we find the right size while True: pos = (start + end) // 2 before = text[: pos + 1] before_len = cell_len(before) if before_len == total + 1 and cell_len(before[-1]) == 2: return before[:-1] + " " if before_len == total: return before if before_len > total: end = pos else: start = pos def chop_cells( text: str, width: int, ) -> list[str]: """Split text into lines such that each line fits within the available (cell) width. Args: text: The text to fold such that it fits in the given width. width: The width available (number of cells). Returns: A list of strings such that each string in the list has cell width less than or equal to the available width. """ _get_character_cell_size = get_character_cell_size lines: list[list[str]] = [[]] append_new_line = lines.append append_to_last_line = lines[-1].append total_width = 0 for character in text: cell_width = _get_character_cell_size(character) char_doesnt_fit = total_width + cell_width > width if char_doesnt_fit: append_new_line([character]) append_to_last_line = lines[-1].append total_width = cell_width else: append_to_last_line(character) total_width += cell_width return ["".join(line) for line in lines] if __name__ == "__main__": # pragma: no cover print(get_character_cell_size("😽")) for line in chop_cells("""这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑。""", 8): print(line) for n in range(80, 1, -1): print(set_cell_size("""这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑。""", n) + "|") print("x" * n)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_emoji_replace.py
rich/_emoji_replace.py
from typing import Callable, Match, Optional import re from ._emoji_codes import EMOJI _ReStringMatch = Match[str] # regex match object _ReSubCallable = Callable[[_ReStringMatch], str] # Callable invoked by re.sub _EmojiSubMethod = Callable[[_ReSubCallable, str], str] # Sub method of a compiled re def _emoji_replace( text: str, default_variant: Optional[str] = None, _emoji_sub: _EmojiSubMethod = re.compile(r"(:(\S*?)(?:(?:\-)(emoji|text))?:)").sub, ) -> str: """Replace emoji code in text.""" get_emoji = EMOJI.__getitem__ variants = {"text": "\uFE0E", "emoji": "\uFE0F"} get_variant = variants.get default_variant_code = variants.get(default_variant, "") if default_variant else "" def do_replace(match: Match[str]) -> str: emoji_code, emoji_name, variant = match.groups() try: return get_emoji(emoji_name.lower()) + get_variant( variant, default_variant_code ) except KeyError: return emoji_code return _emoji_sub(do_replace, text)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_null_file.py
rich/_null_file.py
from types import TracebackType from typing import IO, Iterable, Iterator, List, Optional, Type class NullFile(IO[str]): def close(self) -> None: pass def isatty(self) -> bool: return False def read(self, __n: int = 1) -> str: return "" def readable(self) -> bool: return False def readline(self, __limit: int = 1) -> str: return "" def readlines(self, __hint: int = 1) -> List[str]: return [] def seek(self, __offset: int, __whence: int = 1) -> int: return 0 def seekable(self) -> bool: return False def tell(self) -> int: return 0 def truncate(self, __size: Optional[int] = 1) -> int: return 0 def writable(self) -> bool: return False def writelines(self, __lines: Iterable[str]) -> None: pass def __next__(self) -> str: return "" def __iter__(self) -> Iterator[str]: return iter([""]) def __enter__(self) -> IO[str]: return self def __exit__( self, __t: Optional[Type[BaseException]], __value: Optional[BaseException], __traceback: Optional[TracebackType], ) -> None: pass def write(self, text: str) -> int: return 0 def flush(self) -> None: pass def fileno(self) -> int: return -1 NULL_FILE = NullFile()
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/palette.py
rich/palette.py
from math import sqrt from functools import lru_cache from typing import Sequence, Tuple, TYPE_CHECKING from .color_triplet import ColorTriplet if TYPE_CHECKING: from rich.table import Table class Palette: """A palette of available colors.""" def __init__(self, colors: Sequence[Tuple[int, int, int]]): self._colors = colors def __getitem__(self, number: int) -> ColorTriplet: return ColorTriplet(*self._colors[number]) def __rich__(self) -> "Table": from rich.color import Color from rich.style import Style from rich.text import Text from rich.table import Table table = Table( "index", "RGB", "Color", title="Palette", caption=f"{len(self._colors)} colors", highlight=True, caption_justify="right", ) for index, color in enumerate(self._colors): table.add_row( str(index), repr(color), Text(" " * 16, style=Style(bgcolor=Color.from_rgb(*color))), ) return table # This is somewhat inefficient and needs caching @lru_cache(maxsize=1024) def match(self, color: Tuple[int, int, int]) -> int: """Find a color from a palette that most closely matches a given color. Args: color (Tuple[int, int, int]): RGB components in range 0 > 255. Returns: int: Index of closes matching color. """ red1, green1, blue1 = color _sqrt = sqrt get_color = self._colors.__getitem__ def get_color_distance(index: int) -> float: """Get the distance to a color.""" red2, green2, blue2 = get_color(index) red_mean = (red1 + red2) // 2 red = red1 - red2 green = green1 - green2 blue = blue1 - blue2 return _sqrt( (((512 + red_mean) * red * red) >> 8) + 4 * green * green + (((767 - red_mean) * blue * blue) >> 8) ) min_index = min(range(len(self._colors)), key=get_color_distance) return min_index if __name__ == "__main__": # pragma: no cover import colorsys from typing import Iterable from rich.color import Color from rich.console import Console, ConsoleOptions from rich.segment import Segment from rich.style import Style class ColorBox: def __rich_console__( self, console: Console, options: ConsoleOptions ) -> Iterable[Segment]: height = console.size.height - 3 for y in range(0, height): for x in range(options.max_width): h = x / options.max_width l = y / (height + 1) r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0) r2, g2, b2 = colorsys.hls_to_rgb(h, l + (1 / height / 2), 1.0) bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255) color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255) yield Segment("▄", Style(color=color, bgcolor=bgcolor)) yield Segment.line() console = Console() console.print(ColorBox())
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_loop.py
rich/_loop.py
from typing import Iterable, Tuple, TypeVar T = TypeVar("T") def loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: """Iterate and generate a tuple with a flag for first value.""" iter_values = iter(values) try: value = next(iter_values) except StopIteration: return yield True, value for value in iter_values: yield False, value def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: """Iterate and generate a tuple with a flag for last value.""" iter_values = iter(values) try: previous_value = next(iter_values) except StopIteration: return for value in iter_values: yield False, previous_value previous_value = value yield True, previous_value def loop_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]: """Iterate and generate a tuple with a flag for first and last value.""" iter_values = iter(values) try: previous_value = next(iter_values) except StopIteration: return first = True for value in iter_values: yield first, False, previous_value first = False previous_value = value yield first, True, previous_value
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/filesize.py
rich/filesize.py
"""Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2 The functions declared in this module should cover the different use cases needed to generate a string representation of a file size using several different units. Since there are many standards regarding file size units, three different functions have been implemented. See Also: * `Wikipedia: Binary prefix <https://en.wikipedia.org/wiki/Binary_prefix>`_ """ __all__ = ["decimal"] from typing import Iterable, List, Optional, Tuple def _to_str( size: int, suffixes: Iterable[str], base: int, *, precision: Optional[int] = 1, separator: Optional[str] = " ", ) -> str: if size == 1: return "1 byte" elif size < base: return f"{size:,} bytes" for i, suffix in enumerate(suffixes, 2): # noqa: B007 unit = base**i if size < unit: break return "{:,.{precision}f}{separator}{}".format( (base * size / unit), suffix, precision=precision, separator=separator, ) def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]: """Pick a suffix and base for the given size.""" for i, suffix in enumerate(suffixes): unit = base**i if size < unit * base: break return unit, suffix def decimal( size: int, *, precision: Optional[int] = 1, separator: Optional[str] = " ", ) -> str: """Convert a filesize in to a string (powers of 1000, SI prefixes). In this convention, ``1000 B = 1 kB``. This is typically the format used to advertise the storage capacity of USB flash drives and the like (*256 MB* meaning actually a storage capacity of more than *256 000 000 B*), or used by **Mac OS X** since v10.6 to report file sizes. Arguments: int (size): A file size. int (precision): The number of decimal places to include (default = 1). str (separator): The string to separate the value from the units (default = " "). Returns: `str`: A string containing a abbreviated file size and units. Example: >>> filesize.decimal(30000) '30.0 kB' >>> filesize.decimal(30000, precision=2, separator="") '30.00kB' """ return _to_str( size, ("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"), 1000, precision=precision, separator=separator, )
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/__main__.py
rich/__main__.py
import colorsys import io from time import process_time from rich import box from rich.color import Color from rich.console import Console, ConsoleOptions, Group, RenderableType, RenderResult from rich.markdown import Markdown from rich.measure import Measurement from rich.pretty import Pretty from rich.segment import Segment from rich.style import Style from rich.syntax import Syntax from rich.table import Table from rich.text import Text class ColorBox: def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: for y in range(0, 5): for x in range(options.max_width): h = x / options.max_width l = 0.1 + ((y / 5) * 0.7) r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0) r2, g2, b2 = colorsys.hls_to_rgb(h, l + 0.7 / 10, 1.0) bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255) color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255) yield Segment("▄", Style(color=color, bgcolor=bgcolor)) yield Segment.line() def __rich_measure__( self, console: "Console", options: ConsoleOptions ) -> Measurement: return Measurement(1, options.max_width) def make_test_card() -> Table: """Get a renderable that demonstrates a number of features.""" table = Table.grid(padding=1, pad_edge=True) table.title = "Rich features" table.add_column("Feature", no_wrap=True, justify="center", style="bold red") table.add_column("Demonstration") color_table = Table( box=None, expand=False, show_header=False, show_edge=False, pad_edge=False, ) color_table.add_row( ( "✓ [bold green]4-bit color[/]\n" "✓ [bold blue]8-bit color[/]\n" "✓ [bold magenta]Truecolor (16.7 million)[/]\n" "✓ [bold yellow]Dumb terminals[/]\n" "✓ [bold cyan]Automatic color conversion" ), ColorBox(), ) table.add_row("Colors", color_table) table.add_row( "Styles", "All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].", ) lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus." lorem_table = Table.grid(padding=1, collapse_padding=True) lorem_table.pad_edge = False lorem_table.add_row( Text(lorem, justify="left", style="green"), Text(lorem, justify="center", style="yellow"), Text(lorem, justify="right", style="blue"), Text(lorem, justify="full", style="red"), ) table.add_row( "Text", Group( Text.from_markup( """Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\n""" ), lorem_table, ), ) def comparison(renderable1: RenderableType, renderable2: RenderableType) -> Table: table = Table(show_header=False, pad_edge=False, box=None, expand=True) table.add_column("1", ratio=1) table.add_column("2", ratio=1) table.add_row(renderable1, renderable2) return table table.add_row( "Asian\nlanguage\nsupport", ":flag_for_china: 该库支持中文,日文和韩文文本!\n:flag_for_japan: ライブラリは中国語、日本語、韓国語のテキストをサポートしています\n:flag_for_south_korea: 이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다", ) markup_example = ( "[bold magenta]Rich[/] supports a simple [i]bbcode[/i]-like [b]markup[/b] for [yellow]color[/], [underline]style[/], and emoji! " ":+1: :apple: :ant: :bear: :baguette_bread: :bus: " ) table.add_row("Markup", markup_example) example_table = Table( show_edge=False, show_header=True, expand=False, row_styles=["none", "dim"], box=box.SIMPLE, ) example_table.add_column("[green]Date", style="green", no_wrap=True) example_table.add_column("[blue]Title", style="blue") example_table.add_column( "[cyan]Production Budget", style="cyan", justify="right", no_wrap=True, ) example_table.add_column( "[magenta]Box Office", style="magenta", justify="right", no_wrap=True, ) example_table.add_row( "Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118", ) example_table.add_row( "May 25, 2018", "[b]Solo[/]: A Star Wars Story", "$275,000,000", "$393,151,347", ) example_table.add_row( "Dec 15, 2017", "Star Wars Ep. VIII: The Last Jedi", "$262,000,000", "[bold]$1,332,539,889[/bold]", ) example_table.add_row( "May 19, 1999", "Star Wars Ep. [b]I[/b]: [i]The phantom Menace", "$115,000,000", "$1,027,044,677", ) table.add_row("Tables", example_table) code = '''\ def iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: """Iterate and generate a tuple with a flag for last value.""" iter_values = iter(values) try: previous_value = next(iter_values) except StopIteration: return for value in iter_values: yield False, previous_value previous_value = value yield True, previous_value''' pretty_data = { "foo": [ 3.1427, ( "Paul Atreides", "Vladimir Harkonnen", "Thufir Hawat", ), ], "atomic": (False, True, None), } table.add_row( "Syntax\nhighlighting\n&\npretty\nprinting", comparison( Syntax(code, "python3", line_numbers=True, indent_guides=True), Pretty(pretty_data, indent_guides=True), ), ) markdown_example = """\ # Markdown Supports much of the *markdown* __syntax__! - Headers - Basic formatting: **bold**, *italic*, `code` - Block quotes - Lists, and more... """ table.add_row( "Markdown", comparison("[cyan]" + markdown_example, Markdown(markdown_example)) ) table.add_row( "+more!", """Progress bars, columns, styled logging handler, tracebacks, etc...""", ) return table if __name__ == "__main__": # pragma: no cover from rich.panel import Panel console = Console( file=io.StringIO(), force_terminal=True, ) test_card = make_test_card() # Print once to warm cache start = process_time() console.print(test_card) pre_cache_taken = round((process_time() - start) * 1000.0, 1) console.file = io.StringIO() start = process_time() console.print(test_card) taken = round((process_time() - start) * 1000.0, 1) c = Console(record=True) c.print(test_card) console = Console() console.print(f"[dim]rendered in [not dim]{pre_cache_taken}ms[/] (cold cache)") console.print(f"[dim]rendered in [not dim]{taken}ms[/] (warm cache)") console.print() console.print( Panel.fit( "[b magenta]Hope you enjoy using Rich![/]\n\n" "Please consider sponsoring me if you get value from my work.\n\n" "Even the price of a ☕ can brighten my day!\n\n" "https://github.com/sponsors/willmcgugan", border_style="red", title="Help ensure Rich is maintained", ) )
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/scope.py
rich/scope.py
from collections.abc import Mapping from typing import TYPE_CHECKING, Any, Optional, Tuple from .highlighter import ReprHighlighter from .panel import Panel from .pretty import Pretty from .table import Table from .text import Text, TextType if TYPE_CHECKING: from .console import ConsoleRenderable def render_scope( scope: "Mapping[str, Any]", *, title: Optional[TextType] = None, sort_keys: bool = True, indent_guides: bool = False, max_length: Optional[int] = None, max_string: Optional[int] = None, ) -> "ConsoleRenderable": """Render python variables in a given scope. Args: scope (Mapping): A mapping containing variable names and values. title (str, optional): Optional title. Defaults to None. sort_keys (bool, optional): Enable sorting of items. Defaults to True. indent_guides (bool, optional): Enable indentation guides. Defaults to False. max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to None. max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None. Returns: ConsoleRenderable: A renderable object. """ highlighter = ReprHighlighter() items_table = Table.grid(padding=(0, 1), expand=False) items_table.add_column(justify="right") def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]: """Sort special variables first, then alphabetically.""" key, _ = item return (not key.startswith("__"), key.lower()) items = sorted(scope.items(), key=sort_items) if sort_keys else scope.items() for key, value in items: key_text = Text.assemble( (key, "scope.key.special" if key.startswith("__") else "scope.key"), (" =", "scope.equals"), ) items_table.add_row( key_text, Pretty( value, highlighter=highlighter, indent_guides=indent_guides, max_length=max_length, max_string=max_string, ), ) return Panel.fit( items_table, title=title, border_style="scope.border", padding=(0, 1), ) if __name__ == "__main__": # pragma: no cover from rich import print print() def test(foo: float, bar: float) -> None: list_of_things = [1, 2, 3, None, 4, True, False, "Hello World"] dict_of_things = { "version": "1.1", "method": "confirmFruitPurchase", "params": [["apple", "orange", "mangoes", "pomelo"], 1.123], "id": "194521489", } print(render_scope(locals(), title="[i]locals", sort_keys=False)) test(20.3423, 3.1427) print()
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/containers.py
rich/containers.py
from itertools import zip_longest from typing import ( TYPE_CHECKING, Iterable, Iterator, List, Optional, TypeVar, Union, overload, ) if TYPE_CHECKING: from .console import ( Console, ConsoleOptions, JustifyMethod, OverflowMethod, RenderResult, RenderableType, ) from .text import Text from .cells import cell_len from .measure import Measurement T = TypeVar("T") class Renderables: """A list subclass which renders its contents to the console.""" def __init__( self, renderables: Optional[Iterable["RenderableType"]] = None ) -> None: self._renderables: List["RenderableType"] = ( list(renderables) if renderables is not None else [] ) def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": """Console render method to insert line-breaks.""" yield from self._renderables def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> "Measurement": dimensions = [ Measurement.get(console, options, renderable) for renderable in self._renderables ] if not dimensions: return Measurement(1, 1) _min = max(dimension.minimum for dimension in dimensions) _max = max(dimension.maximum for dimension in dimensions) return Measurement(_min, _max) def append(self, renderable: "RenderableType") -> None: self._renderables.append(renderable) def __iter__(self) -> Iterable["RenderableType"]: return iter(self._renderables) class Lines: """A list subclass which can render to the console.""" def __init__(self, lines: Iterable["Text"] = ()) -> None: self._lines: List["Text"] = list(lines) def __repr__(self) -> str: return f"Lines({self._lines!r})" def __iter__(self) -> Iterator["Text"]: return iter(self._lines) @overload def __getitem__(self, index: int) -> "Text": ... @overload def __getitem__(self, index: slice) -> List["Text"]: ... def __getitem__(self, index: Union[slice, int]) -> Union["Text", List["Text"]]: return self._lines[index] def __setitem__(self, index: int, value: "Text") -> "Lines": self._lines[index] = value return self def __len__(self) -> int: return self._lines.__len__() def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": """Console render method to insert line-breaks.""" yield from self._lines def append(self, line: "Text") -> None: self._lines.append(line) def extend(self, lines: Iterable["Text"]) -> None: self._lines.extend(lines) def pop(self, index: int = -1) -> "Text": return self._lines.pop(index) def justify( self, console: "Console", width: int, justify: "JustifyMethod" = "left", overflow: "OverflowMethod" = "fold", ) -> None: """Justify and overflow text to a given width. Args: console (Console): Console instance. width (int): Number of cells available per line. justify (str, optional): Default justify method for text: "left", "center", "full" or "right". Defaults to "left". overflow (str, optional): Default overflow for text: "crop", "fold", or "ellipsis". Defaults to "fold". """ from .text import Text if justify == "left": for line in self._lines: line.truncate(width, overflow=overflow, pad=True) elif justify == "center": for line in self._lines: line.rstrip() line.truncate(width, overflow=overflow) line.pad_left((width - cell_len(line.plain)) // 2) line.pad_right(width - cell_len(line.plain)) elif justify == "right": for line in self._lines: line.rstrip() line.truncate(width, overflow=overflow) line.pad_left(width - cell_len(line.plain)) elif justify == "full": for line_index, line in enumerate(self._lines): if line_index == len(self._lines) - 1: break words = line.split(" ") words_size = sum(cell_len(word.plain) for word in words) num_spaces = len(words) - 1 spaces = [1 for _ in range(num_spaces)] index = 0 if spaces: while words_size + num_spaces < width: spaces[len(spaces) - index - 1] += 1 num_spaces += 1 index = (index + 1) % len(spaces) tokens: List[Text] = [] for index, (word, next_word) in enumerate( zip_longest(words, words[1:]) ): tokens.append(word) if index < len(spaces): style = word.get_style_at_offset(console, -1) next_style = next_word.get_style_at_offset(console, 0) space_style = style if style == next_style else line.style tokens.append(Text(" " * spaces[index], style=space_style)) self[line_index] = Text("").join(tokens)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_log_render.py
rich/_log_render.py
from datetime import datetime from typing import Iterable, List, Optional, TYPE_CHECKING, Union, Callable from .text import Text, TextType if TYPE_CHECKING: from .console import Console, ConsoleRenderable, RenderableType from .table import Table FormatTimeCallable = Callable[[datetime], Text] class LogRender: def __init__( self, show_time: bool = True, show_level: bool = False, show_path: bool = True, time_format: Union[str, FormatTimeCallable] = "[%x %X]", omit_repeated_times: bool = True, level_width: Optional[int] = 8, ) -> None: self.show_time = show_time self.show_level = show_level self.show_path = show_path self.time_format = time_format self.omit_repeated_times = omit_repeated_times self.level_width = level_width self._last_time: Optional[Text] = None def __call__( self, console: "Console", renderables: Iterable["ConsoleRenderable"], log_time: Optional[datetime] = None, time_format: Optional[Union[str, FormatTimeCallable]] = None, level: TextType = "", path: Optional[str] = None, line_no: Optional[int] = None, link_path: Optional[str] = None, ) -> "Table": from .containers import Renderables from .table import Table output = Table.grid(padding=(0, 1)) output.expand = True if self.show_time: output.add_column(style="log.time") if self.show_level: output.add_column(style="log.level", width=self.level_width) output.add_column(ratio=1, style="log.message", overflow="fold") if self.show_path and path: output.add_column(style="log.path") row: List["RenderableType"] = [] if self.show_time: log_time = log_time or console.get_datetime() time_format = time_format or self.time_format if callable(time_format): log_time_display = time_format(log_time) else: log_time_display = Text(log_time.strftime(time_format)) if log_time_display == self._last_time and self.omit_repeated_times: row.append(Text(" " * len(log_time_display))) else: row.append(log_time_display) self._last_time = log_time_display if self.show_level: row.append(level) row.append(Renderables(renderables)) if self.show_path and path: path_text = Text() path_text.append( path, style=f"link file://{link_path}" if link_path else "" ) if line_no: path_text.append(":") path_text.append( f"{line_no}", style=f"link file://{link_path}#{line_no}" if link_path else "", ) row.append(path_text) output.add_row(*row) return output if __name__ == "__main__": # pragma: no cover from rich.console import Console c = Console() c.print("[on blue]Hello", justify="right") c.log("[on blue]hello", justify="right")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/traceback.py
rich/traceback.py
import inspect import linecache import os import sys from dataclasses import dataclass, field from itertools import islice from traceback import walk_tb from types import ModuleType, TracebackType from typing import ( Any, Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Type, Union, ) from pygments.lexers import guess_lexer_for_filename from pygments.token import Comment, Keyword, Name, Number, Operator, String from pygments.token import Text as TextToken from pygments.token import Token from pygments.util import ClassNotFound from . import pretty from ._loop import loop_first_last, loop_last from .columns import Columns from .console import ( Console, ConsoleOptions, ConsoleRenderable, Group, RenderResult, group, ) from .constrain import Constrain from .highlighter import RegexHighlighter, ReprHighlighter from .panel import Panel from .scope import render_scope from .style import Style from .syntax import Syntax, SyntaxPosition from .text import Text from .theme import Theme WINDOWS = sys.platform == "win32" LOCALS_MAX_LENGTH = 10 LOCALS_MAX_STRING = 80 def _iter_syntax_lines( start: SyntaxPosition, end: SyntaxPosition ) -> Iterable[Tuple[int, int, int]]: """Yield start and end positions per line. Args: start: Start position. end: End position. Returns: Iterable of (LINE, COLUMN1, COLUMN2). """ line1, column1 = start line2, column2 = end if line1 == line2: yield line1, column1, column2 else: for first, last, line_no in loop_first_last(range(line1, line2 + 1)): if first: yield line_no, column1, -1 elif last: yield line_no, 0, column2 else: yield line_no, 0, -1 def install( *, console: Optional[Console] = None, width: Optional[int] = 100, code_width: Optional[int] = 88, extra_lines: int = 3, theme: Optional[str] = None, word_wrap: bool = False, show_locals: bool = False, locals_max_length: int = LOCALS_MAX_LENGTH, locals_max_string: int = LOCALS_MAX_STRING, locals_hide_dunder: bool = True, locals_hide_sunder: Optional[bool] = None, indent_guides: bool = True, suppress: Iterable[Union[str, ModuleType]] = (), max_frames: int = 100, ) -> Callable[[Type[BaseException], BaseException, Optional[TracebackType]], Any]: """Install a rich traceback handler. Once installed, any tracebacks will be printed with syntax highlighting and rich formatting. Args: console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance. width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100. code_width (Optional[int], optional): Code width (in characters) of traceback. Defaults to 88. extra_lines (int, optional): Extra lines of code. Defaults to 3. theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick a theme appropriate for the platform. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False. show_locals (bool, optional): Enable display of local variables. Defaults to False. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True. locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False. indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True. suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. Returns: Callable: The previous exception handler that was replaced. """ traceback_console = Console(stderr=True) if console is None else console locals_hide_sunder = ( True if (traceback_console.is_jupyter and locals_hide_sunder is None) else locals_hide_sunder ) def excepthook( type_: Type[BaseException], value: BaseException, traceback: Optional[TracebackType], ) -> None: exception_traceback = Traceback.from_exception( type_, value, traceback, width=width, code_width=code_width, extra_lines=extra_lines, theme=theme, word_wrap=word_wrap, show_locals=show_locals, locals_max_length=locals_max_length, locals_max_string=locals_max_string, locals_hide_dunder=locals_hide_dunder, locals_hide_sunder=bool(locals_hide_sunder), indent_guides=indent_guides, suppress=suppress, max_frames=max_frames, ) traceback_console.print(exception_traceback) def ipy_excepthook_closure(ip: Any) -> None: # pragma: no cover tb_data = {} # store information about showtraceback call default_showtraceback = ip.showtraceback # keep reference of default traceback def ipy_show_traceback(*args: Any, **kwargs: Any) -> None: """wrap the default ip.showtraceback to store info for ip._showtraceback""" nonlocal tb_data tb_data = kwargs default_showtraceback(*args, **kwargs) def ipy_display_traceback( *args: Any, is_syntax: bool = False, **kwargs: Any ) -> None: """Internally called traceback from ip._showtraceback""" nonlocal tb_data exc_tuple = ip._get_exc_info() # do not display trace on syntax error tb: Optional[TracebackType] = None if is_syntax else exc_tuple[2] # determine correct tb_offset compiled = tb_data.get("running_compiled_code", False) tb_offset = tb_data.get("tb_offset") if tb_offset is None: tb_offset = 1 if compiled else 0 # remove ipython internal frames from trace with tb_offset for _ in range(tb_offset): if tb is None: break tb = tb.tb_next excepthook(exc_tuple[0], exc_tuple[1], tb) tb_data = {} # clear data upon usage # replace _showtraceback instead of showtraceback to allow ipython features such as debugging to work # this is also what the ipython docs recommends to modify when subclassing InteractiveShell ip._showtraceback = ipy_display_traceback # add wrapper to capture tb_data ip.showtraceback = ipy_show_traceback ip.showsyntaxerror = lambda *args, **kwargs: ipy_display_traceback( *args, is_syntax=True, **kwargs ) try: # pragma: no cover # if within ipython, use customized traceback ip = get_ipython() # type: ignore[name-defined] ipy_excepthook_closure(ip) return sys.excepthook except Exception: # otherwise use default system hook old_excepthook = sys.excepthook sys.excepthook = excepthook return old_excepthook @dataclass class Frame: filename: str lineno: int name: str line: str = "" locals: Optional[Dict[str, pretty.Node]] = None last_instruction: Optional[Tuple[Tuple[int, int], Tuple[int, int]]] = None @dataclass class _SyntaxError: offset: int filename: str line: str lineno: int msg: str notes: List[str] = field(default_factory=list) @dataclass class Stack: exc_type: str exc_value: str syntax_error: Optional[_SyntaxError] = None is_cause: bool = False frames: List[Frame] = field(default_factory=list) notes: List[str] = field(default_factory=list) is_group: bool = False exceptions: List["Trace"] = field(default_factory=list) @dataclass class Trace: stacks: List[Stack] class PathHighlighter(RegexHighlighter): highlights = [r"(?P<dim>.*/)(?P<bold>.+)"] class Traceback: """A Console renderable that renders a traceback. Args: trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses the last exception. width (Optional[int], optional): Number of characters used to traceback. Defaults to 100. code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88. extra_lines (int, optional): Additional lines of code to render. Defaults to 3. theme (str, optional): Override pygments theme used in traceback. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False. show_locals (bool, optional): Enable display of local variables. Defaults to False. indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True. locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False. suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. """ LEXERS = { "": "text", ".py": "python", ".pxd": "cython", ".pyx": "cython", ".pxi": "pyrex", } def __init__( self, trace: Optional[Trace] = None, *, width: Optional[int] = 100, code_width: Optional[int] = 88, extra_lines: int = 3, theme: Optional[str] = None, word_wrap: bool = False, show_locals: bool = False, locals_max_length: int = LOCALS_MAX_LENGTH, locals_max_string: int = LOCALS_MAX_STRING, locals_hide_dunder: bool = True, locals_hide_sunder: bool = False, indent_guides: bool = True, suppress: Iterable[Union[str, ModuleType]] = (), max_frames: int = 100, ): if trace is None: exc_type, exc_value, traceback = sys.exc_info() if exc_type is None or exc_value is None or traceback is None: raise ValueError( "Value for 'trace' required if not called in except: block" ) trace = self.extract( exc_type, exc_value, traceback, show_locals=show_locals ) self.trace = trace self.width = width self.code_width = code_width self.extra_lines = extra_lines self.theme = Syntax.get_theme(theme or "ansi_dark") self.word_wrap = word_wrap self.show_locals = show_locals self.indent_guides = indent_guides self.locals_max_length = locals_max_length self.locals_max_string = locals_max_string self.locals_hide_dunder = locals_hide_dunder self.locals_hide_sunder = locals_hide_sunder self.suppress: Sequence[str] = [] for suppress_entity in suppress: if not isinstance(suppress_entity, str): assert ( suppress_entity.__file__ is not None ), f"{suppress_entity!r} must be a module with '__file__' attribute" path = os.path.dirname(suppress_entity.__file__) else: path = suppress_entity path = os.path.normpath(os.path.abspath(path)) self.suppress.append(path) self.max_frames = max(4, max_frames) if max_frames > 0 else 0 @classmethod def from_exception( cls, exc_type: Type[Any], exc_value: BaseException, traceback: Optional[TracebackType], *, width: Optional[int] = 100, code_width: Optional[int] = 88, extra_lines: int = 3, theme: Optional[str] = None, word_wrap: bool = False, show_locals: bool = False, locals_max_length: int = LOCALS_MAX_LENGTH, locals_max_string: int = LOCALS_MAX_STRING, locals_hide_dunder: bool = True, locals_hide_sunder: bool = False, indent_guides: bool = True, suppress: Iterable[Union[str, ModuleType]] = (), max_frames: int = 100, ) -> "Traceback": """Create a traceback from exception info Args: exc_type (Type[BaseException]): Exception type. exc_value (BaseException): Exception value. traceback (TracebackType): Python Traceback object. width (Optional[int], optional): Number of characters used to traceback. Defaults to 100. code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88. extra_lines (int, optional): Additional lines of code to render. Defaults to 3. theme (str, optional): Override pygments theme used in traceback. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False. show_locals (bool, optional): Enable display of local variables. Defaults to False. indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True. locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False. suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. Returns: Traceback: A Traceback instance that may be printed. """ rich_traceback = cls.extract( exc_type, exc_value, traceback, show_locals=show_locals, locals_max_length=locals_max_length, locals_max_string=locals_max_string, locals_hide_dunder=locals_hide_dunder, locals_hide_sunder=locals_hide_sunder, ) return cls( rich_traceback, width=width, code_width=code_width, extra_lines=extra_lines, theme=theme, word_wrap=word_wrap, show_locals=show_locals, indent_guides=indent_guides, locals_max_length=locals_max_length, locals_max_string=locals_max_string, locals_hide_dunder=locals_hide_dunder, locals_hide_sunder=locals_hide_sunder, suppress=suppress, max_frames=max_frames, ) @classmethod def extract( cls, exc_type: Type[BaseException], exc_value: BaseException, traceback: Optional[TracebackType], *, show_locals: bool = False, locals_max_length: int = LOCALS_MAX_LENGTH, locals_max_string: int = LOCALS_MAX_STRING, locals_hide_dunder: bool = True, locals_hide_sunder: bool = False, _visited_exceptions: Optional[Set[BaseException]] = None, ) -> Trace: """Extract traceback information. Args: exc_type (Type[BaseException]): Exception type. exc_value (BaseException): Exception value. traceback (TracebackType): Python Traceback object. show_locals (bool, optional): Enable display of local variables. Defaults to False. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True. locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False. Returns: Trace: A Trace instance which you can use to construct a `Traceback`. """ stacks: List[Stack] = [] is_cause = False from rich import _IMPORT_CWD notes: List[str] = getattr(exc_value, "__notes__", None) or [] grouped_exceptions: Set[BaseException] = ( set() if _visited_exceptions is None else _visited_exceptions ) def safe_str(_object: Any) -> str: """Don't allow exceptions from __str__ to propagate.""" try: return str(_object) except Exception: return "<exception str() failed>" while True: stack = Stack( exc_type=safe_str(exc_type.__name__), exc_value=safe_str(exc_value), is_cause=is_cause, notes=notes, ) if sys.version_info >= (3, 11): if isinstance(exc_value, (BaseExceptionGroup, ExceptionGroup)): stack.is_group = True for exception in exc_value.exceptions: if exception in grouped_exceptions: continue grouped_exceptions.add(exception) stack.exceptions.append( Traceback.extract( type(exception), exception, exception.__traceback__, show_locals=show_locals, locals_max_length=locals_max_length, locals_hide_dunder=locals_hide_dunder, locals_hide_sunder=locals_hide_sunder, _visited_exceptions=grouped_exceptions, ) ) if isinstance(exc_value, SyntaxError): stack.syntax_error = _SyntaxError( offset=exc_value.offset or 0, filename=exc_value.filename or "?", lineno=exc_value.lineno or 0, line=exc_value.text or "", msg=exc_value.msg, notes=notes, ) stacks.append(stack) append = stack.frames.append def get_locals( iter_locals: Iterable[Tuple[str, object]], ) -> Iterable[Tuple[str, object]]: """Extract locals from an iterator of key pairs.""" if not (locals_hide_dunder or locals_hide_sunder): yield from iter_locals return for key, value in iter_locals: if locals_hide_dunder and key.startswith("__"): continue if locals_hide_sunder and key.startswith("_"): continue yield key, value for frame_summary, line_no in walk_tb(traceback): filename = frame_summary.f_code.co_filename last_instruction: Optional[Tuple[Tuple[int, int], Tuple[int, int]]] last_instruction = None if sys.version_info >= (3, 11): instruction_index = frame_summary.f_lasti // 2 instruction_position = next( islice( frame_summary.f_code.co_positions(), instruction_index, instruction_index + 1, ) ) ( start_line, end_line, start_column, end_column, ) = instruction_position if ( start_line is not None and end_line is not None and start_column is not None and end_column is not None ): last_instruction = ( (start_line, start_column), (end_line, end_column), ) if filename and not filename.startswith("<"): if not os.path.isabs(filename): filename = os.path.join(_IMPORT_CWD, filename) if frame_summary.f_locals.get("_rich_traceback_omit", False): continue frame = Frame( filename=filename or "?", lineno=line_no, name=frame_summary.f_code.co_name, locals=( { key: pretty.traverse( value, max_length=locals_max_length, max_string=locals_max_string, ) for key, value in get_locals(frame_summary.f_locals.items()) if not (inspect.isfunction(value) or inspect.isclass(value)) } if show_locals else None ), last_instruction=last_instruction, ) append(frame) if frame_summary.f_locals.get("_rich_traceback_guard", False): del stack.frames[:] if not grouped_exceptions: cause = getattr(exc_value, "__cause__", None) if cause is not None and cause is not exc_value: exc_type = cause.__class__ exc_value = cause # __traceback__ can be None, e.g. for exceptions raised by the # 'multiprocessing' module traceback = cause.__traceback__ is_cause = True continue cause = exc_value.__context__ if cause is not None and not getattr( exc_value, "__suppress_context__", False ): exc_type = cause.__class__ exc_value = cause traceback = cause.__traceback__ is_cause = False continue # No cover, code is reached but coverage doesn't recognize it. break # pragma: no cover trace = Trace(stacks=stacks) return trace def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: theme = self.theme background_style = theme.get_background_style() token_style = theme.get_style_for_token traceback_theme = Theme( { "pretty": token_style(TextToken), "pygments.text": token_style(Token), "pygments.string": token_style(String), "pygments.function": token_style(Name.Function), "pygments.number": token_style(Number), "repr.indent": token_style(Comment) + Style(dim=True), "repr.str": token_style(String), "repr.brace": token_style(TextToken) + Style(bold=True), "repr.number": token_style(Number), "repr.bool_true": token_style(Keyword.Constant), "repr.bool_false": token_style(Keyword.Constant), "repr.none": token_style(Keyword.Constant), "scope.border": token_style(String.Delimiter), "scope.equals": token_style(Operator), "scope.key": token_style(Name), "scope.key.special": token_style(Name.Constant) + Style(dim=True), }, inherit=False, ) highlighter = ReprHighlighter() @group() def render_stack(stack: Stack, last: bool) -> RenderResult: if stack.frames: stack_renderable: ConsoleRenderable = Panel( self._render_stack(stack), title="[traceback.title]Traceback [dim](most recent call last)", style=background_style, border_style="traceback.border", expand=True, padding=(0, 1), ) stack_renderable = Constrain(stack_renderable, self.width) with console.use_theme(traceback_theme): yield stack_renderable if stack.syntax_error is not None: with console.use_theme(traceback_theme): yield Constrain( Panel( self._render_syntax_error(stack.syntax_error), style=background_style, border_style="traceback.border.syntax_error", expand=True, padding=(0, 1), width=self.width, ), self.width, ) yield Text.assemble( (f"{stack.exc_type}: ", "traceback.exc_type"), highlighter(stack.syntax_error.msg), ) elif stack.exc_value: yield Text.assemble( (f"{stack.exc_type}: ", "traceback.exc_type"), highlighter(stack.exc_value), ) else: yield Text.assemble((f"{stack.exc_type}", "traceback.exc_type")) for note in stack.notes: yield Text.assemble(("[NOTE] ", "traceback.note"), highlighter(note)) if stack.is_group: for group_no, group_exception in enumerate(stack.exceptions, 1): grouped_exceptions: List[Group] = [] for group_last, group_stack in loop_last(group_exception.stacks): grouped_exceptions.append(render_stack(group_stack, group_last)) yield "" yield Constrain( Panel( Group(*grouped_exceptions), title=f"Sub-exception #{group_no}", border_style="traceback.group.border", ), self.width, ) if not last: if stack.is_cause: yield Text.from_markup( "\n[i]The above exception was the direct cause of the following exception:\n", ) else: yield Text.from_markup( "\n[i]During handling of the above exception, another exception occurred:\n", ) for last, stack in loop_last(reversed(self.trace.stacks)): yield render_stack(stack, last) @group() def _render_syntax_error(self, syntax_error: _SyntaxError) -> RenderResult: highlighter = ReprHighlighter() path_highlighter = PathHighlighter() if syntax_error.filename != "<stdin>": if os.path.exists(syntax_error.filename): text = Text.assemble( (f" {syntax_error.filename}", "pygments.string"), (":", "pygments.text"), (str(syntax_error.lineno), "pygments.number"), style="pygments.text", ) yield path_highlighter(text) syntax_error_text = highlighter(syntax_error.line.rstrip()) syntax_error_text.no_wrap = True offset = min(syntax_error.offset - 1, len(syntax_error_text)) syntax_error_text.stylize("bold underline", offset, offset) syntax_error_text += Text.from_markup( "\n" + " " * offset + "[traceback.offset]▲[/]", style="pygments.text", ) yield syntax_error_text @classmethod def _guess_lexer(cls, filename: str, code: str) -> str: ext = os.path.splitext(filename)[-1] if not ext: # No extension, look at first line to see if it is a hashbang # Note, this is an educated guess and not a guarantee # If it fails, the only downside is that the code is highlighted strangely new_line_index = code.index("\n") first_line = code[:new_line_index] if new_line_index != -1 else code if first_line.startswith("#!") and "python" in first_line.lower(): return "python" try: return cls.LEXERS.get(ext) or guess_lexer_for_filename(filename, code).name except ClassNotFound: return "text" @group() def _render_stack(self, stack: Stack) -> RenderResult: path_highlighter = PathHighlighter() theme = self.theme def render_locals(frame: Frame) -> Iterable[ConsoleRenderable]: if frame.locals: yield render_scope( frame.locals, title="locals", indent_guides=self.indent_guides, max_length=self.locals_max_length, max_string=self.locals_max_string, ) exclude_frames: Optional[range] = None if self.max_frames != 0: exclude_frames = range( self.max_frames // 2, len(stack.frames) - self.max_frames // 2, ) excluded = False for frame_index, frame in enumerate(stack.frames): if exclude_frames and frame_index in exclude_frames: excluded = True continue if excluded: assert exclude_frames is not None yield Text( f"\n... {len(exclude_frames)} frames hidden ...", justify="center", style="traceback.error", ) excluded = False first = frame_index == 0 frame_filename = frame.filename suppressed = any(frame_filename.startswith(path) for path in self.suppress) if os.path.exists(frame.filename): text = Text.assemble( path_highlighter(Text(frame.filename, style="pygments.string")), (":", "pygments.text"), (str(frame.lineno), "pygments.number"), " in ", (frame.name, "pygments.function"), style="pygments.text", ) else: text = Text.assemble( "in ", (frame.name, "pygments.function"), (":", "pygments.text"), (str(frame.lineno), "pygments.number"), style="pygments.text", ) if not frame.filename.startswith("<") and not first: yield "" yield text if frame.filename.startswith("<"): yield from render_locals(frame) continue if not suppressed: try: code_lines = linecache.getlines(frame.filename) code = "".join(code_lines) if not code: # code may be an empty string if the file doesn't exist, OR # if the traceback filename is generated dynamically continue lexer_name = self._guess_lexer(frame.filename, code) syntax = Syntax( code,
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
true
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/prompt.py
rich/prompt.py
from typing import Any, Generic, List, Optional, TextIO, TypeVar, Union, overload from . import get_console from .console import Console from .text import Text, TextType PromptType = TypeVar("PromptType") DefaultType = TypeVar("DefaultType") class PromptError(Exception): """Exception base class for prompt related errors.""" class InvalidResponse(PromptError): """Exception to indicate a response was invalid. Raise this within process_response() to indicate an error and provide an error message. Args: message (Union[str, Text]): Error message. """ def __init__(self, message: TextType) -> None: self.message = message def __rich__(self) -> TextType: return self.message class PromptBase(Generic[PromptType]): """Ask the user for input until a valid response is received. This is the base class, see one of the concrete classes for examples. Args: prompt (TextType, optional): Prompt text. Defaults to "". console (Console, optional): A Console instance or None to use global console. Defaults to None. password (bool, optional): Enable password input. Defaults to False. choices (List[str], optional): A list of valid choices. Defaults to None. case_sensitive (bool, optional): Matching of choices should be case-sensitive. Defaults to True. show_default (bool, optional): Show default in prompt. Defaults to True. show_choices (bool, optional): Show choices in prompt. Defaults to True. """ response_type: type = str validate_error_message = "[prompt.invalid]Please enter a valid value" illegal_choice_message = ( "[prompt.invalid.choice]Please select one of the available options" ) prompt_suffix = ": " choices: Optional[List[str]] = None def __init__( self, prompt: TextType = "", *, console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, case_sensitive: bool = True, show_default: bool = True, show_choices: bool = True, ) -> None: self.console = console or get_console() self.prompt = ( Text.from_markup(prompt, style="prompt") if isinstance(prompt, str) else prompt ) self.password = password if choices is not None: self.choices = choices self.case_sensitive = case_sensitive self.show_default = show_default self.show_choices = show_choices @classmethod @overload def ask( cls, prompt: TextType = "", *, console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, case_sensitive: bool = True, show_default: bool = True, show_choices: bool = True, default: DefaultType, stream: Optional[TextIO] = None, ) -> Union[DefaultType, PromptType]: ... @classmethod @overload def ask( cls, prompt: TextType = "", *, console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, case_sensitive: bool = True, show_default: bool = True, show_choices: bool = True, stream: Optional[TextIO] = None, ) -> PromptType: ... @classmethod def ask( cls, prompt: TextType = "", *, console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, case_sensitive: bool = True, show_default: bool = True, show_choices: bool = True, default: Any = ..., stream: Optional[TextIO] = None, ) -> Any: """Shortcut to construct and run a prompt loop and return the result. Example: >>> filename = Prompt.ask("Enter a filename") Args: prompt (TextType, optional): Prompt text. Defaults to "". console (Console, optional): A Console instance or None to use global console. Defaults to None. password (bool, optional): Enable password input. Defaults to False. choices (List[str], optional): A list of valid choices. Defaults to None. case_sensitive (bool, optional): Matching of choices should be case-sensitive. Defaults to True. show_default (bool, optional): Show default in prompt. Defaults to True. show_choices (bool, optional): Show choices in prompt. Defaults to True. stream (TextIO, optional): Optional text file open for reading to get input. Defaults to None. """ _prompt = cls( prompt, console=console, password=password, choices=choices, case_sensitive=case_sensitive, show_default=show_default, show_choices=show_choices, ) return _prompt(default=default, stream=stream) def render_default(self, default: DefaultType) -> Text: """Turn the supplied default in to a Text instance. Args: default (DefaultType): Default value. Returns: Text: Text containing rendering of default value. """ return Text(f"({default})", "prompt.default") def make_prompt(self, default: DefaultType) -> Text: """Make prompt text. Args: default (DefaultType): Default value. Returns: Text: Text to display in prompt. """ prompt = self.prompt.copy() prompt.end = "" if self.show_choices and self.choices: _choices = "/".join(self.choices) choices = f"[{_choices}]" prompt.append(" ") prompt.append(choices, "prompt.choices") if ( default != ... and self.show_default and isinstance(default, (str, self.response_type)) ): prompt.append(" ") _default = self.render_default(default) prompt.append(_default) prompt.append(self.prompt_suffix) return prompt @classmethod def get_input( cls, console: Console, prompt: TextType, password: bool, stream: Optional[TextIO] = None, ) -> str: """Get input from user. Args: console (Console): Console instance. prompt (TextType): Prompt text. password (bool): Enable password entry. Returns: str: String from user. """ return console.input(prompt, password=password, stream=stream) def check_choice(self, value: str) -> bool: """Check value is in the list of valid choices. Args: value (str): Value entered by user. Returns: bool: True if choice was valid, otherwise False. """ assert self.choices is not None if self.case_sensitive: return value.strip() in self.choices return value.strip().lower() in [choice.lower() for choice in self.choices] def process_response(self, value: str) -> PromptType: """Process response from user, convert to prompt type. Args: value (str): String typed by user. Raises: InvalidResponse: If ``value`` is invalid. Returns: PromptType: The value to be returned from ask method. """ value = value.strip() try: return_value: PromptType = self.response_type(value) except ValueError: raise InvalidResponse(self.validate_error_message) if self.choices is not None: if not self.check_choice(value): raise InvalidResponse(self.illegal_choice_message) if not self.case_sensitive: # return the original choice, not the lower case version return_value = self.response_type( self.choices[ [choice.lower() for choice in self.choices].index(value.lower()) ] ) return return_value def on_validate_error(self, value: str, error: InvalidResponse) -> None: """Called to handle validation error. Args: value (str): String entered by user. error (InvalidResponse): Exception instance the initiated the error. """ self.console.print(error) def pre_prompt(self) -> None: """Hook to display something before the prompt.""" @overload def __call__(self, *, stream: Optional[TextIO] = None) -> PromptType: ... @overload def __call__( self, *, default: DefaultType, stream: Optional[TextIO] = None ) -> Union[PromptType, DefaultType]: ... def __call__(self, *, default: Any = ..., stream: Optional[TextIO] = None) -> Any: """Run the prompt loop. Args: default (Any, optional): Optional default value. Returns: PromptType: Processed value. """ while True: self.pre_prompt() prompt = self.make_prompt(default) value = self.get_input(self.console, prompt, self.password, stream=stream) if value == "" and default != ...: return default try: return_value = self.process_response(value) except InvalidResponse as error: self.on_validate_error(value, error) continue else: return return_value class Prompt(PromptBase[str]): """A prompt that returns a str. Example: >>> name = Prompt.ask("Enter your name") """ response_type = str class IntPrompt(PromptBase[int]): """A prompt that returns an integer. Example: >>> burrito_count = IntPrompt.ask("How many burritos do you want to order") """ response_type = int validate_error_message = "[prompt.invalid]Please enter a valid integer number" class FloatPrompt(PromptBase[float]): """A prompt that returns a float. Example: >>> temperature = FloatPrompt.ask("Enter desired temperature") """ response_type = float validate_error_message = "[prompt.invalid]Please enter a number" class Confirm(PromptBase[bool]): """A yes / no confirmation prompt. Example: >>> if Confirm.ask("Continue"): run_job() """ response_type = bool validate_error_message = "[prompt.invalid]Please enter Y or N" choices: List[str] = ["y", "n"] def render_default(self, default: DefaultType) -> Text: """Render the default as (y) or (n) rather than True/False.""" yes, no = self.choices return Text(f"({yes})" if default else f"({no})", style="prompt.default") def process_response(self, value: str) -> bool: """Convert choices to a bool.""" value = value.strip().lower() if value not in self.choices: raise InvalidResponse(self.validate_error_message) return value == self.choices[0] if __name__ == "__main__": # pragma: no cover from rich import print if Confirm.ask("Run [i]prompt[/i] tests?", default=True): while True: result = IntPrompt.ask( ":rocket: Enter a number between [b]1[/b] and [b]10[/b]", default=5 ) if result >= 1 and result <= 10: break print(":pile_of_poo: [prompt.invalid]Number must be between 1 and 10") print(f"number={result}") while True: password = Prompt.ask( "Please enter a password [cyan](must be at least 5 characters)", password=True, ) if len(password) >= 5: break print("[prompt.invalid]password too short") print(f"password={password!r}") fruit = Prompt.ask("Enter a fruit", choices=["apple", "orange", "pear"]) print(f"fruit={fruit!r}") doggie = Prompt.ask( "What's the best Dog? (Case INSENSITIVE)", choices=["Border Terrier", "Collie", "Labradoodle"], case_sensitive=False, ) print(f"doggie={doggie!r}") else: print("[b]OK :loudly_crying_face:")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/terminal_theme.py
rich/terminal_theme.py
from typing import List, Optional, Tuple from .color_triplet import ColorTriplet from .palette import Palette _ColorTuple = Tuple[int, int, int] class TerminalTheme: """A color theme used when exporting console content. Args: background (Tuple[int, int, int]): The background color. foreground (Tuple[int, int, int]): The foreground (text) color. normal (List[Tuple[int, int, int]]): A list of 8 normal intensity colors. bright (List[Tuple[int, int, int]], optional): A list of 8 bright colors, or None to repeat normal intensity. Defaults to None. """ def __init__( self, background: _ColorTuple, foreground: _ColorTuple, normal: List[_ColorTuple], bright: Optional[List[_ColorTuple]] = None, ) -> None: self.background_color = ColorTriplet(*background) self.foreground_color = ColorTriplet(*foreground) self.ansi_colors = Palette(normal + (bright or normal)) DEFAULT_TERMINAL_THEME = TerminalTheme( (255, 255, 255), (0, 0, 0), [ (0, 0, 0), (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128), (0, 128, 128), (192, 192, 192), ], [ (128, 128, 128), (255, 0, 0), (0, 255, 0), (255, 255, 0), (0, 0, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255), ], ) MONOKAI = TerminalTheme( (12, 12, 12), (217, 217, 217), [ (26, 26, 26), (244, 0, 95), (152, 224, 36), (253, 151, 31), (157, 101, 255), (244, 0, 95), (88, 209, 235), (196, 197, 181), (98, 94, 76), ], [ (244, 0, 95), (152, 224, 36), (224, 213, 97), (157, 101, 255), (244, 0, 95), (88, 209, 235), (246, 246, 239), ], ) DIMMED_MONOKAI = TerminalTheme( (25, 25, 25), (185, 188, 186), [ (58, 61, 67), (190, 63, 72), (135, 154, 59), (197, 166, 53), (79, 118, 161), (133, 92, 141), (87, 143, 164), (185, 188, 186), (136, 137, 135), ], [ (251, 0, 31), (15, 114, 47), (196, 112, 51), (24, 109, 227), (251, 0, 103), (46, 112, 109), (253, 255, 185), ], ) NIGHT_OWLISH = TerminalTheme( (255, 255, 255), (64, 63, 83), [ (1, 22, 39), (211, 66, 62), (42, 162, 152), (218, 170, 1), (72, 118, 214), (64, 63, 83), (8, 145, 106), (122, 129, 129), (122, 129, 129), ], [ (247, 110, 110), (73, 208, 197), (218, 194, 107), (92, 167, 228), (105, 112, 152), (0, 201, 144), (152, 159, 177), ], ) SVG_EXPORT_THEME = TerminalTheme( (41, 41, 41), (197, 200, 198), [ (75, 78, 85), (204, 85, 90), (152, 168, 75), (208, 179, 68), (96, 138, 177), (152, 114, 159), (104, 160, 179), (197, 200, 198), (154, 155, 153), ], [ (255, 38, 39), (0, 130, 61), (208, 132, 66), (25, 132, 233), (255, 44, 122), (57, 130, 128), (253, 253, 197), ], )
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/errors.py
rich/errors.py
class ConsoleError(Exception): """An error in console operation.""" class StyleError(Exception): """An error in styles.""" class StyleSyntaxError(ConsoleError): """Style was badly formatted.""" class MissingStyle(StyleError): """No such style.""" class StyleStackError(ConsoleError): """Style stack is invalid.""" class NotRenderableError(ConsoleError): """Object is not renderable.""" class MarkupError(ConsoleError): """Markup was badly formatted.""" class LiveError(ConsoleError): """Error related to Live display.""" class NoAltScreen(ConsoleError): """Alt screen mode was required."""
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/theme.py
rich/theme.py
import configparser from typing import IO, Dict, List, Mapping, Optional from .default_styles import DEFAULT_STYLES from .style import Style, StyleType class Theme: """A container for style information, used by :class:`~rich.console.Console`. Args: styles (Dict[str, Style], optional): A mapping of style names on to styles. Defaults to None for a theme with no styles. inherit (bool, optional): Inherit default styles. Defaults to True. """ styles: Dict[str, Style] def __init__( self, styles: Optional[Mapping[str, StyleType]] = None, inherit: bool = True ): self.styles = DEFAULT_STYLES.copy() if inherit else {} if styles is not None: self.styles.update( { name: style if isinstance(style, Style) else Style.parse(style) for name, style in styles.items() } ) @property def config(self) -> str: """Get contents of a config file for this theme.""" config = "[styles]\n" + "\n".join( f"{name} = {style}" for name, style in sorted(self.styles.items()) ) return config @classmethod def from_file( cls, config_file: IO[str], source: Optional[str] = None, inherit: bool = True ) -> "Theme": """Load a theme from a text mode file. Args: config_file (IO[str]): An open conf file. source (str, optional): The filename of the open file. Defaults to None. inherit (bool, optional): Inherit default styles. Defaults to True. Returns: Theme: A New theme instance. """ config = configparser.ConfigParser() config.read_file(config_file, source=source) styles = {name: Style.parse(value) for name, value in config.items("styles")} theme = Theme(styles, inherit=inherit) return theme @classmethod def read( cls, path: str, inherit: bool = True, encoding: Optional[str] = None ) -> "Theme": """Read a theme from a path. Args: path (str): Path to a config file readable by Python configparser module. inherit (bool, optional): Inherit default styles. Defaults to True. encoding (str, optional): Encoding of the config file. Defaults to None. Returns: Theme: A new theme instance. """ with open(path, encoding=encoding) as config_file: return cls.from_file(config_file, source=path, inherit=inherit) class ThemeStackError(Exception): """Base exception for errors related to the theme stack.""" class ThemeStack: """A stack of themes. Args: theme (Theme): A theme instance """ def __init__(self, theme: Theme) -> None: self._entries: List[Dict[str, Style]] = [theme.styles] self.get = self._entries[-1].get def push_theme(self, theme: Theme, inherit: bool = True) -> None: """Push a theme on the top of the stack. Args: theme (Theme): A Theme instance. inherit (boolean, optional): Inherit styles from current top of stack. """ styles: Dict[str, Style] styles = ( {**self._entries[-1], **theme.styles} if inherit else theme.styles.copy() ) self._entries.append(styles) self.get = self._entries[-1].get def pop_theme(self) -> None: """Pop (and discard) the top-most theme.""" if len(self._entries) == 1: raise ThemeStackError("Unable to pop base theme") self._entries.pop() self.get = self._entries[-1].get if __name__ == "__main__": # pragma: no cover theme = Theme() print(theme.config)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_pick.py
rich/_pick.py
from typing import Optional def pick_bool(*values: Optional[bool]) -> bool: """Pick the first non-none bool or return the last value. Args: *values (bool): Any number of boolean or None values. Returns: bool: First non-none boolean. """ assert values, "1 or more values required" for value in values: if value is not None: return value return bool(value)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/jupyter.py
rich/jupyter.py
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence if TYPE_CHECKING: from rich.console import ConsoleRenderable from . import get_console from .segment import Segment from .terminal_theme import DEFAULT_TERMINAL_THEME if TYPE_CHECKING: from rich.console import ConsoleRenderable JUPYTER_HTML_FORMAT = """\ <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">{code}</pre> """ class JupyterRenderable: """A shim to write html to Jupyter notebook.""" def __init__(self, html: str, text: str) -> None: self.html = html self.text = text def _repr_mimebundle_( self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any ) -> Dict[str, str]: data = {"text/plain": self.text, "text/html": self.html} if include: data = {k: v for (k, v) in data.items() if k in include} if exclude: data = {k: v for (k, v) in data.items() if k not in exclude} return data class JupyterMixin: """Add to an Rich renderable to make it render in Jupyter notebook.""" __slots__ = () def _repr_mimebundle_( self: "ConsoleRenderable", include: Sequence[str], exclude: Sequence[str], **kwargs: Any, ) -> Dict[str, str]: console = get_console() segments = list(console.render(self, console.options)) html = _render_segments(segments) text = console._render_buffer(segments) data = {"text/plain": text, "text/html": html} if include: data = {k: v for (k, v) in data.items() if k in include} if exclude: data = {k: v for (k, v) in data.items() if k not in exclude} return data def _render_segments(segments: Iterable[Segment]) -> str: def escape(text: str) -> str: """Escape html.""" return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") fragments: List[str] = [] append_fragment = fragments.append theme = DEFAULT_TERMINAL_THEME for text, style, control in Segment.simplify(segments): if control: continue text = escape(text) if style: rule = style.get_html_style(theme) text = f'<span style="{rule}">{text}</span>' if rule else text if style.link: text = f'<a href="{style.link}" target="_blank">{text}</a>' append_fragment(text) code = "".join(fragments) html = JUPYTER_HTML_FORMAT.format(code=code) return html def display(segments: Iterable[Segment], text: str) -> None: """Render segments to Jupyter.""" html = _render_segments(segments) jupyter_renderable = JupyterRenderable(html, text) try: from IPython.display import display as ipython_display ipython_display(jupyter_renderable) except ModuleNotFoundError: # Handle the case where the Console has force_jupyter=True, # but IPython is not installed. pass def print(*args: Any, **kwargs: Any) -> None: """Proxy for Console print.""" console = get_console() return console.print(*args, **kwargs)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/logging.py
rich/logging.py
import logging from datetime import datetime from logging import Handler, LogRecord from pathlib import Path from types import ModuleType from typing import ClassVar, Iterable, List, Optional, Type, Union from rich._null_file import NullFile from . import get_console from ._log_render import FormatTimeCallable, LogRender from .console import Console, ConsoleRenderable from .highlighter import Highlighter, ReprHighlighter from .text import Text from .traceback import Traceback class RichHandler(Handler): """A logging handler that renders output with Rich. The time / level / message and file are displayed in columns. The level is color coded, and the message is syntax highlighted. Note: Be careful when enabling console markup in log messages if you have configured logging for libraries not under your control. If a dependency writes messages containing square brackets, it may not produce the intended output. Args: level (Union[int, str], optional): Log level. Defaults to logging.NOTSET. console (:class:`~rich.console.Console`, optional): Optional console instance to write logs. Default will use a global console instance writing to stdout. show_time (bool, optional): Show a column for the time. Defaults to True. omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True. show_level (bool, optional): Show a column for the level. Defaults to True. show_path (bool, optional): Show the path to the original log call. Defaults to True. enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True. highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None. markup (bool, optional): Enable console markup in log messages. Defaults to False. rich_tracebacks (bool, optional): Enable rich tracebacks with syntax highlighting and formatting. Defaults to False. tracebacks_width (Optional[int], optional): Number of characters used to render tracebacks, or None for full width. Defaults to None. tracebacks_code_width (int, optional): Number of code characters used to render tracebacks, or None for full width. Defaults to 88. tracebacks_extra_lines (int, optional): Additional lines of code to render tracebacks, or None for full width. Defaults to None. tracebacks_theme (str, optional): Override pygments theme used in traceback. tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True. tracebacks_show_locals (bool, optional): Enable display of locals in tracebacks. Defaults to False. tracebacks_suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. tracebacks_max_frames (int, optional): Optional maximum number of frames returned by traceback. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%x %X] ". keywords (List[str], optional): List of words to highlight instead of ``RichHandler.KEYWORDS``. """ KEYWORDS: ClassVar[Optional[List[str]]] = [ "GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS", "TRACE", "PATCH", ] HIGHLIGHTER_CLASS: ClassVar[Type[Highlighter]] = ReprHighlighter def __init__( self, level: Union[int, str] = logging.NOTSET, console: Optional[Console] = None, *, show_time: bool = True, omit_repeated_times: bool = True, show_level: bool = True, show_path: bool = True, enable_link_path: bool = True, highlighter: Optional[Highlighter] = None, markup: bool = False, rich_tracebacks: bool = False, tracebacks_width: Optional[int] = None, tracebacks_code_width: Optional[int] = 88, tracebacks_extra_lines: int = 3, tracebacks_theme: Optional[str] = None, tracebacks_word_wrap: bool = True, tracebacks_show_locals: bool = False, tracebacks_suppress: Iterable[Union[str, ModuleType]] = (), tracebacks_max_frames: int = 100, locals_max_length: int = 10, locals_max_string: int = 80, log_time_format: Union[str, FormatTimeCallable] = "[%x %X]", keywords: Optional[List[str]] = None, ) -> None: super().__init__(level=level) self.console = console or get_console() self.highlighter = highlighter or self.HIGHLIGHTER_CLASS() self._log_render = LogRender( show_time=show_time, show_level=show_level, show_path=show_path, time_format=log_time_format, omit_repeated_times=omit_repeated_times, level_width=None, ) self.enable_link_path = enable_link_path self.markup = markup self.rich_tracebacks = rich_tracebacks self.tracebacks_width = tracebacks_width self.tracebacks_extra_lines = tracebacks_extra_lines self.tracebacks_theme = tracebacks_theme self.tracebacks_word_wrap = tracebacks_word_wrap self.tracebacks_show_locals = tracebacks_show_locals self.tracebacks_suppress = tracebacks_suppress self.tracebacks_max_frames = tracebacks_max_frames self.tracebacks_code_width = tracebacks_code_width self.locals_max_length = locals_max_length self.locals_max_string = locals_max_string self.keywords = keywords def get_level_text(self, record: LogRecord) -> Text: """Get the level name from the record. Args: record (LogRecord): LogRecord instance. Returns: Text: A tuple of the style and level name. """ level_name = record.levelname level_text = Text.styled( level_name.ljust(8), f"logging.level.{level_name.lower()}" ) return level_text def emit(self, record: LogRecord) -> None: """Invoked by logging.""" message = self.format(record) traceback = None if ( self.rich_tracebacks and record.exc_info and record.exc_info != (None, None, None) ): exc_type, exc_value, exc_traceback = record.exc_info assert exc_type is not None assert exc_value is not None traceback = Traceback.from_exception( exc_type, exc_value, exc_traceback, width=self.tracebacks_width, code_width=self.tracebacks_code_width, extra_lines=self.tracebacks_extra_lines, theme=self.tracebacks_theme, word_wrap=self.tracebacks_word_wrap, show_locals=self.tracebacks_show_locals, locals_max_length=self.locals_max_length, locals_max_string=self.locals_max_string, suppress=self.tracebacks_suppress, max_frames=self.tracebacks_max_frames, ) message = record.getMessage() if self.formatter: record.message = record.getMessage() formatter = self.formatter if hasattr(formatter, "usesTime") and formatter.usesTime(): record.asctime = formatter.formatTime(record, formatter.datefmt) message = formatter.formatMessage(record) message_renderable = self.render_message(record, message) log_renderable = self.render( record=record, traceback=traceback, message_renderable=message_renderable ) if isinstance(self.console.file, NullFile): # Handles pythonw, where stdout/stderr are null, and we return NullFile # instance from Console.file. In this case, we still want to make a log record # even though we won't be writing anything to a file. self.handleError(record) else: try: self.console.print(log_renderable) except Exception: self.handleError(record) def render_message(self, record: LogRecord, message: str) -> "ConsoleRenderable": """Render message text in to Text. Args: record (LogRecord): logging Record. message (str): String containing log message. Returns: ConsoleRenderable: Renderable to display log message. """ use_markup = getattr(record, "markup", self.markup) message_text = Text.from_markup(message) if use_markup else Text(message) highlighter = getattr(record, "highlighter", self.highlighter) if highlighter: message_text = highlighter(message_text) if self.keywords is None: self.keywords = self.KEYWORDS if self.keywords: message_text.highlight_words(self.keywords, "logging.keyword") return message_text def render( self, *, record: LogRecord, traceback: Optional[Traceback], message_renderable: "ConsoleRenderable", ) -> "ConsoleRenderable": """Render log for display. Args: record (LogRecord): logging Record. traceback (Optional[Traceback]): Traceback instance or None for no Traceback. message_renderable (ConsoleRenderable): Renderable (typically Text) containing log message contents. Returns: ConsoleRenderable: Renderable to display log. """ path = Path(record.pathname).name level = self.get_level_text(record) time_format = None if self.formatter is None else self.formatter.datefmt log_time = datetime.fromtimestamp(record.created) log_renderable = self._log_render( self.console, [message_renderable] if not traceback else [message_renderable, traceback], log_time=log_time, time_format=time_format, level=level, path=path, line_no=record.lineno, link_path=record.pathname if self.enable_link_path else None, ) return log_renderable if __name__ == "__main__": # pragma: no cover from time import sleep FORMAT = "%(message)s" # FORMAT = "%(asctime)-15s - %(levelname)s - %(message)s" logging.basicConfig( level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)], ) log = logging.getLogger("rich") log.info("Server starting...") log.info("Listening on http://127.0.0.1:8080") sleep(1) log.info("GET /index.html 200 1298") log.info("GET /imgs/backgrounds/back1.jpg 200 54386") log.info("GET /css/styles.css 200 54386") log.warning("GET /favicon.ico 404 242") sleep(1) log.debug( "JSONRPC request\n--> %r\n<-- %r", { "version": "1.1", "method": "confirmFruitPurchase", "params": [["apple", "orange", "mangoes", "pomelo"], 1.123], "id": "194521489", }, {"version": "1.1", "result": True, "error": None, "id": "194521489"}, ) log.debug( "Loading configuration file /adasd/asdasd/qeqwe/qwrqwrqwr/sdgsdgsdg/werwerwer/dfgerert/ertertert/ertetert/werwerwer" ) log.error("Unable to find 'pomelo' in database!") log.info("POST /jsonrpc/ 200 65532") log.info("POST /admin/ 401 42234") log.warning("password was rejected for admin site.") def divide() -> None: number = 1 divisor = 0 foos = ["foo"] * 100 log.debug("in divide") try: number / divisor except: log.exception("An error of some kind occurred!") divide() sleep(1) log.critical("Out of memory!") log.info("Server exited with code=-1") log.info("[bold]EXITING...[/bold]", extra=dict(markup=True))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/screen.py
rich/screen.py
from typing import Optional, TYPE_CHECKING from .segment import Segment from .style import StyleType from ._loop import loop_last if TYPE_CHECKING: from .console import ( Console, ConsoleOptions, RenderResult, RenderableType, Group, ) class Screen: """A renderable that fills the terminal screen and crops excess. Args: renderable (RenderableType): Child renderable. style (StyleType, optional): Optional background style. Defaults to None. """ renderable: "RenderableType" def __init__( self, *renderables: "RenderableType", style: Optional[StyleType] = None, application_mode: bool = False, ) -> None: from rich.console import Group self.renderable = Group(*renderables) self.style = style self.application_mode = application_mode def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": width, height = options.size style = console.get_style(self.style) if self.style else None render_options = options.update(width=width, height=height) lines = console.render_lines( self.renderable or "", render_options, style=style, pad=True ) lines = Segment.set_shape(lines, width, height, style=style) new_line = Segment("\n\r") if self.application_mode else Segment.line() for last, line in loop_last(lines): yield from line if not last: yield new_line
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false