index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
21,635 | auto_gptq.modeling.auto | AutoGPTQForCausalLM | null | class AutoGPTQForCausalLM:
def __init__(self):
raise EnvironmentError(
"AutoGPTQModelForCausalLM is designed to be instantiated\n"
"using `AutoGPTQModelForCausalLM.from_pretrained` if want to quantize a pretrained model.\n"
"using `AutoGPTQModelForCausalLM.from_quantized` if want to inference with quantized model."
)
@classmethod
def from_pretrained(
cls,
pretrained_model_name_or_path: str,
quantize_config: BaseQuantizeConfig,
max_memory: Optional[dict] = None,
trust_remote_code: bool = False,
**model_init_kwargs,
) -> BaseGPTQForCausalLM:
model_type = check_and_get_model_type(pretrained_model_name_or_path, trust_remote_code)
return GPTQ_CAUSAL_LM_MODEL_MAP[model_type].from_pretrained(
pretrained_model_name_or_path=pretrained_model_name_or_path,
quantize_config=quantize_config,
max_memory=max_memory,
trust_remote_code=trust_remote_code,
**model_init_kwargs,
)
@classmethod
def from_quantized(
cls,
model_name_or_path: Optional[str],
device_map: Optional[Union[str, Dict[str, Union[str, int]]]] = None,
max_memory: Optional[dict] = None,
device: Optional[Union[str, int]] = None,
low_cpu_mem_usage: bool = False,
use_triton: bool = False,
inject_fused_attention: bool = False,
inject_fused_mlp: bool = False,
use_cuda_fp16: bool = True,
quantize_config: Optional[BaseQuantizeConfig] = None,
model_basename: Optional[str] = None,
use_safetensors: bool = True,
trust_remote_code: bool = False,
warmup_triton: bool = False,
trainable: bool = False,
disable_exllama: Optional[bool] = None,
disable_exllamav2: bool = False,
use_marlin: bool = False,
**kwargs,
) -> BaseGPTQForCausalLM:
# If disable_exllamav2 is True, we want to fall back on the exllama kernel and not the cuda/cuda_old ones.
if disable_exllama is None:
if disable_exllamav2:
disable_exllama = False
else:
disable_exllama = True
model_type = check_and_get_model_type(model_name_or_path, trust_remote_code)
quant_func = GPTQ_CAUSAL_LM_MODEL_MAP[model_type].from_quantized
# A static list of kwargs needed for huggingface_hub
huggingface_kwargs = [
"cache_dir",
"force_download",
"proxies",
"resume_download",
"local_files_only",
"use_auth_token",
"revision",
"subfolder",
"_raise_exceptions_for_missing_entries",
"_commit_hash",
]
# TODO: do we need this filtering of kwargs? @PanQiWei is there a reason we can't just pass all kwargs?
keywords = {
key: kwargs[key]
for key in list(signature(quant_func).parameters.keys()) + huggingface_kwargs
if key in kwargs
}
return quant_func(
model_name_or_path=model_name_or_path,
device_map=device_map,
max_memory=max_memory,
device=device,
low_cpu_mem_usage=low_cpu_mem_usage,
use_triton=use_triton,
inject_fused_attention=inject_fused_attention,
inject_fused_mlp=inject_fused_mlp,
use_cuda_fp16=use_cuda_fp16,
quantize_config=quantize_config,
model_basename=model_basename,
use_safetensors=use_safetensors,
trust_remote_code=trust_remote_code,
warmup_triton=warmup_triton,
trainable=trainable,
disable_exllama=disable_exllama,
disable_exllamav2=disable_exllamav2,
use_marlin=use_marlin,
**keywords,
)
| () |
21,636 | auto_gptq.modeling.auto | __init__ | null | def __init__(self):
raise EnvironmentError(
"AutoGPTQModelForCausalLM is designed to be instantiated\n"
"using `AutoGPTQModelForCausalLM.from_pretrained` if want to quantize a pretrained model.\n"
"using `AutoGPTQModelForCausalLM.from_quantized` if want to inference with quantized model."
)
| (self) |
21,637 | auto_gptq.modeling._base | BaseQuantizeConfig | BaseQuantizeConfig(bits: int = 4, group_size: int = -1, damp_percent: float = 0.01, desc_act: bool = True, static_groups: bool = False, sym: bool = True, true_sequential: bool = True, is_marlin_format: bool = False, model_name_or_path: Optional[str] = None, model_file_base_name: Optional[str] = None, awq_gemm_checkpoint: Optional[bool] = False) | class BaseQuantizeConfig(PushToHubMixin):
bits: int = field(default=4, metadata={"choices": [2, 3, 4, 8]})
group_size: int = field(default=-1)
damp_percent: float = field(default=0.01)
desc_act: bool = field(default=True)
static_groups: bool = field(default=False)
sym: bool = field(default=True)
true_sequential: bool = field(default=True)
is_marlin_format: bool = field(default=False)
model_name_or_path: Optional[str] = field(default=None)
model_file_base_name: Optional[str] = field(default=None)
awq_gemm_checkpoint: Optional[bool] = field(default=False)
def __post_init__(self):
fields_info = fields(self)
if self.bits not in fields_info[0].metadata["choices"]:
raise ValueError(f"only support quantize to {fields_info[0].metadata['choices']} bits.")
if self.group_size != -1 and self.group_size <= 0:
raise ValueError("unless equal to -1, group_size must greater then 0.")
if not (0 < self.damp_percent < 1):
raise ValueError("damp_percent must between 0 and 1.")
def save_pretrained(self, save_dir: str, **kwargs):
with open(join(save_dir, "quantize_config.json"), "w", encoding="utf-8") as f:
json.dump(self.to_dict(), f, indent=2)
@classmethod
def from_pretrained(cls, save_dir: str, **kwargs):
# Parameters related to loading from Hugging Face Hub
cache_dir = kwargs.pop("cache_dir", None)
force_download = kwargs.pop("force_download", False)
resume_download = kwargs.pop("resume_download", False)
proxies = kwargs.pop("proxies", None)
local_files_only = kwargs.pop("local_files_only", False)
use_auth_token = kwargs.pop("use_auth_token", None)
revision = kwargs.pop("revision", None)
subfolder = kwargs.pop("subfolder", None)
commit_hash = kwargs.pop("_commit_hash", None)
transformers_config = False
for quantize_config_filename in [
"quantize_config.json",
"quant_config.json",
"config.json",
]:
if os.path.isdir(save_dir): # Local
resolved_config_file = join(save_dir, quantize_config_filename)
else: # Remote
resolved_config_file = cached_file(
save_dir,
quantize_config_filename,
cache_dir=cache_dir,
force_download=force_download,
resume_download=resume_download,
proxies=proxies,
use_auth_token=use_auth_token,
revision=revision,
local_files_only=local_files_only,
subfolder=subfolder,
_raise_exceptions_for_missing_entries=False,
_raise_exceptions_for_connection_errors=False,
_commit_hash=commit_hash,
)
if resolved_config_file is not None:
if quantize_config_filename == "config.json":
transformers_config = True
break
if resolved_config_file is None:
raise ValueError(
"No quantize_config.json, quant_config.json or config.json file was found in the model repository."
)
field_names = [field.name for field in fields(cls)]
with open(resolved_config_file, "r", encoding="utf-8") as f:
args_from_json = json.load(f)
if transformers_config:
args_from_json = args_from_json["quantization_config"]
filtered_args = {"awq_gemm_checkpoint": False}
for key, val in args_from_json.items():
if key == "version" and val == "GEMM":
filtered_args["awq_gemm_checkpoint"] = True
elif key in field_names:
filtered_args[key] = val
elif key in SYNONYMS and SYNONYMS[key] in field_names:
filtered_args[SYNONYMS[key]] = val
else:
logger.warning(f"ignoring unknown parameter in {quantize_config_filename}: {key}.")
if filtered_args["awq_gemm_checkpoint"]:
# AWQ does not reorder the rows.
filtered_args["desc_act"] = False
if "sym" not in args_from_json:
logger.warning(
f"The quantization configuration {quantize_config_filename} does not contain an entry `sym` (symetric quantization). This may result in silent errors."
)
return cls(**filtered_args)
def to_dict(self):
return {
"bits": self.bits,
"group_size": self.group_size,
"damp_percent": self.damp_percent,
"desc_act": self.desc_act,
"static_groups": self.static_groups,
"sym": self.sym,
"true_sequential": self.true_sequential,
"model_name_or_path": self.model_name_or_path,
"model_file_base_name": self.model_file_base_name,
"is_marlin_format": self.is_marlin_format,
"quant_method": "gptq",
}
| (bits: int = 4, group_size: int = -1, damp_percent: float = 0.01, desc_act: bool = True, static_groups: bool = False, sym: bool = True, true_sequential: bool = True, is_marlin_format: bool = False, model_name_or_path: Optional[str] = None, model_file_base_name: Optional[str] = None, awq_gemm_checkpoint: Optional[bool] = False) -> None |
21,638 | auto_gptq.modeling._base | __eq__ | null | import copy
import json
import logging
import os
from dataclasses import dataclass, field, fields
from os.path import isdir, join
from typing import Dict, List, Optional, Union
import accelerate
import huggingface_hub
import torch
import torch.nn as nn
import transformers
from accelerate.hooks import remove_hook_from_module
from safetensors import safe_open
from safetensors.torch import load_file as safe_load
from safetensors.torch import save_file as safe_save
from tqdm import tqdm
from transformers import AutoConfig, AutoModelForCausalLM, PreTrainedModel
from transformers.modeling_utils import no_init_weights
from transformers.utils.generic import ContextManagers
from transformers.utils.hub import (
CommitOperationAdd,
PushToHubMixin,
cached_file,
create_commit,
create_repo,
)
from ..nn_modules._fused_base import FusedBaseAttentionModule, FusedBaseMLPModule
from ..nn_modules.qlinear import GeneralQuantLinear
from ..quantization import GPTQ
from ..utils.data_utils import collate_data
from ..utils.import_utils import (
AUTOGPTQ_CUDA_AVAILABLE,
EXLLAMA_KERNELS_AVAILABLE,
EXLLAMAV2_KERNELS_AVAILABLE,
MARLIN_AVAILABLE,
QIGEN_AVAILABLE,
TRITON_AVAILABLE,
dynamically_import_QuantLinear,
)
from ..utils.marlin_utils import (
_validate_marlin_compatibility,
_validate_marlin_device_support,
prepare_model_for_marlin_load,
)
from ._const import CPU, CUDA_0, SUPPORTED_MODELS
from ._utils import (
autogptq_post_init,
find_layers,
get_checkpoints,
get_device,
get_module_by_name_prefix,
get_module_by_name_suffix,
make_quant,
make_sure_no_tensor_in_meta_device,
move_to_device,
pack_from_tensors,
pack_model,
preprocess_checkpoint_qigen,
simple_dispatch_model,
unpack_awq,
)
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
SYNONYMS = {
"w_bit": "bits",
"q_group_size": "group_size",
}
@dataclass
class BaseQuantizeConfig(PushToHubMixin):
bits: int = field(default=4, metadata={"choices": [2, 3, 4, 8]})
group_size: int = field(default=-1)
damp_percent: float = field(default=0.01)
desc_act: bool = field(default=True)
static_groups: bool = field(default=False)
sym: bool = field(default=True)
true_sequential: bool = field(default=True)
is_marlin_format: bool = field(default=False)
model_name_or_path: Optional[str] = field(default=None)
model_file_base_name: Optional[str] = field(default=None)
awq_gemm_checkpoint: Optional[bool] = field(default=False)
def __post_init__(self):
fields_info = fields(self)
if self.bits not in fields_info[0].metadata["choices"]:
raise ValueError(f"only support quantize to {fields_info[0].metadata['choices']} bits.")
if self.group_size != -1 and self.group_size <= 0:
raise ValueError("unless equal to -1, group_size must greater then 0.")
if not (0 < self.damp_percent < 1):
raise ValueError("damp_percent must between 0 and 1.")
def save_pretrained(self, save_dir: str, **kwargs):
with open(join(save_dir, "quantize_config.json"), "w", encoding="utf-8") as f:
json.dump(self.to_dict(), f, indent=2)
@classmethod
def from_pretrained(cls, save_dir: str, **kwargs):
# Parameters related to loading from Hugging Face Hub
cache_dir = kwargs.pop("cache_dir", None)
force_download = kwargs.pop("force_download", False)
resume_download = kwargs.pop("resume_download", False)
proxies = kwargs.pop("proxies", None)
local_files_only = kwargs.pop("local_files_only", False)
use_auth_token = kwargs.pop("use_auth_token", None)
revision = kwargs.pop("revision", None)
subfolder = kwargs.pop("subfolder", None)
commit_hash = kwargs.pop("_commit_hash", None)
transformers_config = False
for quantize_config_filename in [
"quantize_config.json",
"quant_config.json",
"config.json",
]:
if os.path.isdir(save_dir): # Local
resolved_config_file = join(save_dir, quantize_config_filename)
else: # Remote
resolved_config_file = cached_file(
save_dir,
quantize_config_filename,
cache_dir=cache_dir,
force_download=force_download,
resume_download=resume_download,
proxies=proxies,
use_auth_token=use_auth_token,
revision=revision,
local_files_only=local_files_only,
subfolder=subfolder,
_raise_exceptions_for_missing_entries=False,
_raise_exceptions_for_connection_errors=False,
_commit_hash=commit_hash,
)
if resolved_config_file is not None:
if quantize_config_filename == "config.json":
transformers_config = True
break
if resolved_config_file is None:
raise ValueError(
"No quantize_config.json, quant_config.json or config.json file was found in the model repository."
)
field_names = [field.name for field in fields(cls)]
with open(resolved_config_file, "r", encoding="utf-8") as f:
args_from_json = json.load(f)
if transformers_config:
args_from_json = args_from_json["quantization_config"]
filtered_args = {"awq_gemm_checkpoint": False}
for key, val in args_from_json.items():
if key == "version" and val == "GEMM":
filtered_args["awq_gemm_checkpoint"] = True
elif key in field_names:
filtered_args[key] = val
elif key in SYNONYMS and SYNONYMS[key] in field_names:
filtered_args[SYNONYMS[key]] = val
else:
logger.warning(f"ignoring unknown parameter in {quantize_config_filename}: {key}.")
if filtered_args["awq_gemm_checkpoint"]:
# AWQ does not reorder the rows.
filtered_args["desc_act"] = False
if "sym" not in args_from_json:
logger.warning(
f"The quantization configuration {quantize_config_filename} does not contain an entry `sym` (symetric quantization). This may result in silent errors."
)
return cls(**filtered_args)
def to_dict(self):
return {
"bits": self.bits,
"group_size": self.group_size,
"damp_percent": self.damp_percent,
"desc_act": self.desc_act,
"static_groups": self.static_groups,
"sym": self.sym,
"true_sequential": self.true_sequential,
"model_name_or_path": self.model_name_or_path,
"model_file_base_name": self.model_file_base_name,
"is_marlin_format": self.is_marlin_format,
"quant_method": "gptq",
}
| (self, other) |
21,640 | auto_gptq.modeling._base | __post_init__ | null | def __post_init__(self):
fields_info = fields(self)
if self.bits not in fields_info[0].metadata["choices"]:
raise ValueError(f"only support quantize to {fields_info[0].metadata['choices']} bits.")
if self.group_size != -1 and self.group_size <= 0:
raise ValueError("unless equal to -1, group_size must greater then 0.")
if not (0 < self.damp_percent < 1):
raise ValueError("damp_percent must between 0 and 1.")
| (self) |
21,641 | auto_gptq.modeling._base | __repr__ | null | def __init__(
self,
model: PreTrainedModel,
quantized: bool,
quantize_config: BaseQuantizeConfig,
is_triton_backend: bool = False,
injected_fused_attention: bool = False,
injected_fused_mlp: bool = False,
trainable: bool = False,
):
super().__init__()
self.model = model
self.model_type = self.model.config.model_type
self._quantized = quantized
self.quantize_config = quantize_config
self.config = self.model.config
self.is_triton_backend = is_triton_backend
self.injected_fused_attention = injected_fused_attention
self.injected_fused_mlp = injected_fused_mlp
self.trainable = trainable
| (self) |
21,645 | transformers.utils.hub | push_to_hub |
Upload the {object_files} to the 🤗 Model Hub.
Parameters:
repo_id (`str`):
The name of the repository you want to push your {object} to. It should contain your organization name
when pushing to a given organization.
use_temp_dir (`bool`, *optional*):
Whether or not to use a temporary directory to store the files saved before they are pushed to the Hub.
Will default to `True` if there is no directory named like `repo_id`, `False` otherwise.
commit_message (`str`, *optional*):
Message to commit while pushing. Will default to `"Upload {object}"`.
private (`bool`, *optional*):
Whether or not the repository created should be private.
token (`bool` or `str`, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `huggingface-cli login` (stored in `~/.huggingface`). Will default to `True` if `repo_url`
is not specified.
max_shard_size (`int` or `str`, *optional*, defaults to `"5GB"`):
Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard
will then be each of size lower than this size. If expressed as a string, needs to be digits followed
by a unit (like `"5MB"`). We default it to `"5GB"` so that users can easily load models on free-tier
Google Colab instances without any CPU OOM issues.
create_pr (`bool`, *optional*, defaults to `False`):
Whether or not to create a PR with the uploaded files or directly commit.
safe_serialization (`bool`, *optional*, defaults to `True`):
Whether or not to convert the model weights in safetensors format for safer serialization.
revision (`str`, *optional*):
Branch to push the uploaded files to.
commit_description (`str`, *optional*):
The description of the commit that will be created
tags (`List[str]`, *optional*):
List of tags to push on the Hub.
Examples:
```python
from transformers import {object_class}
{object} = {object_class}.from_pretrained("google-bert/bert-base-cased")
# Push the {object} to your namespace with the name "my-finetuned-bert".
{object}.push_to_hub("my-finetuned-bert")
# Push the {object} to an organization with the name "my-finetuned-bert".
{object}.push_to_hub("huggingface/my-finetuned-bert")
```
| def push_to_hub(
self,
repo_id: str,
use_temp_dir: Optional[bool] = None,
commit_message: Optional[str] = None,
private: Optional[bool] = None,
token: Optional[Union[bool, str]] = None,
max_shard_size: Optional[Union[int, str]] = "5GB",
create_pr: bool = False,
safe_serialization: bool = True,
revision: str = None,
commit_description: str = None,
tags: Optional[List[str]] = None,
**deprecated_kwargs,
) -> str:
"""
Upload the {object_files} to the 🤗 Model Hub.
Parameters:
repo_id (`str`):
The name of the repository you want to push your {object} to. It should contain your organization name
when pushing to a given organization.
use_temp_dir (`bool`, *optional*):
Whether or not to use a temporary directory to store the files saved before they are pushed to the Hub.
Will default to `True` if there is no directory named like `repo_id`, `False` otherwise.
commit_message (`str`, *optional*):
Message to commit while pushing. Will default to `"Upload {object}"`.
private (`bool`, *optional*):
Whether or not the repository created should be private.
token (`bool` or `str`, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `huggingface-cli login` (stored in `~/.huggingface`). Will default to `True` if `repo_url`
is not specified.
max_shard_size (`int` or `str`, *optional*, defaults to `"5GB"`):
Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard
will then be each of size lower than this size. If expressed as a string, needs to be digits followed
by a unit (like `"5MB"`). We default it to `"5GB"` so that users can easily load models on free-tier
Google Colab instances without any CPU OOM issues.
create_pr (`bool`, *optional*, defaults to `False`):
Whether or not to create a PR with the uploaded files or directly commit.
safe_serialization (`bool`, *optional*, defaults to `True`):
Whether or not to convert the model weights in safetensors format for safer serialization.
revision (`str`, *optional*):
Branch to push the uploaded files to.
commit_description (`str`, *optional*):
The description of the commit that will be created
tags (`List[str]`, *optional*):
List of tags to push on the Hub.
Examples:
```python
from transformers import {object_class}
{object} = {object_class}.from_pretrained("google-bert/bert-base-cased")
# Push the {object} to your namespace with the name "my-finetuned-bert".
{object}.push_to_hub("my-finetuned-bert")
# Push the {object} to an organization with the name "my-finetuned-bert".
{object}.push_to_hub("huggingface/my-finetuned-bert")
```
"""
use_auth_token = deprecated_kwargs.pop("use_auth_token", None)
ignore_metadata_errors = deprecated_kwargs.pop("ignore_metadata_errors", False)
if use_auth_token is not None:
warnings.warn(
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
FutureWarning,
)
if token is not None:
raise ValueError(
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
)
token = use_auth_token
repo_path_or_name = deprecated_kwargs.pop("repo_path_or_name", None)
if repo_path_or_name is not None:
# Should use `repo_id` instead of `repo_path_or_name`. When using `repo_path_or_name`, we try to infer
# repo_id from the folder path, if it exists.
warnings.warn(
"The `repo_path_or_name` argument is deprecated and will be removed in v5 of Transformers. Use "
"`repo_id` instead.",
FutureWarning,
)
if repo_id is not None:
raise ValueError(
"`repo_id` and `repo_path_or_name` are both specified. Please set only the argument `repo_id`."
)
if os.path.isdir(repo_path_or_name):
# repo_path: infer repo_id from the path
repo_id = repo_id.split(os.path.sep)[-1]
working_dir = repo_id
else:
# repo_name: use it as repo_id
repo_id = repo_path_or_name
working_dir = repo_id.split("/")[-1]
else:
# Repo_id is passed correctly: infer working_dir from it
working_dir = repo_id.split("/")[-1]
# Deprecation warning will be sent after for repo_url and organization
repo_url = deprecated_kwargs.pop("repo_url", None)
organization = deprecated_kwargs.pop("organization", None)
repo_id = self._create_repo(
repo_id, private=private, token=token, repo_url=repo_url, organization=organization
)
# Create a new empty model card and eventually tag it
model_card = create_and_tag_model_card(
repo_id, tags, token=token, ignore_metadata_errors=ignore_metadata_errors
)
if use_temp_dir is None:
use_temp_dir = not os.path.isdir(working_dir)
with working_or_temp_dir(working_dir=working_dir, use_temp_dir=use_temp_dir) as work_dir:
files_timestamps = self._get_files_timestamps(work_dir)
# Save all files.
self.save_pretrained(work_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
# Update model card if needed:
model_card.save(os.path.join(work_dir, "README.md"))
return self._upload_modified_files(
work_dir,
repo_id,
files_timestamps,
commit_message=commit_message,
token=token,
create_pr=create_pr,
revision=revision,
commit_description=commit_description,
)
| (self, repo_id: str, use_temp_dir: Optional[bool] = None, commit_message: Optional[str] = None, private: Optional[bool] = None, token: Union[bool, str, NoneType] = None, max_shard_size: Union[int, str, NoneType] = '5GB', create_pr: bool = False, safe_serialization: bool = True, revision: Optional[str] = None, commit_description: Optional[str] = None, tags: Optional[List[str]] = None, **deprecated_kwargs) -> str |
21,646 | auto_gptq.modeling._base | save_pretrained | null | def save_pretrained(self, save_dir: str, **kwargs):
with open(join(save_dir, "quantize_config.json"), "w", encoding="utf-8") as f:
json.dump(self.to_dict(), f, indent=2)
| (self, save_dir: str, **kwargs) |
21,647 | auto_gptq.modeling._base | to_dict | null | def to_dict(self):
return {
"bits": self.bits,
"group_size": self.group_size,
"damp_percent": self.damp_percent,
"desc_act": self.desc_act,
"static_groups": self.static_groups,
"sym": self.sym,
"true_sequential": self.true_sequential,
"model_name_or_path": self.model_name_or_path,
"model_file_base_name": self.model_file_base_name,
"is_marlin_format": self.is_marlin_format,
"quant_method": "gptq",
}
| (self) |
21,648 | auto_gptq.utils.exllama_utils | exllama_set_max_input_length |
This method does not necessarily require `model` to inherit from BaseGPTQForCausalLM.
When using the exllama backend with act-order, it is necessary to initialize a buffer that depends on the maximum expected input length. In case the
default used (EXLLAMA_DEFAULT_MAX_INPUT_LENGTH) is too short, this method can be called to extend the buffer size without reloading the whole model.
| def exllama_set_max_input_length(model, max_input_length: int):
"""
This method does not necessarily require `model` to inherit from BaseGPTQForCausalLM.
When using the exllama backend with act-order, it is necessary to initialize a buffer that depends on the maximum expected input length. In case the
default used (EXLLAMA_DEFAULT_MAX_INPUT_LENGTH) is too short, this method can be called to extend the buffer size without reloading the whole model.
"""
# The import is set here to avoid a global import. Arguably this is quite ugly, it would be better to have lazy loading.
from exllama_kernels import cleanup_buffers_cuda, prepare_buffers
if not model.quantize_config.desc_act:
raise ValueError(
"The method exllama_set_max_input_length should be called only when using the exllama backend **with act-order**."
)
uses_exllama = False
for name, submodule in model.named_modules():
if isinstance(submodule, ExllamaQuantLinear):
uses_exllama = True
if not uses_exllama:
raise ValueError(
f"The function exllama_set_max_input_length was called, but the model (instance of {model.__class__.__name__}) does not use the exllama backend for GPTQ. An other implementation is used (exllamav2, cuda, cuda-old, triton) and that the call to exllama_set_max_input_length is unnecessary. Please remove the call to exllama_set_max_input_length or use the exllama v1 backend."
)
device_to_buffers_size = {}
for device, buffers in model.device_to_buffers.items():
device_to_buffers_size[device] = {
"max_dq_buffer_size": buffers["max_dq_buffer_size"],
"max_inner_outer_dim": buffers["max_inner_outer_dim"],
}
# For an unknown reason calling just `del model.device_to_buffers` raises an AttributeError.
for key in list(model.device_to_buffers.keys()):
del model.device_to_buffers[key]
model.device_to_buffers = None
del model.device_to_buffers
gc.collect()
torch.cuda.empty_cache()
cleanup_buffers_cuda()
device_to_buffers = {}
for device, buffers_size in device_to_buffers_size.items():
# The temp_state buffer is required to reorder X in the act-order case.
# The temp_dq buffer is required to dequantize weights when using cuBLAS, typically for the prefill.
device_to_buffers[device] = {
"temp_state": torch.zeros(
(max_input_length, buffers_size["max_inner_outer_dim"]),
dtype=torch.float16,
device=device,
),
"temp_dq": torch.zeros(
(1, buffers_size["max_dq_buffer_size"]),
dtype=torch.float16,
device=device,
),
"max_dq_buffer_size": buffers_size["max_dq_buffer_size"],
"max_inner_outer_dim": buffers_size["max_inner_outer_dim"],
}
prepare_buffers(
device,
device_to_buffers[device]["temp_state"],
device_to_buffers[device]["temp_dq"],
)
# Buffers need to be persistent to avoid any bug.
model.device_to_buffers = device_to_buffers
return model
| (model, max_input_length: int) |
21,649 | auto_gptq.utils.peft_utils | get_gptq_peft_model | null | def get_gptq_peft_model(
model: BaseGPTQForCausalLM,
peft_config: PeftConfig = None,
model_id: str = None,
adapter_name: str = "default",
auto_find_all_linears: bool = True,
train_mode: bool = False,
):
if train_mode and not model.trainable:
model.enable_trainable_mode()
if train_mode and not peft_config:
raise ValueError("peft_config not specified when in train mode.")
if not train_mode and not model_id:
raise ValueError("model_id(where to load adapters) not specified when in inference mode.")
if model.fused_attn_module_type is not None and not model.injected_fused_attention:
peft_types = [PeftType.LORA.value, PeftType.ADALORA.value]
warnings.warn(
f"You can just ignore this warning if the peft type you use isn't in {peft_types}.\n"
f"{model.__class__.__name__} supports injecting fused attention but not enables this time. "
"If you are training adapters, you must also disable fused attention injection when loading quantized "
"base model at inference time, otherwise adapters may not be added to base model properly. "
"If you are loading adapters to do inference, you can reference to adapter's config file to check "
"whether the adapters are trained using base model that not enable fused attention injection."
)
if model.injected_fused_mlp:
raise NotImplementedError(
"GPTQ model that enables fused mlp injection is not supported to integrate with peft."
)
if train_mode:
peft_type = peft_config.peft_type
if not isinstance(peft_type, str):
peft_type = peft_type.value
if peft_type in [PeftType.LORA.value, PeftType.ADALORA.value]:
if auto_find_all_linears:
peft_config.target_modules = find_all_linear_names(model, ignore_lm_head=True)
if peft_type == PeftType.LORA.value and not isinstance(peft_config, GPTQLoraConfig):
peft_config = GPTQLoraConfig(**peft_config.to_dict())
if peft_type == PeftType.ADALORA.value and not isinstance(peft_config, GPTQAdaLoraConfig):
peft_config = GPTQAdaLoraConfig(**peft_config.to_dict())
peft_config.injected_fused_attention = model.injected_fused_attention
peft_config.injected_fused_mlp = model.injected_fused_mlp
if peft_type == PeftType.ADAPTION_PROMPT.value:
if peft_config.adapter_layers > model.config.num_hidden_layers:
warnings.warn(
f"model has only {model.config.num_hidden_layers} layers "
f"but adapter_layers is set to {peft_config.adapter_layers}, "
f"will reset value to {model.config.num_hidden_layers}."
)
peft_config.adapter_layers = model.config.num_hidden_layers
if model.injected_fused_attention:
raise NotImplementedError(
"model with fused attention injected isn't supported to use ADAPTION_PROMPT peft type yet."
)
with hijack_peft_mappings():
try:
if train_mode:
peft_model = get_peft_model(model.model, peft_config, adapter_name=adapter_name)
else:
peft_model = PeftModel.from_pretrained(model.model, model_id, adapter_name)
except:
raise
raise NotImplementedError(
f"{model.__class__.__name__} not support {peft_config.peft_type.value} peft type yet."
)
return peft_model
| (model: auto_gptq.modeling._base.BaseGPTQForCausalLM, peft_config: Optional[peft.config.PeftConfig] = None, model_id: Optional[str] = None, adapter_name: str = 'default', auto_find_all_linears: bool = True, train_mode: bool = False) |
21,654 | magic_filter.attrdict | AttrDict |
A wrapper over dict which where element can be accessed as regular attributes
| class AttrDict(Dict[KT, VT]):
"""
A wrapper over dict which where element can be accessed as regular attributes
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self # type: ignore
| (*args: Any, **kwargs: Any) -> None |
21,655 | magic_filter.attrdict | __init__ | null | def __init__(self, *args: Any, **kwargs: Any) -> None:
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self # type: ignore
| (self, *args: Any, **kwargs: Any) -> NoneType |
21,656 | magic_filter.magic | MagicFilter | null | class MagicFilter:
__slots__ = ("_operations",)
def __init__(self, operations: Tuple[BaseOperation, ...] = ()) -> None:
self._operations = operations
# An instance of MagicFilter cannot be used as an iterable object because objects
# with a __getitem__ method can be endlessly iterated, which is not the desired behavior.
__iter__ = None
@classmethod
def ilter(cls, magic: "MagicFilter") -> Callable[[Any], Any]:
@wraps(magic.resolve)
def wrapper(value: Any) -> Any:
return magic.resolve(value)
return wrapper
@classmethod
def _new(cls: Type[MagicT], operations: Tuple[BaseOperation, ...]) -> MagicT:
return cls(operations=operations)
def _extend(self: MagicT, operation: BaseOperation) -> MagicT:
return self._new(self._operations + (operation,))
def _replace_last(self: MagicT, operation: BaseOperation) -> MagicT:
return self._new(self._operations[:-1] + (operation,))
def _exclude_last(self: MagicT) -> MagicT:
return self._new(self._operations[:-1])
def _resolve(self, value: Any, operations: Optional[Tuple[BaseOperation, ...]] = None) -> Any:
initial_value = value
if operations is None:
operations = self._operations
rejected = False
for index, operation in enumerate(operations):
if rejected and not operation.important:
continue
try:
value = operation.resolve(value=value, initial_value=initial_value)
except SwitchModeToAll:
return all(self._resolve(value=item, operations=operations[index + 1 :]) for item in value)
except SwitchModeToAny:
return any(self._resolve(value=item, operations=operations[index + 1 :]) for item in value)
except RejectOperations:
rejected = True
value = None
continue
rejected = False
return value
def __bool__(self) -> bool:
return True
def resolve(self: MagicT, value: Any) -> Any:
return self._resolve(value=value)
def __getattr__(self: MagicT, item: Any) -> MagicT:
if item.startswith("_"):
raise AttributeError(f"{type(self).__name__!r} object has no attribute {item!r}")
return self._extend(GetAttributeOperation(name=item))
attr_ = __getattr__
def __getitem__(self: MagicT, item: Any) -> MagicT:
if isinstance(item, MagicFilter):
return self._extend(SelectorOperation(inner=item))
return self._extend(GetItemOperation(key=item))
def __len__(self) -> int:
raise TypeError(f"Length can't be taken using len() function. Use {type(self).__name__}.len() instead.")
def __eq__(self: MagicT, other: Any) -> MagicT: # type: ignore
return self._extend(ComparatorOperation(right=other, comparator=operator.eq))
def __ne__(self: MagicT, other: Any) -> MagicT: # type: ignore
return self._extend(ComparatorOperation(right=other, comparator=operator.ne))
def __lt__(self: MagicT, other: Any) -> MagicT:
return self._extend(ComparatorOperation(right=other, comparator=operator.lt))
def __gt__(self: MagicT, other: Any) -> MagicT:
return self._extend(ComparatorOperation(right=other, comparator=operator.gt))
def __le__(self: MagicT, other: Any) -> MagicT:
return self._extend(ComparatorOperation(right=other, comparator=operator.le))
def __ge__(self: MagicT, other: Any) -> MagicT:
return self._extend(ComparatorOperation(right=other, comparator=operator.ge))
def __invert__(self: MagicT) -> MagicT:
if (
self._operations
and isinstance(self._operations[-1], ImportantFunctionOperation)
and self._operations[-1].function == operator.not_
):
return self._exclude_last()
return self._extend(ImportantFunctionOperation(function=operator.not_))
def __call__(self: MagicT, *args: Any, **kwargs: Any) -> MagicT:
return self._extend(CallOperation(args=args, kwargs=kwargs))
def __and__(self: MagicT, other: Any) -> MagicT:
if isinstance(other, MagicFilter):
return self._extend(CombinationOperation(right=other, combinator=and_op))
return self._extend(CombinationOperation(right=other, combinator=operator.and_))
def __rand__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.and_))
def __or__(self: MagicT, other: Any) -> MagicT:
if isinstance(other, MagicFilter):
return self._extend(ImportantCombinationOperation(right=other, combinator=or_op))
return self._extend(ImportantCombinationOperation(right=other, combinator=operator.or_))
def __ror__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.or_))
def __xor__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.xor))
def __rxor__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.xor))
def __rshift__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.rshift))
def __rrshift__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.rshift))
def __lshift__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.lshift))
def __rlshift__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.lshift))
def __add__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.add))
def __radd__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.add))
def __sub__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.sub))
def __rsub__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.sub))
def __mul__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.mul))
def __rmul__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.mul))
def __truediv__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.truediv))
def __rtruediv__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.truediv))
def __floordiv__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.floordiv))
def __rfloordiv__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.floordiv))
def __mod__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.mod))
def __rmod__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.mod))
def __matmul__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.matmul))
def __rmatmul__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.matmul))
def __pow__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.pow))
def __rpow__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.pow))
def __pos__(self: MagicT) -> MagicT:
return self._extend(FunctionOperation(function=operator.pos))
def __neg__(self: MagicT) -> MagicT:
return self._extend(FunctionOperation(function=operator.neg))
def is_(self: MagicT, value: Any) -> MagicT:
return self._extend(CombinationOperation(right=value, combinator=operator.is_))
def is_not(self: MagicT, value: Any) -> MagicT:
return self._extend(CombinationOperation(right=value, combinator=operator.is_not))
def in_(self: MagicT, iterable: Union[Container[Any], MagicT]) -> MagicT:
return self._extend(FunctionOperation(in_op, iterable))
def not_in(self: MagicT, iterable: Union[Container[Any], MagicT]) -> MagicT:
return self._extend(FunctionOperation(not_in_op, iterable))
def contains(self: MagicT, value: Any) -> MagicT:
return self._extend(FunctionOperation(contains_op, value))
def not_contains(self: MagicT, value: Any) -> MagicT:
return self._extend(FunctionOperation(not_contains_op, value))
def len(self: MagicT) -> MagicT:
return self._extend(FunctionOperation(len))
def regexp(
self: MagicT,
pattern: Union[str, Pattern[str]],
*,
mode: Optional[str] = None,
search: Optional[bool] = None,
flags: Union[int, re.RegexFlag] = 0,
) -> MagicT:
if search is not None:
warn(
"Param 'search' is deprecated, use 'mode' instead.",
DeprecationWarning,
)
if mode is not None:
msg = "Can't pass both 'search' and 'mode' params."
raise ParamsConflict(msg)
mode = RegexpMode.SEARCH if search else RegexpMode.MATCH
if mode is None:
mode = RegexpMode.MATCH
if isinstance(pattern, str):
pattern = re.compile(pattern, flags=flags)
regexp_func = getattr(pattern, mode)
return self._extend(FunctionOperation(regexp_func))
def func(self: MagicT, func: Callable[[Any], Any], *args: Any, **kwargs: Any) -> MagicT:
return self._extend(FunctionOperation(func, *args, **kwargs))
def cast(self: MagicT, func: Callable[[Any], Any]) -> MagicT:
return self._extend(CastOperation(func))
def extract(self: MagicT, magic: "MagicT") -> MagicT:
return self._extend(ExtractOperation(magic))
| (operations: Tuple[magic_filter.operations.base.BaseOperation, ...] = ()) -> None |
21,657 | magic_filter.magic | __add__ | null | def __add__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.add))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,658 | magic_filter.magic | __and__ | null | def __and__(self: MagicT, other: Any) -> MagicT:
if isinstance(other, MagicFilter):
return self._extend(CombinationOperation(right=other, combinator=and_op))
return self._extend(CombinationOperation(right=other, combinator=operator.and_))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,659 | magic_filter.magic | __bool__ | null | def __bool__(self) -> bool:
return True
| (self) -> bool |
21,660 | magic_filter.magic | __call__ | null | def __call__(self: MagicT, *args: Any, **kwargs: Any) -> MagicT:
return self._extend(CallOperation(args=args, kwargs=kwargs))
| (self: ~MagicT, *args: Any, **kwargs: Any) -> ~MagicT |
21,661 | magic_filter.magic | __eq__ | null | def __eq__(self: MagicT, other: Any) -> MagicT: # type: ignore
return self._extend(ComparatorOperation(right=other, comparator=operator.eq))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,662 | magic_filter.magic | __floordiv__ | null | def __floordiv__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.floordiv))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,663 | magic_filter.magic | __ge__ | null | def __ge__(self: MagicT, other: Any) -> MagicT:
return self._extend(ComparatorOperation(right=other, comparator=operator.ge))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,664 | magic_filter.magic | __getattr__ | null | def __getattr__(self: MagicT, item: Any) -> MagicT:
if item.startswith("_"):
raise AttributeError(f"{type(self).__name__!r} object has no attribute {item!r}")
return self._extend(GetAttributeOperation(name=item))
| (self: ~MagicT, item: Any) -> ~MagicT |
21,665 | magic_filter.magic | __getitem__ | null | def __getitem__(self: MagicT, item: Any) -> MagicT:
if isinstance(item, MagicFilter):
return self._extend(SelectorOperation(inner=item))
return self._extend(GetItemOperation(key=item))
| (self: ~MagicT, item: Any) -> ~MagicT |
21,666 | magic_filter.magic | __gt__ | null | def __gt__(self: MagicT, other: Any) -> MagicT:
return self._extend(ComparatorOperation(right=other, comparator=operator.gt))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,667 | magic_filter.magic | __init__ | null | def __init__(self, operations: Tuple[BaseOperation, ...] = ()) -> None:
self._operations = operations
| (self, operations: Tuple[magic_filter.operations.base.BaseOperation, ...] = ()) -> NoneType |
21,668 | magic_filter.magic | __invert__ | null | def __invert__(self: MagicT) -> MagicT:
if (
self._operations
and isinstance(self._operations[-1], ImportantFunctionOperation)
and self._operations[-1].function == operator.not_
):
return self._exclude_last()
return self._extend(ImportantFunctionOperation(function=operator.not_))
| (self: ~MagicT) -> ~MagicT |
21,669 | magic_filter.magic | __le__ | null | def __le__(self: MagicT, other: Any) -> MagicT:
return self._extend(ComparatorOperation(right=other, comparator=operator.le))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,670 | magic_filter.magic | __len__ | null | def __len__(self) -> int:
raise TypeError(f"Length can't be taken using len() function. Use {type(self).__name__}.len() instead.")
| (self) -> int |
21,671 | magic_filter.magic | __lshift__ | null | def __lshift__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.lshift))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,672 | magic_filter.magic | __lt__ | null | def __lt__(self: MagicT, other: Any) -> MagicT:
return self._extend(ComparatorOperation(right=other, comparator=operator.lt))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,673 | magic_filter.magic | __matmul__ | null | def __matmul__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.matmul))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,674 | magic_filter.magic | __mod__ | null | def __mod__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.mod))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,675 | magic_filter.magic | __mul__ | null | def __mul__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.mul))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,676 | magic_filter.magic | __ne__ | null | def __ne__(self: MagicT, other: Any) -> MagicT: # type: ignore
return self._extend(ComparatorOperation(right=other, comparator=operator.ne))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,677 | magic_filter.magic | __neg__ | null | def __neg__(self: MagicT) -> MagicT:
return self._extend(FunctionOperation(function=operator.neg))
| (self: ~MagicT) -> ~MagicT |
21,678 | magic_filter.magic | __or__ | null | def __or__(self: MagicT, other: Any) -> MagicT:
if isinstance(other, MagicFilter):
return self._extend(ImportantCombinationOperation(right=other, combinator=or_op))
return self._extend(ImportantCombinationOperation(right=other, combinator=operator.or_))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,679 | magic_filter.magic | __pos__ | null | def __pos__(self: MagicT) -> MagicT:
return self._extend(FunctionOperation(function=operator.pos))
| (self: ~MagicT) -> ~MagicT |
21,680 | magic_filter.magic | __pow__ | null | def __pow__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.pow))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,681 | magic_filter.magic | __radd__ | null | def __radd__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.add))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,682 | magic_filter.magic | __rand__ | null | def __rand__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.and_))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,683 | magic_filter.magic | __rfloordiv__ | null | def __rfloordiv__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.floordiv))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,684 | magic_filter.magic | __rlshift__ | null | def __rlshift__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.lshift))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,685 | magic_filter.magic | __rmatmul__ | null | def __rmatmul__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.matmul))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,686 | magic_filter.magic | __rmod__ | null | def __rmod__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.mod))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,687 | magic_filter.magic | __rmul__ | null | def __rmul__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.mul))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,688 | magic_filter.magic | __ror__ | null | def __ror__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.or_))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,689 | magic_filter.magic | __rpow__ | null | def __rpow__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.pow))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,690 | magic_filter.magic | __rrshift__ | null | def __rrshift__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.rshift))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,691 | magic_filter.magic | __rshift__ | null | def __rshift__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.rshift))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,692 | magic_filter.magic | __rsub__ | null | def __rsub__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.sub))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,693 | magic_filter.magic | __rtruediv__ | null | def __rtruediv__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.truediv))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,694 | magic_filter.magic | __rxor__ | null | def __rxor__(self: MagicT, other: Any) -> MagicT:
return self._extend(RCombinationOperation(left=other, combinator=operator.xor))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,695 | magic_filter.magic | __sub__ | null | def __sub__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.sub))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,696 | magic_filter.magic | __truediv__ | null | def __truediv__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.truediv))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,697 | magic_filter.magic | __xor__ | null | def __xor__(self: MagicT, other: Any) -> MagicT:
return self._extend(CombinationOperation(right=other, combinator=operator.xor))
| (self: ~MagicT, other: Any) -> ~MagicT |
21,698 | magic_filter.magic | _exclude_last | null | def _exclude_last(self: MagicT) -> MagicT:
return self._new(self._operations[:-1])
| (self: ~MagicT) -> ~MagicT |
21,699 | magic_filter.magic | _extend | null | def _extend(self: MagicT, operation: BaseOperation) -> MagicT:
return self._new(self._operations + (operation,))
| (self: ~MagicT, operation: magic_filter.operations.base.BaseOperation) -> ~MagicT |
21,700 | magic_filter.magic | _replace_last | null | def _replace_last(self: MagicT, operation: BaseOperation) -> MagicT:
return self._new(self._operations[:-1] + (operation,))
| (self: ~MagicT, operation: magic_filter.operations.base.BaseOperation) -> ~MagicT |
21,701 | magic_filter.magic | _resolve | null | def _resolve(self, value: Any, operations: Optional[Tuple[BaseOperation, ...]] = None) -> Any:
initial_value = value
if operations is None:
operations = self._operations
rejected = False
for index, operation in enumerate(operations):
if rejected and not operation.important:
continue
try:
value = operation.resolve(value=value, initial_value=initial_value)
except SwitchModeToAll:
return all(self._resolve(value=item, operations=operations[index + 1 :]) for item in value)
except SwitchModeToAny:
return any(self._resolve(value=item, operations=operations[index + 1 :]) for item in value)
except RejectOperations:
rejected = True
value = None
continue
rejected = False
return value
| (self, value: Any, operations: Optional[Tuple[magic_filter.operations.base.BaseOperation, ...]] = None) -> Any |
21,703 | magic_filter.magic | cast | null | def cast(self: MagicT, func: Callable[[Any], Any]) -> MagicT:
return self._extend(CastOperation(func))
| (self: ~MagicT, func: Callable[[Any], Any]) -> ~MagicT |
21,704 | magic_filter.magic | contains | null | def contains(self: MagicT, value: Any) -> MagicT:
return self._extend(FunctionOperation(contains_op, value))
| (self: ~MagicT, value: Any) -> ~MagicT |
21,705 | magic_filter.magic | extract | null | def extract(self: MagicT, magic: "MagicT") -> MagicT:
return self._extend(ExtractOperation(magic))
| (self: ~MagicT, magic: ~MagicT) -> ~MagicT |
21,706 | magic_filter.magic | func | null | def func(self: MagicT, func: Callable[[Any], Any], *args: Any, **kwargs: Any) -> MagicT:
return self._extend(FunctionOperation(func, *args, **kwargs))
| (self: ~MagicT, func: Callable[[Any], Any], *args: Any, **kwargs: Any) -> ~MagicT |
21,707 | magic_filter.magic | in_ | null | def in_(self: MagicT, iterable: Union[Container[Any], MagicT]) -> MagicT:
return self._extend(FunctionOperation(in_op, iterable))
| (self: ~MagicT, iterable: Union[Container[Any], ~MagicT]) -> ~MagicT |
21,708 | magic_filter.magic | is_ | null | def is_(self: MagicT, value: Any) -> MagicT:
return self._extend(CombinationOperation(right=value, combinator=operator.is_))
| (self: ~MagicT, value: Any) -> ~MagicT |
21,709 | magic_filter.magic | is_not | null | def is_not(self: MagicT, value: Any) -> MagicT:
return self._extend(CombinationOperation(right=value, combinator=operator.is_not))
| (self: ~MagicT, value: Any) -> ~MagicT |
21,710 | magic_filter.magic | len | null | def len(self: MagicT) -> MagicT:
return self._extend(FunctionOperation(len))
| (self: ~MagicT) -> ~MagicT |
21,711 | magic_filter.magic | not_contains | null | def not_contains(self: MagicT, value: Any) -> MagicT:
return self._extend(FunctionOperation(not_contains_op, value))
| (self: ~MagicT, value: Any) -> ~MagicT |
21,712 | magic_filter.magic | not_in | null | def not_in(self: MagicT, iterable: Union[Container[Any], MagicT]) -> MagicT:
return self._extend(FunctionOperation(not_in_op, iterable))
| (self: ~MagicT, iterable: Union[Container[Any], ~MagicT]) -> ~MagicT |
21,713 | magic_filter.magic | regexp | null | def regexp(
self: MagicT,
pattern: Union[str, Pattern[str]],
*,
mode: Optional[str] = None,
search: Optional[bool] = None,
flags: Union[int, re.RegexFlag] = 0,
) -> MagicT:
if search is not None:
warn(
"Param 'search' is deprecated, use 'mode' instead.",
DeprecationWarning,
)
if mode is not None:
msg = "Can't pass both 'search' and 'mode' params."
raise ParamsConflict(msg)
mode = RegexpMode.SEARCH if search else RegexpMode.MATCH
if mode is None:
mode = RegexpMode.MATCH
if isinstance(pattern, str):
pattern = re.compile(pattern, flags=flags)
regexp_func = getattr(pattern, mode)
return self._extend(FunctionOperation(regexp_func))
| (self: ~MagicT, pattern: Union[str, Pattern[str]], *, mode: Optional[str] = None, search: Optional[bool] = None, flags: Union[int, re.RegexFlag] = 0) -> ~MagicT |
21,714 | magic_filter.magic | resolve | null | def resolve(self: MagicT, value: Any) -> Any:
return self._resolve(value=value)
| (self: ~MagicT, value: Any) -> Any |
21,715 | magic_filter.magic | RegexpMode | null | class RegexpMode:
SEARCH = "search"
MATCH = "match"
FINDALL = "findall"
FINDITER = "finditer"
FULLMATCH = "fullmatch"
| () |
21,722 | basicauth | DecodeError | null | class DecodeError(Exception):
pass
| null |
21,723 | basicauth | EncodeError | null | class EncodeError(Exception):
pass
| null |
21,725 | base64 | b64encode | Encode the bytes-like object s using Base64 and return a bytes object.
Optional altchars should be a byte string of length 2 which specifies an
alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
| def b64encode(s, altchars=None):
"""Encode the bytes-like object s using Base64 and return a bytes object.
Optional altchars should be a byte string of length 2 which specifies an
alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
"""
encoded = binascii.b2a_base64(s, newline=False)
if altchars is not None:
assert len(altchars) == 2, repr(altchars)
return encoded.translate(bytes.maketrans(b'+/', altchars))
return encoded
| (s, altchars=None) |
21,726 | basicauth | decode | Decode an encrypted HTTP basic authentication string. Returns a tuple of
the form (username, password), and raises a DecodeError exception if
nothing could be decoded.
| def decode(encoded_str):
"""Decode an encrypted HTTP basic authentication string. Returns a tuple of
the form (username, password), and raises a DecodeError exception if
nothing could be decoded.
"""
split = encoded_str.strip().split(' ')
# If split is only one element, try to decode the username and password
# directly.
if len(split) == 1:
try:
username, password = b64decode(split[0]).decode().split(':', 1)
except:
raise DecodeError
# If there are only two elements, check the first and ensure it says
# 'basic' so that we know we're about to decode the right thing. If not,
# bail out.
elif len(split) == 2:
if split[0].strip().lower() == 'basic':
try:
username, password = b64decode(split[1]).decode().split(':', 1)
except:
raise DecodeError
else:
raise DecodeError
# If there are more than 2 elements, something crazy must be happening.
# Bail.
else:
raise DecodeError
return unquote(username), unquote(password)
| (encoded_str) |
21,727 | basicauth | encode | Returns an HTTP basic authentication encrypted string given a valid
username and password.
| def encode(username, password):
"""Returns an HTTP basic authentication encrypted string given a valid
username and password.
"""
if ':' in username:
raise EncodeError
username_password = f'{quote(username)}:{quote(password)}'
return f'Basic {b64encode(username_password.encode()).decode()}'
| (username, password) |
21,729 | urllib.parse | unquote | Replace %xx escapes by their single-character equivalent. The optional
encoding and errors parameters specify how to decode percent-encoded
sequences into Unicode characters, as accepted by the bytes.decode()
method.
By default, percent-encoded sequences are decoded with UTF-8, and invalid
sequences are replaced by a placeholder character.
unquote('abc%20def') -> 'abc def'.
| def unquote(string, encoding='utf-8', errors='replace'):
"""Replace %xx escapes by their single-character equivalent. The optional
encoding and errors parameters specify how to decode percent-encoded
sequences into Unicode characters, as accepted by the bytes.decode()
method.
By default, percent-encoded sequences are decoded with UTF-8, and invalid
sequences are replaced by a placeholder character.
unquote('abc%20def') -> 'abc def'.
"""
if isinstance(string, bytes):
return unquote_to_bytes(string).decode(encoding, errors)
if '%' not in string:
string.split
return string
if encoding is None:
encoding = 'utf-8'
if errors is None:
errors = 'replace'
bits = _asciire.split(string)
res = [bits[0]]
append = res.append
for i in range(1, len(bits), 2):
append(unquote_to_bytes(bits[i]).decode(encoding, errors))
append(bits[i + 1])
return ''.join(res)
| (string, encoding='utf-8', errors='replace') |
21,730 | aiosocks.errors | InvalidServerReply | null | class InvalidServerReply(SocksError):
pass
| null |
21,731 | aiosocks.errors | InvalidServerVersion | null | class InvalidServerVersion(SocksError):
pass
| null |
21,732 | aiosocks.errors | LoginAuthenticationFailed | null | class LoginAuthenticationFailed(SocksError):
pass
| null |
21,733 | aiosocks.errors | NoAcceptableAuthMethods | null | class NoAcceptableAuthMethods(SocksError):
pass
| null |
21,734 | aiosocks.helpers | Socks4Addr | null | class Socks4Addr(SocksAddr):
pass
| (host, port=1080) |
21,736 | aiosocks.helpers | __new__ | null | def __new__(cls, host, port=1080):
if host is None:
raise ValueError('None is not allowed as host value')
if port is None:
port = 1080 # default socks server port
return super().__new__(cls, host, port)
| (cls, host, port=1080) |
21,739 | collections | _replace | Return a new SocksServer object replacing specified fields with new values | def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
# Validate the field names. At the user's option, either generate an error
# message or automatically replace the field name with a valid name.
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = _sys.intern(str(typename))
if rename:
seen = set()
for index, name in enumerate(field_names):
if (not name.isidentifier()
or _iskeyword(name)
or name.startswith('_')
or name in seen):
field_names[index] = f'_{index}'
seen.add(name)
for name in [typename] + field_names:
if type(name) is not str:
raise TypeError('Type names and field names must be strings')
if not name.isidentifier():
raise ValueError('Type names and field names must be valid '
f'identifiers: {name!r}')
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
f'keyword: {name!r}')
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
f'{name!r}')
if name in seen:
raise ValueError(f'Encountered duplicate field name: {name!r}')
seen.add(name)
field_defaults = {}
if defaults is not None:
defaults = tuple(defaults)
if len(defaults) > len(field_names):
raise TypeError('Got more default values than field names')
field_defaults = dict(reversed(list(zip(reversed(field_names),
reversed(defaults)))))
# Variables used in the methods and docstrings
field_names = tuple(map(_sys.intern, field_names))
num_fields = len(field_names)
arg_list = ', '.join(field_names)
if num_fields == 1:
arg_list += ','
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
tuple_new = tuple.__new__
_dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
# Create all the named tuple methods to be added to the class namespace
namespace = {
'_tuple_new': tuple_new,
'__builtins__': {},
'__name__': f'namedtuple_{typename}',
}
code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
__new__ = eval(code, namespace)
__new__.__name__ = '__new__'
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults
@classmethod
def _make(cls, iterable):
result = tuple_new(cls, iterable)
if _len(result) != num_fields:
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
return result
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
'or iterable')
def _replace(self, /, **kwds):
result = self._make(_map(kwds.pop, field_names, self))
if kwds:
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
return result
_replace.__doc__ = (f'Return a new {typename} object replacing specified '
'fields with new values')
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + repr_fmt % self
def _asdict(self):
'Return a new dict which maps field names to their values.'
return _dict(_zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return _tuple(self)
# Modify function metadata to help with introspection and debugging
for method in (
__new__,
_make.__func__,
_replace,
__repr__,
_asdict,
__getnewargs__,
):
method.__qualname__ = f'{typename}.{method.__name__}'
# Build-up the class namespace dictionary
# and use type() to build the result class
class_namespace = {
'__doc__': f'{typename}({arg_list})',
'__slots__': (),
'_fields': field_names,
'_field_defaults': field_defaults,
'__new__': __new__,
'_make': _make,
'_replace': _replace,
'__repr__': __repr__,
'_asdict': _asdict,
'__getnewargs__': __getnewargs__,
'__match_args__': field_names,
}
for index, name in enumerate(field_names):
doc = _sys.intern(f'Alias for field number {index}')
class_namespace[name] = _tuplegetter(index, doc)
result = type(typename, (tuple,), class_namespace)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython), or where the user has
# specified a particular module.
if module is None:
try:
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
if module is not None:
result.__module__ = module
return result
| (self, /, **kwds) |
21,740 | aiosocks.helpers | Socks4Auth | null | class Socks4Auth(namedtuple('Socks4Auth', ['login', 'encoding'])):
def __new__(cls, login, encoding='utf-8'):
if login is None:
raise ValueError('None is not allowed as login value')
return super().__new__(cls, login.encode(encoding), encoding)
| (login, encoding='utf-8') |
21,742 | aiosocks.helpers | __new__ | null | def __new__(cls, login, encoding='utf-8'):
if login is None:
raise ValueError('None is not allowed as login value')
return super().__new__(cls, login.encode(encoding), encoding)
| (cls, login, encoding='utf-8') |
21,745 | collections | _replace | Return a new Socks4Auth object replacing specified fields with new values | def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
# Validate the field names. At the user's option, either generate an error
# message or automatically replace the field name with a valid name.
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = _sys.intern(str(typename))
if rename:
seen = set()
for index, name in enumerate(field_names):
if (not name.isidentifier()
or _iskeyword(name)
or name.startswith('_')
or name in seen):
field_names[index] = f'_{index}'
seen.add(name)
for name in [typename] + field_names:
if type(name) is not str:
raise TypeError('Type names and field names must be strings')
if not name.isidentifier():
raise ValueError('Type names and field names must be valid '
f'identifiers: {name!r}')
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
f'keyword: {name!r}')
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
f'{name!r}')
if name in seen:
raise ValueError(f'Encountered duplicate field name: {name!r}')
seen.add(name)
field_defaults = {}
if defaults is not None:
defaults = tuple(defaults)
if len(defaults) > len(field_names):
raise TypeError('Got more default values than field names')
field_defaults = dict(reversed(list(zip(reversed(field_names),
reversed(defaults)))))
# Variables used in the methods and docstrings
field_names = tuple(map(_sys.intern, field_names))
num_fields = len(field_names)
arg_list = ', '.join(field_names)
if num_fields == 1:
arg_list += ','
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
tuple_new = tuple.__new__
_dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
# Create all the named tuple methods to be added to the class namespace
namespace = {
'_tuple_new': tuple_new,
'__builtins__': {},
'__name__': f'namedtuple_{typename}',
}
code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
__new__ = eval(code, namespace)
__new__.__name__ = '__new__'
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults
@classmethod
def _make(cls, iterable):
result = tuple_new(cls, iterable)
if _len(result) != num_fields:
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
return result
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
'or iterable')
def _replace(self, /, **kwds):
result = self._make(_map(kwds.pop, field_names, self))
if kwds:
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
return result
_replace.__doc__ = (f'Return a new {typename} object replacing specified '
'fields with new values')
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + repr_fmt % self
def _asdict(self):
'Return a new dict which maps field names to their values.'
return _dict(_zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return _tuple(self)
# Modify function metadata to help with introspection and debugging
for method in (
__new__,
_make.__func__,
_replace,
__repr__,
_asdict,
__getnewargs__,
):
method.__qualname__ = f'{typename}.{method.__name__}'
# Build-up the class namespace dictionary
# and use type() to build the result class
class_namespace = {
'__doc__': f'{typename}({arg_list})',
'__slots__': (),
'_fields': field_names,
'_field_defaults': field_defaults,
'__new__': __new__,
'_make': _make,
'_replace': _replace,
'__repr__': __repr__,
'_asdict': _asdict,
'__getnewargs__': __getnewargs__,
'__match_args__': field_names,
}
for index, name in enumerate(field_names):
doc = _sys.intern(f'Alias for field number {index}')
class_namespace[name] = _tuplegetter(index, doc)
result = type(typename, (tuple,), class_namespace)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython), or where the user has
# specified a particular module.
if module is None:
try:
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
if module is not None:
result.__module__ = module
return result
| (self, /, **kwds) |
21,746 | aiosocks.protocols | Socks4Protocol | null | class Socks4Protocol(BaseSocksProtocol):
def __init__(self, proxy, proxy_auth, dst, app_protocol_factory, waiter,
remote_resolve=True, loop=None, ssl=False,
server_hostname=None, negotiate_done_cb=None,
reader_limit=DEFAULT_LIMIT):
proxy_auth = proxy_auth or Socks4Auth('')
if not isinstance(proxy, Socks4Addr):
raise ValueError('Invalid proxy format')
if not isinstance(proxy_auth, Socks4Auth):
raise ValueError('Invalid proxy_auth format')
super().__init__(proxy, proxy_auth, dst, app_protocol_factory,
waiter, remote_resolve=remote_resolve, loop=loop,
ssl=ssl, server_hostname=server_hostname,
reader_limit=reader_limit,
negotiate_done_cb=negotiate_done_cb)
async def socks_request(self, cmd):
# prepare destination addr/port
host, port = self._dst_host, self._dst_port
port_bytes = struct.pack(b'>H', port)
include_hostname = False
try:
host_bytes = socket.inet_aton(host)
except socket.error:
if self._remote_resolve:
host_bytes = bytes([c.NULL, c.NULL, c.NULL, 0x01])
include_hostname = True
else:
# it's not an IP number, so it's probably a DNS name.
family, host = await self._get_dst_addr()
host_bytes = socket.inet_aton(host)
# build and send connect command
req = [c.SOCKS_VER4, cmd, port_bytes,
host_bytes, self._auth.login, c.NULL]
if include_hostname:
req += [self._dst_host.encode('idna'), c.NULL]
self.write_request(req)
# read/process result
resp = await self.read_response(8)
if resp[0] != c.NULL:
raise InvalidServerReply('SOCKS4 proxy server sent invalid data')
if resp[1] != c.SOCKS4_GRANTED:
error = c.SOCKS4_ERRORS.get(resp[1], 'Unknown error')
raise SocksError('[Errno {0:#04x}]: {1}'.format(resp[1], error))
binded = socket.inet_ntoa(resp[4:]), struct.unpack('>H', resp[2:4])[0]
return (host, port), binded
| (proxy, proxy_auth, dst, app_protocol_factory, waiter, remote_resolve=True, loop=None, ssl=False, server_hostname=None, negotiate_done_cb=None, reader_limit=65536) |
21,747 | asyncio.streams | __del__ | null | def __del__(self):
# Prevent reports about unhandled exceptions.
# Better than self._closed._log_traceback = False hack
try:
closed = self._closed
except AttributeError:
pass # failed constructor
else:
if closed.done() and not closed.cancelled():
closed.exception()
| (self) |
21,748 | aiosocks.protocols | __init__ | null | def __init__(self, proxy, proxy_auth, dst, app_protocol_factory, waiter,
remote_resolve=True, loop=None, ssl=False,
server_hostname=None, negotiate_done_cb=None,
reader_limit=DEFAULT_LIMIT):
proxy_auth = proxy_auth or Socks4Auth('')
if not isinstance(proxy, Socks4Addr):
raise ValueError('Invalid proxy format')
if not isinstance(proxy_auth, Socks4Auth):
raise ValueError('Invalid proxy_auth format')
super().__init__(proxy, proxy_auth, dst, app_protocol_factory,
waiter, remote_resolve=remote_resolve, loop=loop,
ssl=ssl, server_hostname=server_hostname,
reader_limit=reader_limit,
negotiate_done_cb=negotiate_done_cb)
| (self, proxy, proxy_auth, dst, app_protocol_factory, waiter, remote_resolve=True, loop=None, ssl=False, server_hostname=None, negotiate_done_cb=None, reader_limit=65536) |
21,749 | asyncio.streams | _drain_helper | null | def connection_lost(self, exc):
self._connection_lost = True
# Wake up the writer(s) if currently paused.
if not self._paused:
return
for waiter in self._drain_waiters:
if not waiter.done():
if exc is None:
waiter.set_result(None)
else:
waiter.set_exception(exc)
| (self) |
21,750 | asyncio.streams | _get_close_waiter | null | def _get_close_waiter(self, stream):
return self._closed
| (self, stream) |
21,751 | aiosocks.protocols | _get_dst_addr | null | def write_request(self, request):
bdata = bytearray()
for item in request:
if isinstance(item, int):
bdata.append(item)
elif isinstance(item, (bytearray, bytes)):
bdata += item
else:
raise ValueError('Unsupported item')
self._stream_writer.write(bdata)
| (self) |
21,752 | aiosocks.protocols | connection_lost | null | def connection_lost(self, exc):
if self._negotiate_done and self._app_protocol is not self:
self._loop.call_soon(self._app_protocol.connection_lost, exc)
super().connection_lost(exc)
| (self, exc) |
21,753 | aiosocks.protocols | connection_made | null | def connection_made(self, transport):
# connection_made is called
if self._transport:
return
super().connection_made(transport)
self._transport = transport
| (self, transport) |
21,754 | aiosocks.protocols | data_received | null | def data_received(self, data):
if self._negotiate_done and self._app_protocol is not self:
self._app_protocol.data_received(data)
else:
super().data_received(data)
| (self, data) |
21,755 | aiosocks.protocols | eof_received | null | def eof_received(self):
if self._negotiate_done and self._app_protocol is not self:
self._app_protocol.eof_received()
super().eof_received()
| (self) |
21,756 | aiosocks.protocols | negotiate | null | def __init__(self, proxy, proxy_auth, dst, app_protocol_factory, waiter, *,
remote_resolve=True, loop=None, ssl=False,
server_hostname=None, negotiate_done_cb=None,
reader_limit=DEFAULT_LIMIT):
if not isinstance(dst, (tuple, list)) or len(dst) != 2:
raise ValueError(
'Invalid dst format, tuple("dst_host", dst_port))'
)
self._proxy = proxy
self._auth = proxy_auth
self._dst_host, self._dst_port = dst
self._remote_resolve = remote_resolve
self._waiter = waiter
self._ssl = ssl
self._server_hostname = server_hostname
self._negotiate_done_cb = negotiate_done_cb
self._loop = loop or asyncio.get_event_loop()
self._transport = None
self._negotiate_done = False
self._proxy_peername = None
self._proxy_sockname = None
if app_protocol_factory:
self._app_protocol = app_protocol_factory()
else:
self._app_protocol = self
reader = asyncio.StreamReader(loop=self._loop, limit=reader_limit)
super().__init__(stream_reader=reader,
client_connected_cb=self.negotiate, loop=self._loop)
| (self, reader, writer) |
21,757 | aiosocks.protocols | pause_writing | null | def pause_writing(self):
if self._negotiate_done and self._app_protocol is not self:
self._app_protocol.pause_writing()
else:
super().pause_writing()
| (self) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.