path
stringlengths 9
117
| type
stringclasses 2
values | project
stringclasses 10
values | commit_hash
stringlengths 40
40
| commit_message
stringlengths 1
137
| ground_truth
stringlengths 0
2.74k
| main_code
stringlengths 102
3.37k
| context
stringlengths 0
14.7k
|
---|---|---|---|---|---|---|---|
bitsandbytes.diagnostics.cuda/find_cuda_libraries_in_path_list
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
0c64a0d8c377734377fa591226e3b2c65fa8aaf8
|
Merge pull request #1148 from stevhliu/fsdp-qlora
|
<17>:<add> except (OSError, PermissionError):
<del> except PermissionError:
|
# module: bitsandbytes.diagnostics.cuda
def find_cuda_libraries_in_path_list(paths_list_candidate: str) -> Iterable[Path]:
<0> for dir_string in paths_list_candidate.split(os.pathsep):
<1> if not dir_string:
<2> continue
<3> if os.sep not in dir_string:
<4> continue
<5> try:
<6> dir = Path(dir_string)
<7> try:
<8> if not dir.exists():
<9> logger.warning(f"The directory listed in your path is found to be non-existent: {dir}")
<10> continue
<11> except OSError: # Assume an esoteric error trying to poke at the directory
<12> pass
<13> for lib_pattern in CUDA_RUNTIME_LIB_PATTERNS:
<14> for pth in dir.glob(lib_pattern):
<15> if pth.is_file():
<16> yield pth
<17> except PermissionError:
<18> pass
<19>
|
===========unchanged ref 0===========
at: bitsandbytes.diagnostics.cuda
CUDA_RUNTIME_LIB_PATTERNS = (
"cudart64*.dll", # Windows
"libcudart*.so*", # libcudart.so, libcudart.so.11.0, libcudart.so.12.0, libcudart.so.12.1, libcudart.so.12.2 etc.
"nvcuda*.dll", # Windows
)
logger = logging.getLogger(__name__)
at: logging.Logger
warning(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: pathlib
Path()
at: pathlib.Path
__slots__ = ()
glob(pattern: str) -> Generator[_P, None, None]
exists() -> bool
is_file() -> bool
at: typing
Iterable = _alias(collections.abc.Iterable, 1)
===========changed ref 0===========
# module: bitsandbytes.functional
def get_4bit_type(typename, device=None, blocksize=64):
if device is None:
device = "cuda"
data = None
if typename == "nf4":
""" Implements the NF4 data type.
Constructs a quantization data type where each bin has equal area under a standard normal distribution N(0, 1) that
is normalized into the range [-1, 1].
For more information read the paper: QLoRA: Efficient Finetuning of Quantized LLMs (https://arxiv.org/abs/2305.14314)
Implementation of the NF4 data type in bitsandbytes can be found in the `create_normal_map` function in
the `functional.py` file: https://github.com/TimDettmers/bitsandbytes/blob/main/bitsandbytes/functional.py#L236.
"""
data = [
-1.0,
-0.6961928009986877,
-0.5250730514526367,
-0.39491748809814453,
-0.28444138169288635,
-0.18477343022823334,
-0.09105003625154495,
0.0,
0.07958029955625534,
0.16093020141124725,
0.24611230194568634,
0.33791524171829224,
0.44070982933044434,
0.5626170039176941,
0.7229568362236023,
1.0,
]
elif typename == "fp4":
# 0b000 = 0
# 0b001 = 0.0625
# 0b010 = 8
# 0b011 = 12
# 0b100 = 4
# 0b101 = 6
# 0b110 = 2
# 0</s>
===========changed ref 1===========
# module: bitsandbytes.functional
def get_4bit_type(typename, device=None, blocksize=64):
# offset: 1
<s> = 12
# 0b100 = 4
# 0b101 = 6
# 0b110 = 2
# 0b111 = 3
# can also be created with bnb.functional.create_fp8_map(signed=True, exponent_bits=2, precision_bits=1, total_bits=4)
data = [0, 0.0625, 8.0, 12.0, 4.0, 6.0, 2.0, 3.0, -0, -0.0625, -8.0, -12.0, -4.0, -6.0, -2.0, -3.0]
elif typename == "int4":
data = [7, 6, 5, 4, 3, 2, 1, 0, -0, -1, -2, -3, -4, -5, -6, -7]
elif typename == "af4":
# Taken from: NF4 Isn't Information Theoretically Optimal (and that's Good)
# https://arxiv.org/abs/2306.06965
if blocksize == 64:
data = [
-1.0,
-0.69441008,
-0.51243739,
-0.3736951,
-0.25607552,
-0.14982478,
-0.04934812,
0.0,
0.04273164,
0.12934483,
0.21961274,
0.31675666,
0.42563882,
0.55496234,
0.72424863,
1.0,
][::-1]
else:
raise NotImplementedError("4-bit AbnormalFloats currently only</s>
===========changed ref 2===========
# module: bitsandbytes.functional
def get_4bit_type(typename, device=None, blocksize=64):
# offset: 2
<s> 64.")
if data is None:
raise NotImplementedError(f"Typename {typename} not supported")
+ data = torch.tensor(data, device=device)
- data = Tensor(data)
+ data.div_(data.abs().max())
- data /= data.abs().max()
+
assert data.numel() == 16
+ return data
- return data.to(device)
|
bitsandbytes.nn.modules/maybe_rearrange_weight
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
7449d713eb65caa186ed0f8d6c763b58bb3e61f9
|
[`Core`] Change 8-bit serialization weight format format (#1164)
|
<6>:<add> if isinstance(weight_format, torch.Tensor):
<add> weight_format = weight_format.item()
<add>
<add> # For new weights format storage type, we explicitly check
<add> # if weights_format is on the mapping
<add> if isinstance(weight_format, int) and weight_format not in INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING:
<add> raise ValueError(f"Expected supported weight format - got {weight_format}")
<add> elif isinstance(weight_format, int) and weight_format in INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING:
<add> weight_format = INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING[weight_format]
<add>
|
# module: bitsandbytes.nn.modules
def maybe_rearrange_weight(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
<0> weight = state_dict.get(f"{prefix}weight")
<1> if weight is None:
<2> # if the state dict has no weights for this layer (e.g., LoRA finetuning), do nothing
<3> return
<4> weight_format = state_dict.pop(f"{prefix}weight_format", "row")
<5>
<6> if weight_format != "row":
<7> tile_indices = get_tile_inds(weight_format, weight.device)
<8> state_dict[f"{prefix}weight"] = undo_layout(weight, tile_indices)
<9>
|
===========unchanged ref 0===========
at: bitsandbytes.nn.modules.Int8Params.to
new_param = Int8Params(
super().to(device=device, dtype=dtype, non_blocking=non_blocking),
requires_grad=self.requires_grad,
has_fp16_weights=self.has_fp16_weights,
)
===========changed ref 0===========
# module: bitsandbytes.utils
+ LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING = {"row": 0, "col32": 1, "col_turing": 2, "col_ampere": 3}
+ INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING = {val: name for (name, val) in LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING.items()}
-
|
bitsandbytes.nn.modules/Linear8bitLt._save_to_state_dict
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
7449d713eb65caa186ed0f8d6c763b58bb3e61f9
|
[`Core`] Change 8-bit serialization weight format format (#1164)
|
<18>:<add> destination[format_name] = torch.tensor(0, dtype=torch.uint8)
<del> destination[format_name] = "row"
<21>:<add> destination[format_name] = torch.tensor(0, dtype=torch.uint8)
<del> destination[format_name] = "row"
<24>:<add> weights_format = self.state.formatB
<del> destination[format_name] = self.state.formatB
<25>:<add> # At this point `weights_format` is an str
<add> if weights_format not in LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING:
<add> raise ValueError(f"Unrecognized weights format {weights_format}")
|
# module: bitsandbytes.nn.modules
class Linear8bitLt(nn.Linear):
def _save_to_state_dict(self, destination, prefix, keep_vars):
<0> super()._save_to_state_dict(destination, prefix, keep_vars)
<1>
<2> # we only need to save SCB as extra data, because CB for quantized weights is already stored in weight.data
<3> scb_name = "SCB"
<4>
<5> # case 1: .cuda was called, SCB is in self.weight
<6> param_from_weight = getattr(self.weight, scb_name)
<7> # case 2: self.init_8bit_state was called, SCB is in self.state
<8> param_from_state = getattr(self.state, scb_name)
<9> # case 3: SCB is in self.state, weight layout reordered after first forward()
<10> layout_reordered = self.state.CxB is not None
<11>
<12> key_name = prefix + f"{scb_name}"
<13> format_name = prefix + "weight_format"
<14>
<15> if not self.state.has_fp16_weights:
<16> if param_from_weight is not None:
<17> destination[key_name] = param_from_weight if keep_vars else param_from_weight.detach()
<18> destination[format_name] = "row"
<19> elif param_from_state is not None and not layout_reordered:
<20> destination[key_name] = param_from_state if keep_vars else param_from_state.detach()
<21> destination[format_name] = "row"
<22> elif param_from_state is not None:
<23> destination[key_name] = param_from_state if keep_vars else param_from_state.detach()
<24> destination[format_name] = self.state.formatB
<25>
|
===========unchanged ref 0===========
at: bitsandbytes.autograd._functions
MatmulLtState(_tile_indices: Optional[torch.Tensor]=None, force_no_igemmlt: bool=False)
at: bitsandbytes.autograd._functions.MatmulLtState
_tile_indices: Optional[torch.Tensor] = None
force_no_igemmlt: bool = False
CB = None
CxB = None
SB = None
SCB = None
CxBt = None
SBt = None
CBt = None
subB = None
outlier_pool = None
has_accumulated_gradients = False
threshold = 0.0
idx = None
is_training = True
has_fp16_weights = True
memory_efficient_backward = False
use_pool = False
formatB = F.get_special_format_str()
at: bitsandbytes.autograd._functions.MatmulLtState.reset_grads
self.CxB = None
at: bitsandbytes.nn.modules
Int8Params(data: Tensor=..., requires_grad: builtins.bool=...)
maybe_rearrange_weight(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
at: bitsandbytes.nn.modules.Int8Params.cuda
self.data = CB
at: torch.nn.modules.linear.Linear
__constants__ = ['in_features', 'out_features']
in_features: int
out_features: int
weight: Tensor
__init__(in_features: int, out_features: int, bias: bool=True, device=None, dtype=None) -> None
at: torch.nn.modules.module.Module
dump_patches: bool = False
_version: int = 1
training: bool
_parameters: Dict[str, Optional[Parameter]]
===========unchanged ref 1===========
_buffers: Dict[str, Optional[Tensor]]
_non_persistent_buffers_set: Set[str]
_backward_pre_hooks: Dict[int, Callable]
_backward_hooks: Dict[int, Callable]
_is_full_backward_hook: Optional[bool]
_forward_hooks: Dict[int, Callable]
_forward_hooks_with_kwargs: Dict[int, bool]
_forward_hooks_always_called: Dict[int, bool]
_forward_pre_hooks: Dict[int, Callable]
_forward_pre_hooks_with_kwargs: Dict[int, bool]
_state_dict_hooks: Dict[int, Callable]
_load_state_dict_pre_hooks: Dict[int, Callable]
_state_dict_pre_hooks: Dict[int, Callable]
_load_state_dict_post_hooks: Dict[int, Callable]
_modules: Dict[str, Optional['Module']]
call_super_init: bool = False
_compiled_call_impl : Optional[Callable] = None
forward: Callable[..., Any] = _forward_unimplemented
__call__ : Callable[..., Any] = _wrapped_call_impl
_save_to_state_dict(self, destination, prefix, keep_vars)
_save_to_state_dict(destination, prefix, keep_vars)
T_destination = TypeVar('T_destination', bound=Dict[str, Any])
_register_load_state_dict_pre_hook(hook, with_module=False)
===========changed ref 0===========
# module: bitsandbytes.nn.modules
def maybe_rearrange_weight(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
weight = state_dict.get(f"{prefix}weight")
if weight is None:
# if the state dict has no weights for this layer (e.g., LoRA finetuning), do nothing
return
weight_format = state_dict.pop(f"{prefix}weight_format", "row")
+ if isinstance(weight_format, torch.Tensor):
+ weight_format = weight_format.item()
+
+ # For new weights format storage type, we explicitly check
+ # if weights_format is on the mapping
+ if isinstance(weight_format, int) and weight_format not in INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING:
+ raise ValueError(f"Expected supported weight format - got {weight_format}")
+ elif isinstance(weight_format, int) and weight_format in INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING:
+ weight_format = INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING[weight_format]
+
if weight_format != "row":
tile_indices = get_tile_inds(weight_format, weight.device)
state_dict[f"{prefix}weight"] = undo_layout(weight, tile_indices)
===========changed ref 1===========
# module: bitsandbytes.utils
+ LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING = {"row": 0, "col32": 1, "col_turing": 2, "col_ampere": 3}
+ INVERSE_LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING = {val: name for (name, val) in LINEAR_8BIT_WEIGHTS_FORMAT_MAPPING.items()}
-
|
bitsandbytes.nn.modules/Params4bit.__getstate__
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
1f2ca43ae5f3b453ff5fed73a17c661dc4fbbcb3
|
Merge pull request #1222 from EtienneDosSantos/main
|
<0>:<add> state = self.__dict__.copy()
<del> state = self.__dict__
|
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
def __getstate__(self):
<0> state = self.__dict__
<1> state["data"] = self.data
<2> state["requires_grad"] = self.requires_grad
<3> return state
<4>
|
===========unchanged ref 0===========
at: bitsandbytes.nn.modules.Params4bit.__setstate__
self.requires_grad = state["requires_grad"]
self.data = state["data"]
at: bitsandbytes.nn.modules.Params4bit._quantize
self.data = w_4bit
|
bitsandbytes.nn.modules/Int8Params.__new__
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
1f2ca43ae5f3b453ff5fed73a17c661dc4fbbcb3
|
Merge pull request #1222 from EtienneDosSantos/main
|
<0>:<del> cls.has_fp16_weights = has_fp16_weights
<1>:<del> cls.CB = None
<2>:<del> cls.SCB = None
<6>:<add> obj.CB = CB
<add> obj.SCB = SCB
<add> obj.has_fp16_weights = has_fp16_weights
<del> obj.CB, obj.SCB = cls.CB, cls.SCB
|
# module: bitsandbytes.nn.modules
class Int8Params(torch.nn.Parameter):
def __new__(
cls,
data=None,
requires_grad=True,
has_fp16_weights=False,
CB=None,
SCB=None,
):
<0> cls.has_fp16_weights = has_fp16_weights
<1> cls.CB = None
<2> cls.SCB = None
<3> if data is None:
<4> data = torch.empty(0)
<5> obj = torch.Tensor._make_subclass(cls, data, requires_grad)
<6> obj.CB, obj.SCB = cls.CB, cls.SCB
<7> return obj
<8>
|
===========unchanged ref 0===========
at: torch._C._VariableFunctions
empty(size: _size, *, names: Optional[Sequence[Union[str, ellipsis, None]]], memory_format: Optional[memory_format]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
empty(*size: _int, memory_format: Optional[memory_format]=None, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
empty(*size: _int, names: Optional[Sequence[Union[str, ellipsis, None]]], memory_format: Optional[memory_format]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
empty(size: Sequence[Union[_int, SymInt]], *, memory_format: Optional[memory_format]=None, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
===========changed ref 0===========
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
def __getstate__(self):
+ state = self.__dict__.copy()
- state = self.__dict__
state["data"] = self.data
state["requires_grad"] = self.requires_grad
return state
|
tests.test_linear4bit/test_deepcopy_param
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
1f2ca43ae5f3b453ff5fed73a17c661dc4fbbcb3
|
Merge pull request #1222 from EtienneDosSantos/main
|
<2>:<add> dict_keys_before = set(param.__dict__.keys())
<3>:<add> dict_keys_after = set(param.__dict__.keys())
<add> dict_keys_copy = set(copy_param.__dict__.keys())
<add>
|
# module: tests.test_linear4bit
def test_deepcopy_param():
<0> tensor = torch.tensor([1.0, 2.0, 3.0, 4.0])
<1> param = bnb.nn.Params4bit(data=tensor, requires_grad=False).cuda(0)
<2> copy_param = copy.deepcopy(param)
<3> assert param.quant_state is not copy_param.quant_state
<4> assert param.data.data_ptr() != copy_param.data.data_ptr()
<5>
|
===========unchanged ref 0===========
at: bitsandbytes.nn.modules
Params4bit(data: Tensor=..., requires_grad: builtins.bool=...)
at: bitsandbytes.nn.modules.Params4bit
cuda(device: Optional[Union[int, device, str]]=None, non_blocking: bool=False)
at: copy
deepcopy(x: _T, memo: Optional[Dict[int, Any]]=..., _nil: Any=...) -> _T
at: torch._C._VariableFunctions
tensor(data: Any, dtype: Optional[_dtype]=None, device: Device=None, requires_grad: _bool=False) -> Tensor
===========changed ref 0===========
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
def __getstate__(self):
+ state = self.__dict__.copy()
- state = self.__dict__
state["data"] = self.data
state["requires_grad"] = self.requires_grad
return state
===========changed ref 1===========
# module: tests.test_linear8bitlt
+ def test_linear8bit_copy_param(linear8bit):
+ shallow_copy = copy.copy(linear8bit)
+ assert linear8bit.weight is shallow_copy.weight
+ assert linear8bit.bias is shallow_copy.bias
+ assert linear8bit.weight.data.data_ptr() == shallow_copy.weight.data.data_ptr()
+
===========changed ref 2===========
# module: bitsandbytes.nn.modules
class Int8Params(torch.nn.Parameter):
+ def __deepcopy__(self, memo):
+ # adjust this if new arguments are added to the constructor
+ new_instance = type(self).__new__(
+ type(self),
+ data=copy.deepcopy(self.data, memo),
+ requires_grad=self.requires_grad,
+ has_fp16_weights=self.has_fp16_weights,
+ CB=copy.deepcopy(self.CB, memo),
+ SCB=copy.deepcopy(self.SCB, memo),
+ )
+ return new_instance
+
===========changed ref 3===========
# module: bitsandbytes.nn.modules
class Int8Params(torch.nn.Parameter):
def __new__(
cls,
data=None,
requires_grad=True,
has_fp16_weights=False,
CB=None,
SCB=None,
):
- cls.has_fp16_weights = has_fp16_weights
- cls.CB = None
- cls.SCB = None
if data is None:
data = torch.empty(0)
obj = torch.Tensor._make_subclass(cls, data, requires_grad)
+ obj.CB = CB
+ obj.SCB = SCB
+ obj.has_fp16_weights = has_fp16_weights
- obj.CB, obj.SCB = cls.CB, cls.SCB
return obj
===========changed ref 4===========
# module: tests.test_linear8bitlt
+ @pytest.fixture
+ def linear8bit():
+ linear = torch.nn.Linear(32, 96)
+ linear_custom = Linear8bitLt(
+ linear.in_features,
+ linear.out_features,
+ linear.bias is not None,
+ has_fp16_weights=False,
+ threshold=6.0,
+ )
+ linear_custom.weight = bnb.nn.Int8Params(
+ linear.weight.data.clone(),
+ requires_grad=False,
+ has_fp16_weights=False,
+ )
+ linear_custom.bias = linear.bias
+ linear_custom = linear_custom.cuda()
+ return linear_custom
+
===========changed ref 5===========
# module: tests.test_linear8bitlt
+ def test_linear8bit_serialization(linear8bit):
+ serialized = pickle.dumps(linear8bit)
+ deserialized = pickle.loads(serialized)
+ assert linear8bit.weight.data.data_ptr() != deserialized.weight.data.data_ptr()
+ assert torch.allclose(linear8bit.weight.data, deserialized.weight.data)
+ assert linear8bit.bias.data.data_ptr() != deserialized.bias.data.data_ptr()
+ assert torch.allclose(linear8bit.bias.data, deserialized.bias.data)
+ assert linear8bit.state == deserialized.state
+
+ # check for a bug where SCB and CB were not copied
+ assert (linear8bit.weight.SCB == deserialized.weight.SCB).all()
+ assert (linear8bit.weight.CB == deserialized.weight.CB).all()
+
===========changed ref 6===========
# module: tests.test_linear8bitlt
+ def test_linear8bit_deepcopy_param(linear8bit):
+ deep_copy = copy.deepcopy(linear8bit)
+ assert linear8bit.weight is not deep_copy.weight
+ assert linear8bit.bias is not deep_copy.bias
+ assert linear8bit.weight.data.data_ptr() != deep_copy.weight.data.data_ptr()
+ assert torch.allclose(linear8bit.weight.data, deep_copy.weight.data)
+ assert linear8bit.state == deep_copy.state
+
+ # check for a bug where SCB and CB were not copied
+ assert deep_copy.weight.SCB is not None
+ assert (linear8bit.weight.SCB == deep_copy.weight.SCB).all()
+ assert deep_copy.weight.CB is not None
+ assert (linear8bit.weight.CB == deep_copy.weight.CB).all()
+
|
tests.test_linear4bit/test_params4bit_real_serialization
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
1f2ca43ae5f3b453ff5fed73a17c661dc4fbbcb3
|
Merge pull request #1222 from EtienneDosSantos/main
|
<2>:<add> dict_keys_before = set(original_param.__dict__.keys())
<7>:<add> dict_keys_after = set(original_param.__dict__.keys())
<add> dict_keys_deserialized = set(deserialized_param.__dict__.keys())
|
# module: tests.test_linear4bit
def test_params4bit_real_serialization():
<0> original_tensor = torch.tensor([1.0, 2.0, 3.0, 4.0], dtype=torch.float32)
<1> original_param = bnb.nn.Params4bit(data=original_tensor, quant_type="fp4")
<2>
<3> original_param.cuda(0) # move to CUDA to trigger quantization
<4>
<5> serialized_param = pickle.dumps(original_param)
<6> deserialized_param = pickle.loads(serialized_param)
<7>
<8> assert torch.equal(original_param.data, deserialized_param.data)
<9> assert original_param.requires_grad == deserialized_param.requires_grad == False
<10> assert original_param.quant_type == deserialized_param.quant_type
<11> assert original_param.blocksize == deserialized_param.blocksize
<12> assert original_param.compress_statistics == deserialized_param.compress_statistics
<13> assert original_param.quant_state == deserialized_param.quant_state
<14>
|
===========unchanged ref 0===========
at: bitsandbytes.nn.modules
Params4bit(data: Tensor=..., requires_grad: builtins.bool=...)
at: bitsandbytes.nn.modules.Params4bit
cuda(device: Optional[Union[int, device, str]]=None, non_blocking: bool=False)
at: bitsandbytes.nn.modules.Params4bit.__setstate__
self.quant_state = state["quant_state"]
self.data = state["data"]
at: bitsandbytes.nn.modules.Params4bit._quantize
self.data = w_4bit
self.quant_state = quant_state
at: tests.test_linear4bit.test_deepcopy_param
param = bnb.nn.Params4bit(data=tensor, requires_grad=False).cuda(0)
dict_keys_before = set(param.__dict__.keys())
copy_param = copy.deepcopy(param)
dict_keys_after = set(param.__dict__.keys())
dict_keys_copy = set(copy_param.__dict__.keys())
at: torch._C
float32: dtype = ...
at: torch._C._VariableFunctions
tensor(data: Any, dtype: Optional[_dtype]=None, device: Device=None, requires_grad: _bool=False) -> Tensor
===========changed ref 0===========
# module: tests.test_linear4bit
def test_deepcopy_param():
tensor = torch.tensor([1.0, 2.0, 3.0, 4.0])
param = bnb.nn.Params4bit(data=tensor, requires_grad=False).cuda(0)
+ dict_keys_before = set(param.__dict__.keys())
copy_param = copy.deepcopy(param)
+ dict_keys_after = set(param.__dict__.keys())
+ dict_keys_copy = set(copy_param.__dict__.keys())
+
assert param.quant_state is not copy_param.quant_state
assert param.data.data_ptr() != copy_param.data.data_ptr()
===========changed ref 1===========
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
def __getstate__(self):
+ state = self.__dict__.copy()
- state = self.__dict__
state["data"] = self.data
state["requires_grad"] = self.requires_grad
return state
===========changed ref 2===========
# module: tests.test_linear8bitlt
+ def test_linear8bit_copy_param(linear8bit):
+ shallow_copy = copy.copy(linear8bit)
+ assert linear8bit.weight is shallow_copy.weight
+ assert linear8bit.bias is shallow_copy.bias
+ assert linear8bit.weight.data.data_ptr() == shallow_copy.weight.data.data_ptr()
+
===========changed ref 3===========
# module: bitsandbytes.nn.modules
class Int8Params(torch.nn.Parameter):
+ def __deepcopy__(self, memo):
+ # adjust this if new arguments are added to the constructor
+ new_instance = type(self).__new__(
+ type(self),
+ data=copy.deepcopy(self.data, memo),
+ requires_grad=self.requires_grad,
+ has_fp16_weights=self.has_fp16_weights,
+ CB=copy.deepcopy(self.CB, memo),
+ SCB=copy.deepcopy(self.SCB, memo),
+ )
+ return new_instance
+
===========changed ref 4===========
# module: bitsandbytes.nn.modules
class Int8Params(torch.nn.Parameter):
def __new__(
cls,
data=None,
requires_grad=True,
has_fp16_weights=False,
CB=None,
SCB=None,
):
- cls.has_fp16_weights = has_fp16_weights
- cls.CB = None
- cls.SCB = None
if data is None:
data = torch.empty(0)
obj = torch.Tensor._make_subclass(cls, data, requires_grad)
+ obj.CB = CB
+ obj.SCB = SCB
+ obj.has_fp16_weights = has_fp16_weights
- obj.CB, obj.SCB = cls.CB, cls.SCB
return obj
===========changed ref 5===========
# module: tests.test_linear8bitlt
+ @pytest.fixture
+ def linear8bit():
+ linear = torch.nn.Linear(32, 96)
+ linear_custom = Linear8bitLt(
+ linear.in_features,
+ linear.out_features,
+ linear.bias is not None,
+ has_fp16_weights=False,
+ threshold=6.0,
+ )
+ linear_custom.weight = bnb.nn.Int8Params(
+ linear.weight.data.clone(),
+ requires_grad=False,
+ has_fp16_weights=False,
+ )
+ linear_custom.bias = linear.bias
+ linear_custom = linear_custom.cuda()
+ return linear_custom
+
===========changed ref 6===========
# module: tests.test_linear8bitlt
+ def test_linear8bit_serialization(linear8bit):
+ serialized = pickle.dumps(linear8bit)
+ deserialized = pickle.loads(serialized)
+ assert linear8bit.weight.data.data_ptr() != deserialized.weight.data.data_ptr()
+ assert torch.allclose(linear8bit.weight.data, deserialized.weight.data)
+ assert linear8bit.bias.data.data_ptr() != deserialized.bias.data.data_ptr()
+ assert torch.allclose(linear8bit.bias.data, deserialized.bias.data)
+ assert linear8bit.state == deserialized.state
+
+ # check for a bug where SCB and CB were not copied
+ assert (linear8bit.weight.SCB == deserialized.weight.SCB).all()
+ assert (linear8bit.weight.CB == deserialized.weight.CB).all()
+
===========changed ref 7===========
# module: tests.test_linear8bitlt
+ def test_linear8bit_deepcopy_param(linear8bit):
+ deep_copy = copy.deepcopy(linear8bit)
+ assert linear8bit.weight is not deep_copy.weight
+ assert linear8bit.bias is not deep_copy.bias
+ assert linear8bit.weight.data.data_ptr() != deep_copy.weight.data.data_ptr()
+ assert torch.allclose(linear8bit.weight.data, deep_copy.weight.data)
+ assert linear8bit.state == deep_copy.state
+
+ # check for a bug where SCB and CB were not copied
+ assert deep_copy.weight.SCB is not None
+ assert (linear8bit.weight.SCB == deep_copy.weight.SCB).all()
+ assert deep_copy.weight.CB is not None
+ assert (linear8bit.weight.CB == deep_copy.weight.CB).all()
+
|
bitsandbytes.autograd._functions/MatMul4Bit.forward
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
9e75374104cec965d9a4a630a68ce4e2b77b066f
|
fix QLoRA mem bug: delete useless buffered activation (#1270)
|
<22>:<add> ctx.tensors = (None, B)
<del> ctx.tensors = (A, B)
|
# module: bitsandbytes.autograd._functions
class MatMul4Bit(torch.autograd.Function):
# forward is the same, but we added the fallback for pre-turing GPUs
# backward is mostly the same, but adds one extra clause (see "elif state.CxB is not None")
@staticmethod
def forward(ctx, A, B, out=None, bias=None, quant_state: Optional[F.QuantState] = None):
<0> # default of pytorch behavior if inputs are empty
<1> ctx.is_empty = False
<2> if prod(A.shape) == 0:
<3> ctx.is_empty = True
<4> ctx.A = A
<5> ctx.B = B
<6> ctx.bias = bias
<7> B_shape = quant_state.shape
<8> if A.shape[-1] == B_shape[0]:
<9> return torch.empty(A.shape[:-1] + B_shape[1:], dtype=A.dtype, device=A.device)
<10> else:
<11> return torch.empty(A.shape[:-1] + B_shape[:1], dtype=A.dtype, device=A.device)
<12>
<13> # 1. Dequantize
<14> # 2. MatmulnN
<15> output = torch.nn.functional.linear(A, F.dequantize_4bit(B, quant_state).to(A.dtype).t(), bias)
<16>
<17> # 3. Save state
<18> ctx.state = quant_state
<19> ctx.dtype_A, ctx.dtype_B, ctx.dtype_bias = A.dtype, B.dtype, None if bias is None else bias.dtype
<20>
<21> if any(ctx.needs_input_grad[:2]):
<22> ctx.tensors = (A, B)
<23> else:
<24> ctx.tensors = (None, None)
<25>
<26> return output
<27>
|
===========unchanged ref 0===========
at: bitsandbytes.autograd._functions
prod(iterable)
at: bitsandbytes.functional
QuantState(absmax, shape=None, code=None, blocksize=None, quant_type=None, dtype=None, offset=None, state2=None)
dequantize_4bit(A: Tensor, quant_state: Optional[QuantState]=None, absmax: Optional[torch.Tensor]=None, out: Optional[torch.Tensor]=None, blocksize: int=64, quant_type="fp4") -> Tensor
at: bitsandbytes.functional.QuantState.__init__
self.shape = shape
===========unchanged ref 1===========
at: torch._C._VariableFunctions
empty(size: _size, *, names: Optional[Sequence[Union[str, ellipsis, None]]], memory_format: Optional[memory_format]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
empty(*size: _int, memory_format: Optional[memory_format]=None, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
empty(*size: _int, names: Optional[Sequence[Union[str, ellipsis, None]]], memory_format: Optional[memory_format]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
empty(size: Sequence[Union[_int, SymInt]], *, memory_format: Optional[memory_format]=None, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
at: torch._C._nn
linear(input: Tensor, weight: Tensor, bias: Optional[Tensor]=None) -> Tensor
at: torch.autograd.function._SingleLevelFunction
forward(ctx: Any, *args: Any, **kwargs: Any) -> Any
vjp = backward
|
bitsandbytes.autograd._functions/MatMul4Bit.backward
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
9e75374104cec965d9a4a630a68ce4e2b77b066f
|
fix QLoRA mem bug: delete useless buffered activation (#1270)
|
<5>:<add> _, B = ctx.tensors
<del> A, B = ctx.tensors
|
# module: bitsandbytes.autograd._functions
class MatMul4Bit(torch.autograd.Function):
@staticmethod
def backward(ctx, grad_output):
<0> if ctx.is_empty:
<1> bias_grad = None if ctx.bias is None else torch.zeros_like(ctx.bias)
<2> return torch.zeros_like(ctx.A), torch.zeros_like(ctx.B), None, bias_grad, None
<3>
<4> req_gradA, _, _, req_gradBias, _ = ctx.needs_input_grad
<5> A, B = ctx.tensors
<6>
<7> grad_A, grad_B, grad_bias = None, None, None
<8>
<9> if req_gradBias:
<10> # compute grad_bias first before changing grad_output dtype
<11> grad_bias = grad_output.sum(0, dtype=ctx.dtype_bias)
<12>
<13> # not supported by PyTorch. TODO: create work-around
<14> # if req_gradB: grad_B = torch.matmul(grad_output.t(), A)
<15> if req_gradA:
<16> grad_A = torch.matmul(grad_output, F.dequantize_4bit(B, ctx.state).to(grad_output.dtype).t())
<17>
<18> return grad_A, grad_B, None, grad_bias, None
<19>
|
===========unchanged ref 0===========
at: bitsandbytes.functional
dequantize_4bit(A: Tensor, quant_state: Optional[QuantState]=None, absmax: Optional[torch.Tensor]=None, out: Optional[torch.Tensor]=None, blocksize: int=64, quant_type="fp4") -> Tensor
at: torch._C._VariableFunctions
matmul(input: Tensor, other: Tensor, *, out: Optional[Tensor]=None) -> Tensor
zeros_like(input: Tensor, *, memory_format: Optional[memory_format]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
at: torch.autograd.function._SingleLevelFunction
backward(ctx: Any, *grad_outputs: Any) -> Any
===========changed ref 0===========
# module: bitsandbytes.autograd._functions
class MatMul4Bit(torch.autograd.Function):
# forward is the same, but we added the fallback for pre-turing GPUs
# backward is mostly the same, but adds one extra clause (see "elif state.CxB is not None")
@staticmethod
def forward(ctx, A, B, out=None, bias=None, quant_state: Optional[F.QuantState] = None):
# default of pytorch behavior if inputs are empty
ctx.is_empty = False
if prod(A.shape) == 0:
ctx.is_empty = True
ctx.A = A
ctx.B = B
ctx.bias = bias
B_shape = quant_state.shape
if A.shape[-1] == B_shape[0]:
return torch.empty(A.shape[:-1] + B_shape[1:], dtype=A.dtype, device=A.device)
else:
return torch.empty(A.shape[:-1] + B_shape[:1], dtype=A.dtype, device=A.device)
# 1. Dequantize
# 2. MatmulnN
output = torch.nn.functional.linear(A, F.dequantize_4bit(B, quant_state).to(A.dtype).t(), bias)
# 3. Save state
ctx.state = quant_state
ctx.dtype_A, ctx.dtype_B, ctx.dtype_bias = A.dtype, B.dtype, None if bias is None else bias.dtype
if any(ctx.needs_input_grad[:2]):
+ ctx.tensors = (None, B)
- ctx.tensors = (A, B)
else:
ctx.tensors = (None, None)
return output
|
bitsandbytes.optim.optimizer/Optimizer2State.init_state
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
5212a0f2a585abba1cc2a65f82f7c4fc939c453f
|
Edenzzzz's fix for min_8bit_size functionality in Optimizer base classes (#1286)
|
<15>:<add> if dtype == torch.float32:
<del> if dtype == torch.float32 or (dtype == torch.uint8 and p.numel() < 4096):
|
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
<0> config = self.get_config(gindex, pindex, group)
<1>
<2> if config["optim_bits"] == 32:
<3> dtype = torch.float32
<4> elif config["optim_bits"] == 8:
<5> dtype = torch.uint8
<6> else:
<7> raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}')
<8>
<9> if p.numel() < config["min_8bit_size"]:
<10> dtype = torch.float32
<11>
<12> state = self.state[p]
<13> state["step"] = 0
<14>
<15> if dtype == torch.float32 or (dtype == torch.uint8 and p.numel() < 4096):
<16> state["state1"] = self.get_state_buffer(p, dtype=torch.float32)
<17> state["state2"] = self.get_state_buffer(p, dtype=torch.float32)
<18> elif dtype == torch.uint8:
<19> if state["step"] == 0:
<20> if "dynamic" not in self.name2qmap:
<21> self.fill_qmap()
<22> self.name2qmap["dynamic"] = self.name2qmap["dynamic"].to(p.device)
<23> self.name2qmap["udynamic"] = self.name2qmap["udynamic"].to(p.device)
<24>
<25> state["state1"] = self.get_state_buffer(p, dtype=torch.uint8)
<26> state["qmap1"] = self.name2qmap["dynamic"]
<27>
<28> state["state2"] = self.get_state_buffer(p, dtype=torch.uint8)
<29> state["qmap2"] = self.name2qmap["udynamic"]
<30>
<31> if config["block_wise"]:
<32> n = p.numel()
<33> </s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
# offset: 1
blocks += 1 if n % 2048 > 0 else 0
state["absmax1"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
state["absmax2"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
else:
state["max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["new_max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["max2"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["new_max2"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
if config["percentile_clipping"] < 100:
state["gnorm_vec"] = torch.zeros((100,), device=p.device)
if config["max_unorm"] > 0.0:
state["unorm_vec"] = torch.zeros((1,), device=p.device)
===========unchanged ref 0===========
at: bitsandbytes.optim.optimizer.Optimizer8bit
fill_qmap()
get_config(gindex, pindex, group)
init_state(self, group, p, gindex, pindex)
get_state_buffer(p, dtype=torch.float32)
at: bitsandbytes.optim.optimizer.Optimizer8bit.__init__
self.name2qmap = {}
at: torch._C
float32: dtype = ...
uint8: dtype = ...
at: torch._C._VariableFunctions
zeros(*size: _int, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: _size, *, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(*size: _int, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: Sequence[Union[_int, SymInt]], *, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
at: torch.autograd.grad_mode
no_grad()
===========unchanged ref 1===========
at: torch.optim.optimizer.Optimizer.__init__
self.state: DefaultDict[torch.Tensor, Any] = defaultdict(dict)
|
bitsandbytes.optim.optimizer/Optimizer1State.init_state
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
5212a0f2a585abba1cc2a65f82f7c4fc939c453f
|
Edenzzzz's fix for min_8bit_size functionality in Optimizer base classes (#1286)
|
<15>:<add> if dtype == torch.float32:
<del> if dtype == torch.float32 or (dtype == torch.uint8 and p.numel() < 4096):
|
# module: bitsandbytes.optim.optimizer
class Optimizer1State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
<0> config = self.get_config(gindex, pindex, group)
<1>
<2> if config["optim_bits"] == 32:
<3> dtype = torch.float32
<4> elif config["optim_bits"] == 8:
<5> dtype = torch.uint8
<6> else:
<7> raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}')
<8>
<9> if p.numel() < config["min_8bit_size"]:
<10> dtype = torch.float32
<11>
<12> state = self.state[p]
<13> state["step"] = 0
<14>
<15> if dtype == torch.float32 or (dtype == torch.uint8 and p.numel() < 4096):
<16> state["state1"] = self.get_state_buffer(p, dtype=torch.float32)
<17> elif dtype == torch.uint8:
<18> if state["step"] == 0:
<19> if "dynamic" not in self.name2qmap:
<20> self.fill_qmap()
<21> self.name2qmap["dynamic"] = self.name2qmap["dynamic"].to(p.device)
<22>
<23> state["state1"] = self.get_state_buffer(p, dtype=torch.uint8)
<24> state["qmap1"] = self.name2qmap["dynamic"]
<25>
<26> if config["block_wise"]:
<27> n = p.numel()
<28> blocks = n // 2048
<29> blocks += 1 if n % 2048 > 0 else 0
<30>
<31> state["absmax1"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
<32> else:
<33> state["max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
<34> state["new_max1"] = torch.zeros((1,), dtype=</s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer1State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
# offset: 1
if config["percentile_clipping"] < 100:
state["gnorm_vec"] = torch.zeros((100,), device=p.device)
if config["max_unorm"] > 0.0:
state["unorm_vec"] = torch.zeros((1,), device=p.device)
===========unchanged ref 0===========
at: bitsandbytes.optim.optimizer.Optimizer8bit
fill_qmap()
get_config(gindex, pindex, group)
init_state(self, group, p, gindex, pindex)
get_state_buffer(p, dtype=torch.float32)
at: bitsandbytes.optim.optimizer.Optimizer8bit.__init__
self.name2qmap = {}
at: torch._C
float32: dtype = ...
uint8: dtype = ...
at: torch._C._VariableFunctions
zeros(*size: _int, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: _size, *, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(*size: _int, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: Sequence[Union[_int, SymInt]], *, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
at: torch.autograd.grad_mode
no_grad()
===========unchanged ref 1===========
at: torch.optim.optimizer.Optimizer.__init__
self.state: DefaultDict[torch.Tensor, Any] = defaultdict(dict)
===========changed ref 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
config = self.get_config(gindex, pindex, group)
if config["optim_bits"] == 32:
dtype = torch.float32
elif config["optim_bits"] == 8:
dtype = torch.uint8
else:
raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}')
if p.numel() < config["min_8bit_size"]:
dtype = torch.float32
state = self.state[p]
state["step"] = 0
+ if dtype == torch.float32:
- if dtype == torch.float32 or (dtype == torch.uint8 and p.numel() < 4096):
state["state1"] = self.get_state_buffer(p, dtype=torch.float32)
state["state2"] = self.get_state_buffer(p, dtype=torch.float32)
elif dtype == torch.uint8:
if state["step"] == 0:
if "dynamic" not in self.name2qmap:
self.fill_qmap()
self.name2qmap["dynamic"] = self.name2qmap["dynamic"].to(p.device)
self.name2qmap["udynamic"] = self.name2qmap["udynamic"].to(p.device)
state["state1"] = self.get_state_buffer(p, dtype=torch.uint8)
state["qmap1"] = self.name2qmap["dynamic"]
state["state2"] = self.get_state_buffer(p, dtype=torch.uint8)
state["qmap2"] = self.name2qmap["udynamic"]
if config["block_wise"]:
n = p.numel()
blocks = n // 2048
blocks += 1 if n % 2048 > 0 else 0
state</s>
===========changed ref 1===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
# offset: 1
<s> = p.numel()
blocks = n // 2048
blocks += 1 if n % 2048 > 0 else 0
state["absmax1"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
state["absmax2"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
else:
state["max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["new_max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["max2"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["new_max2"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
if config["percentile_clipping"] < 100:
state["gnorm_vec"] = torch.zeros((100,), device=p.device)
if config["max_unorm"] > 0.0:
state["unorm_vec"] = torch.zeros((1,), device=p.device)
|
bitsandbytes.optim.optimizer/Optimizer2State.update_step
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
a3f55cea3ab29218067809770bc8bf2380ec46cd
|
Fixed optim update error with non-contiguous grads/params (#1187)
|
<0>:<add> # avoid update error from non-contiguous memory layout
<add> p.data = p.data.contiguous()
<add> p.grad = p.grad.contiguous()
<add>
|
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def update_step(self, group, p, gindex, pindex):
<0> state = self.state[p]
<1> grad = p.grad
<2>
<3> config = self.get_config(gindex, pindex, group)
<4>
<5> state["step"] += 1
<6> step = state["step"]
<7>
<8> if config["percentile_clipping"] < 100:
<9> current_gnorm, clip_value, gnorm_scale = F.percentile_clipping(
<10> grad,
<11> state["gnorm_vec"],
<12> step,
<13> config["percentile_clipping"],
<14> )
<15> else:
<16> gnorm_scale = 1.0
<17>
<18> if state["state1"].dtype == torch.float:
<19> F.optimizer_update_32bit(
<20> self.optimizer_name,
<21> grad,
<22> p,
<23> state["state1"],
<24> config["betas"][0],
<25> config["eps"],
<26> step,
<27> config["lr"],
<28> state["state2"],
<29> config["betas"][1],
<30> config["weight_decay"],
<31> gnorm_scale,
<32> state["unorm_vec"] if config["max_unorm"] > 0.0 else None,
<33> max_unorm=config["max_unorm"],
<34> skip_zeros=config["skip_zeros"],
<35> )
<36>
<37> elif state["state1"].dtype == torch.uint8 and not config["block_wise"]:
<38> F.optimizer_update_8bit(
<39> self.optimizer_name,
<40> grad,
<41> p,
<42> state["state1"],
<43> state["state2"],
<44> config["betas"][0],
<45> config["betas"][1],
<46> config["eps"],
<47> step,
<48> config["lr"],
<49> </s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def update_step(self, group, p, gindex, pindex):
# offset: 1
state["qmap2"],
state["max1"],
state["max2"],
state["new_max1"],
state["new_max2"],
config["weight_decay"],
gnorm_scale=gnorm_scale,
unorm_vec=state["unorm_vec"] if config["max_unorm"] > 0.0 else None,
max_unorm=config["max_unorm"],
)
# swap maxes
state["max1"], state["new_max1"] = state["new_max1"], state["max1"]
state["max2"], state["new_max2"] = state["new_max2"], state["max2"]
elif state["state1"].dtype == torch.uint8 and config["block_wise"]:
F.optimizer_update_8bit_blockwise(
self.optimizer_name,
grad,
p,
state["state1"],
state["state2"],
config["betas"][0],
config["betas"][1],
config["eps"],
step,
config["lr"],
state["qmap1"],
state["qmap2"],
state["absmax1"],
state["absmax2"],
config["weight_decay"],
gnorm_scale=gnorm_scale,
skip_zeros=config["skip_zeros"],
)
===========unchanged ref 0===========
at: bitsandbytes.functional
optimizer_update_32bit(optimizer_name: str, g: Tensor, p: Tensor, state1: Tensor, beta1: float, eps: float, step: int, lr: float, state2: Optional[torch.Tensor]=None, beta2: float=0.0, weight_decay: float=0.0, gnorm_scale: float=1.0, unorm_vec: Optional[torch.Tensor]=None, max_unorm: float=0.0, skip_zeros=False) -> None
optimizer_update_8bit(optimizer_name: str, g: Tensor, p: Tensor, state1: Tensor, state2: Optional[torch.Tensor], beta1: float, beta2: float, eps: float, step: int, lr: float, qmap1: Tensor, qmap2: Optional[torch.Tensor], max1: Tensor, max2: Optional[torch.Tensor], new_max1: Tensor, new_max2: Optional[torch.Tensor], weight_decay: float=0.0, gnorm_scale: float=1.0, unorm_vec: Optional[torch.Tensor]=None, max_unorm: float=0.0) -> None
optimizer_update_8bit_blockwise(optimizer_name: str, g: Tensor, p: Tensor, state1: Tensor, state2: Optional[torch.Tensor], beta1: float, beta2: float, eps: float, step: int, lr: float, qmap1: Tensor, qmap2: Optional[torch.Tensor], absmax1: Tensor, absmax2: Optional[torch.Tensor], weight_decay: float=0.0, gnorm_scale: float=1.0, skip_zeros=False) -> None
percentile_clipping(grad: Tensor, gnorm_vec: Tensor, step: int, percentile: int=5)
at: bitsandbytes.optim.optimizer.Optimizer2State.__init__
self.optimizer_name = optimizer_name
at: bitsandbytes.optim.optimizer.Optimizer8bit
get_config(gindex, pindex, group)
===========unchanged ref 1===========
update_step(self, group, p, gindex, pindex)
at: torch._C
float: dtype = ...
uint8: dtype = ...
at: torch.autograd.grad_mode
no_grad()
at: torch.optim.optimizer.Optimizer.__init__
self.state: DefaultDict[torch.Tensor, Any] = defaultdict(dict)
|
bitsandbytes.optim.optimizer/Optimizer1State.update_step
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
a3f55cea3ab29218067809770bc8bf2380ec46cd
|
Fixed optim update error with non-contiguous grads/params (#1187)
|
<0>:<add> # avoid update error from non-contiguous memory layout
<add> p.data = p.data.contiguous()
<add> p.grad = p.grad.contiguous()
<add>
|
# module: bitsandbytes.optim.optimizer
class Optimizer1State(Optimizer8bit):
@torch.no_grad()
def update_step(self, group, p, gindex, pindex):
<0> state = self.state[p]
<1> grad = p.grad
<2>
<3> config = self.get_config(gindex, pindex, group)
<4>
<5> state["step"] += 1
<6> step = state["step"]
<7>
<8> if config["percentile_clipping"] < 100:
<9> current_gnorm, clip_value, gnorm_scale = F.percentile_clipping(
<10> grad,
<11> state["gnorm_vec"],
<12> step,
<13> config["percentile_clipping"],
<14> )
<15> else:
<16> gnorm_scale = 1.0
<17>
<18> if state["state1"].dtype == torch.float:
<19> F.optimizer_update_32bit(
<20> self.optimizer_name,
<21> grad,
<22> p,
<23> state["state1"],
<24> config["betas"][0],
<25> config["eps"],
<26> step,
<27> config["lr"],
<28> None,
<29> config["betas"][1],
<30> config["weight_decay"],
<31> gnorm_scale,
<32> state["unorm_vec"] if config["max_unorm"] > 0.0 else None,
<33> max_unorm=config["max_unorm"],
<34> skip_zeros=config["skip_zeros"],
<35> )
<36>
<37> elif state["state1"].dtype == torch.uint8 and not config["block_wise"]:
<38> F.optimizer_update_8bit(
<39> self.optimizer_name,
<40> grad,
<41> p,
<42> state["state1"],
<43> None,
<44> config["betas"][0],
<45> config["betas"][1],
<46> config["eps"],
<47> step,
<48> config["lr"],
<49> state["qmap1"],
</s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer1State(Optimizer8bit):
@torch.no_grad()
def update_step(self, group, p, gindex, pindex):
# offset: 1
state["max1"],
None,
state["new_max1"],
None,
config["weight_decay"],
gnorm_scale,
state["unorm_vec"] if config["max_unorm"] > 0.0 else None,
max_unorm=config["max_unorm"],
)
state["max1"], state["new_max1"] = state["new_max1"], state["max1"]
elif state["state1"].dtype == torch.uint8 and config["block_wise"]:
F.optimizer_update_8bit_blockwise(
self.optimizer_name,
grad,
p,
state["state1"],
None,
config["betas"][0],
config["betas"][1],
config["eps"],
step,
config["lr"],
state["qmap1"],
None,
state["absmax1"],
None,
config["weight_decay"],
gnorm_scale=gnorm_scale,
skip_zeros=config["skip_zeros"],
)
===========unchanged ref 0===========
at: bitsandbytes.functional
optimizer_update_32bit(optimizer_name: str, g: Tensor, p: Tensor, state1: Tensor, beta1: float, eps: float, step: int, lr: float, state2: Optional[torch.Tensor]=None, beta2: float=0.0, weight_decay: float=0.0, gnorm_scale: float=1.0, unorm_vec: Optional[torch.Tensor]=None, max_unorm: float=0.0, skip_zeros=False) -> None
optimizer_update_8bit(optimizer_name: str, g: Tensor, p: Tensor, state1: Tensor, state2: Optional[torch.Tensor], beta1: float, beta2: float, eps: float, step: int, lr: float, qmap1: Tensor, qmap2: Optional[torch.Tensor], max1: Tensor, max2: Optional[torch.Tensor], new_max1: Tensor, new_max2: Optional[torch.Tensor], weight_decay: float=0.0, gnorm_scale: float=1.0, unorm_vec: Optional[torch.Tensor]=None, max_unorm: float=0.0) -> None
optimizer_update_8bit_blockwise(optimizer_name: str, g: Tensor, p: Tensor, state1: Tensor, state2: Optional[torch.Tensor], beta1: float, beta2: float, eps: float, step: int, lr: float, qmap1: Tensor, qmap2: Optional[torch.Tensor], absmax1: Tensor, absmax2: Optional[torch.Tensor], weight_decay: float=0.0, gnorm_scale: float=1.0, skip_zeros=False) -> None
percentile_clipping(grad: Tensor, gnorm_vec: Tensor, step: int, percentile: int=5)
at: bitsandbytes.optim.optimizer.Optimizer1State.__init__
self.optimizer_name = optimizer_name
===========unchanged ref 1===========
at: bitsandbytes.optim.optimizer.Optimizer1State.init_state
config = self.get_config(gindex, pindex, group)
state["gnorm_vec"] = torch.zeros((100,), device=p.device)
state["max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["absmax1"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
state["state1"] = self.get_state_buffer(p, dtype=torch.float32)
state["step"] = 0
state["new_max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["qmap1"] = self.name2qmap["dynamic"]
state["state1"] = self.get_state_buffer(p, dtype=torch.uint8)
at: bitsandbytes.optim.optimizer.Optimizer8bit
get_config(gindex, pindex, group)
update_step(self, group, p, gindex, pindex)
at: torch._C
float: dtype = ...
uint8: dtype = ...
===========unchanged ref 2===========
at: torch._C._VariableFunctions
zeros(*size: _int, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: _size, *, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(*size: _int, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: Sequence[Union[_int, SymInt]], *, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
at: torch.autograd.grad_mode
no_grad()
at: torch.optim.optimizer.Optimizer.__init__
self.state: DefaultDict[torch.Tensor, Any] = defaultdict(dict)
|
bitsandbytes.nn.modules/Params4bit.from_prequantized
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
7fed393aa8380f2d7f7c760bbd6a2f68b5caa9ea
|
Fix restoration of quant_storage for CPU offloading (#1279)
|
<7>:<add>
<add> self.quant_storage = data.dtype
<add>
|
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
@classmethod
def from_prequantized(
cls,
data: torch.Tensor,
quantized_stats: Dict[str, Any],
requires_grad: bool = False,
device="cuda",
**kwargs,
) -> "Params4bit":
<0> self = torch.Tensor._make_subclass(cls, data.to(device))
<1> self.requires_grad = requires_grad
<2> self.quant_state = QuantState.from_dict(qs_dict=quantized_stats, device=device)
<3> self.blocksize = self.quant_state.blocksize
<4> self.compress_statistics = self.quant_state.nested
<5> self.quant_type = self.quant_state.quant_type
<6> self.bnb_quantized = True
<7> return self
<8>
|
===========unchanged ref 0===========
at: bitsandbytes.functional
QuantState(absmax, shape=None, code=None, blocksize=None, quant_type=None, dtype=None, offset=None, state2=None)
at: bitsandbytes.functional.QuantState
valid_quant_types = ("fp4", "nf4")
valid_qs_type_keys = [f"bitsandbytes__{x}" for x in valid_quant_types]
valid_qs_keys = [
"absmax",
"quant_map",
"nested_absmax",
"nested_quant_map",
"quant_state",
"quant_type",
"blocksize",
"dtype",
"shape",
"nested_blocksize",
"nested_dtype",
"nested_offset",
]
from_dict(qs_dict: Dict[str, Any], device: torch.device) -> "QuantState"
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
bitsandbytes.nn.modules/Params4bit._quantize
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
7fed393aa8380f2d7f7c760bbd6a2f68b5caa9ea
|
Fix restoration of quant_storage for CPU offloading (#1279)
|
<0>:<add> w = self.data.contiguous().to(device)
<del> w = self.data.contiguous().cuda(device)
|
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
def _quantize(self, device):
<0> w = self.data.contiguous().cuda(device)
<1> w_4bit, quant_state = bnb.functional.quantize_4bit(
<2> w,
<3> blocksize=self.blocksize,
<4> compress_statistics=self.compress_statistics,
<5> quant_type=self.quant_type,
<6> quant_storage=self.quant_storage,
<7> )
<8> self.data = w_4bit
<9> self.quant_state = quant_state
<10> if self.module is not None:
<11> self.module.quant_state = quant_state
<12> self.bnb_quantized = True
<13> return self
<14>
|
===========unchanged ref 0===========
at: bitsandbytes.functional
quantize_4bit(A: Tensor, absmax: Optional[torch.Tensor]=None, out: Optional[torch.Tensor]=None, blocksize=64, compress_statistics=False, quant_type="fp4", quant_storage=torch.uint8) -> Tuple[Tensor, QuantState]
at: bitsandbytes.nn.modules.Params4bit.__setstate__
self.blocksize = state["blocksize"]
self.compress_statistics = state["compress_statistics"]
self.quant_type = state["quant_type"]
self.quant_state = state["quant_state"]
self.data = state["data"]
self.quant_storage = state["quant_storage"]
self.module = state["module"]
at: bitsandbytes.nn.modules.Params4bit.from_prequantized
self = torch.Tensor._make_subclass(cls, data.to(device))
===========changed ref 0===========
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
@classmethod
def from_prequantized(
cls,
data: torch.Tensor,
quantized_stats: Dict[str, Any],
requires_grad: bool = False,
device="cuda",
**kwargs,
) -> "Params4bit":
self = torch.Tensor._make_subclass(cls, data.to(device))
self.requires_grad = requires_grad
self.quant_state = QuantState.from_dict(qs_dict=quantized_stats, device=device)
self.blocksize = self.quant_state.blocksize
self.compress_statistics = self.quant_state.nested
self.quant_type = self.quant_state.quant_type
self.bnb_quantized = True
+
+ self.quant_storage = data.dtype
+
return self
|
bitsandbytes.nn.modules/Params4bit.to
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
7fed393aa8380f2d7f7c760bbd6a2f68b5caa9ea
|
Fix restoration of quant_storage for CPU offloading (#1279)
|
<15>:<add> quant_storage=self.quant_storage,
|
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
def to(self, *args, **kwargs):
<0> device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
<1>
<2> if device is not None and device.type == "cuda" and not self.bnb_quantized:
<3> return self._quantize(device)
<4> else:
<5> if self.quant_state is not None:
<6> self.quant_state.to(device)
<7>
<8> new_param = Params4bit(
<9> super().to(device=device, dtype=dtype, non_blocking=non_blocking),
<10> requires_grad=self.requires_grad,
<11> quant_state=self.quant_state,
<12> blocksize=self.blocksize,
<13> compress_statistics=self.compress_statistics,
<14> quant_type=self.quant_type,
<15> )
<16>
<17> return new_param
<18>
|
===========unchanged ref 0===========
at: bitsandbytes.functional.QuantState
to(device)
at: bitsandbytes.nn.modules
T = TypeVar("T", bound="torch.nn.Module")
Params4bit(data: Tensor=..., requires_grad: builtins.bool=...)
at: bitsandbytes.nn.modules.Params4bit
_quantize(device)
_quantize(self, device)
at: bitsandbytes.nn.modules.Params4bit.__setstate__
self.requires_grad = state["requires_grad"]
self.blocksize = state["blocksize"]
self.compress_statistics = state["compress_statistics"]
self.quant_type = state["quant_type"]
self.quant_state = state["quant_state"]
self.bnb_quantized = state["bnb_quantized"]
at: bitsandbytes.nn.modules.Params4bit._quantize
self.quant_state = quant_state
w_4bit, quant_state = bnb.functional.quantize_4bit(
w,
blocksize=self.blocksize,
compress_statistics=self.compress_statistics,
quant_type=self.quant_type,
quant_storage=self.quant_storage,
)
self.bnb_quantized = True
===========changed ref 0===========
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
def _quantize(self, device):
+ w = self.data.contiguous().to(device)
- w = self.data.contiguous().cuda(device)
w_4bit, quant_state = bnb.functional.quantize_4bit(
w,
blocksize=self.blocksize,
compress_statistics=self.compress_statistics,
quant_type=self.quant_type,
quant_storage=self.quant_storage,
)
self.data = w_4bit
self.quant_state = quant_state
if self.module is not None:
self.module.quant_state = quant_state
self.bnb_quantized = True
return self
===========changed ref 1===========
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
@classmethod
def from_prequantized(
cls,
data: torch.Tensor,
quantized_stats: Dict[str, Any],
requires_grad: bool = False,
device="cuda",
**kwargs,
) -> "Params4bit":
self = torch.Tensor._make_subclass(cls, data.to(device))
self.requires_grad = requires_grad
self.quant_state = QuantState.from_dict(qs_dict=quantized_stats, device=device)
self.blocksize = self.quant_state.blocksize
self.compress_statistics = self.quant_state.nested
self.quant_type = self.quant_state.quant_type
self.bnb_quantized = True
+
+ self.quant_storage = data.dtype
+
return self
|
bitsandbytes.nn.modules/Linear4bit.forward
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
7fed393aa8380f2d7f7c760bbd6a2f68b5caa9ea
|
Fix restoration of quant_storage for CPU offloading (#1279)
|
<10>:<add> self.weight = Params4bit(self.weight, quant_storage=self.quant_storage, bnb_quantized=True)
<del> self.weight = Params4bit(self.weight, quant_storage=self.quant_storage)
|
# module: bitsandbytes.nn.modules
class Linear4bit(nn.Linear):
def forward(self, x: torch.Tensor):
<0> # weights are cast automatically as Int8Params, but the bias has to be cast manually
<1> if self.bias is not None and self.bias.dtype != x.dtype:
<2> self.bias.data = self.bias.data.to(x.dtype)
<3>
<4> if getattr(self.weight, "quant_state", None) is None:
<5> if getattr(self, "quant_state", None) is not None:
<6> # the quant state got lost when the parameter got converted. This happens for example for fsdp
<7> # since we registered the module, we can recover the state here
<8> assert self.weight.shape[1] == 1
<9> if not isinstance(self.weight, Params4bit):
<10> self.weight = Params4bit(self.weight, quant_storage=self.quant_storage)
<11> self.weight.quant_state = self.quant_state
<12> else:
<13> print(
<14> "FP4 quantization state not initialized. Please call .cuda() or .to(device) on the LinearFP4 layer first.",
<15> )
<16> if not self.compute_type_is_set:
<17> self.set_compute_type(x)
<18> self.compute_type_is_set = True
<19>
<20> inp_dtype = x.dtype
<21> if self.compute_dtype is not None:
<22> x = x.to(self.compute_dtype)
<23>
<24> bias = None if self.bias is None else self.bias.to(self.compute_dtype)
<25> out = bnb.matmul_4bit(x, self.weight.t(), bias=bias, quant_state=self.weight.quant_state)
<26>
<27> out = out.to(inp_dtype)
<28>
<29> return out
<30>
|
===========unchanged ref 0===========
at: bitsandbytes.autograd._functions
matmul_4bit(A: torch.Tensor, B: torch.Tensor, quant_state: F.QuantState, out: Optional[torch.Tensor]=None, bias=None)
at: bitsandbytes.functional.QuantState
as_dict(packed=False)
at: bitsandbytes.nn.modules
Params4bit(data: Tensor=..., requires_grad: builtins.bool=...)
at: bitsandbytes.nn.modules.Linear4bit.__init__
self.weight = Params4bit(
self.weight.data,
requires_grad=False,
compress_statistics=compress_statistics,
quant_type=quant_type,
quant_storage=quant_storage,
module=self,
)
at: bitsandbytes.nn.modules.Params4bit.__setstate__
self.quant_state = state["quant_state"]
at: bitsandbytes.nn.modules.Params4bit._quantize
self.quant_state = quant_state
w_4bit, quant_state = bnb.functional.quantize_4bit(
w,
blocksize=self.blocksize,
compress_statistics=self.compress_statistics,
quant_type=self.quant_type,
quant_storage=self.quant_storage,
)
at: torch._tensor.Tensor.__setstate__
self.data = state[0]
at: torch.nn.modules.linear.Linear
__constants__ = ['in_features', 'out_features']
in_features: int
out_features: int
weight: Tensor
forward(self, input: Tensor) -> Tensor
at: torch.nn.modules.linear.Linear.__init__
self.bias = Parameter(torch.empty(out_features, **factory_kwargs))
===========changed ref 0===========
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
@classmethod
def from_prequantized(
cls,
data: torch.Tensor,
quantized_stats: Dict[str, Any],
requires_grad: bool = False,
device="cuda",
**kwargs,
) -> "Params4bit":
self = torch.Tensor._make_subclass(cls, data.to(device))
self.requires_grad = requires_grad
self.quant_state = QuantState.from_dict(qs_dict=quantized_stats, device=device)
self.blocksize = self.quant_state.blocksize
self.compress_statistics = self.quant_state.nested
self.quant_type = self.quant_state.quant_type
self.bnb_quantized = True
+
+ self.quant_storage = data.dtype
+
return self
===========changed ref 1===========
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
def _quantize(self, device):
+ w = self.data.contiguous().to(device)
- w = self.data.contiguous().cuda(device)
w_4bit, quant_state = bnb.functional.quantize_4bit(
w,
blocksize=self.blocksize,
compress_statistics=self.compress_statistics,
quant_type=self.quant_type,
quant_storage=self.quant_storage,
)
self.data = w_4bit
self.quant_state = quant_state
if self.module is not None:
self.module.quant_state = quant_state
self.bnb_quantized = True
return self
===========changed ref 2===========
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
def to(self, *args, **kwargs):
device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
if device is not None and device.type == "cuda" and not self.bnb_quantized:
return self._quantize(device)
else:
if self.quant_state is not None:
self.quant_state.to(device)
new_param = Params4bit(
super().to(device=device, dtype=dtype, non_blocking=non_blocking),
requires_grad=self.requires_grad,
quant_state=self.quant_state,
blocksize=self.blocksize,
compress_statistics=self.compress_statistics,
quant_type=self.quant_type,
+ quant_storage=self.quant_storage,
)
return new_param
|
bitsandbytes.nn.modules/Params4bit.from_prequantized
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
a96d2f055c147b81565bad6cb4763bc4a19e8cc2
|
Merge branch 'main' into fsdp-load-prequantized
|
<9>:<add> self.module = module
<add>
<add> if self.module is not None:
<add> self.module.quant_state = self.quant_state
|
# module: bitsandbytes.nn.modules
class Params4bit(torch.nn.Parameter):
@classmethod
def from_prequantized(
cls,
data: torch.Tensor,
quantized_stats: Dict[str, Any],
requires_grad: bool = False,
device="cuda",
+ module: Optional["Linear4bit"] = None,
**kwargs,
) -> "Params4bit":
<0> self = torch.Tensor._make_subclass(cls, data.to(device))
<1> self.requires_grad = requires_grad
<2> self.quant_state = QuantState.from_dict(qs_dict=quantized_stats, device=device)
<3> self.blocksize = self.quant_state.blocksize
<4> self.compress_statistics = self.quant_state.nested
<5> self.quant_type = self.quant_state.quant_type
<6> self.bnb_quantized = True
<7>
<8> self.quant_storage = data.dtype
<9>
<10> return self
<11>
|
===========unchanged ref 0===========
at: bitsandbytes.functional
QuantState(absmax, shape=None, code=None, blocksize=None, quant_type=None, dtype=None, offset=None, state2=None)
at: bitsandbytes.functional.QuantState
valid_quant_types = ("fp4", "nf4")
valid_qs_type_keys = [f"bitsandbytes__{x}" for x in valid_quant_types]
valid_qs_keys = [
"absmax",
"quant_map",
"nested_absmax",
"nested_quant_map",
"quant_state",
"quant_type",
"blocksize",
"dtype",
"shape",
"nested_blocksize",
"nested_dtype",
"nested_offset",
]
from_dict(qs_dict: Dict[str, Any], device: torch.device) -> "QuantState"
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
bitsandbytes.nn.modules/Linear4bit.forward
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
6d714a5cce3db5bd7f577bc447becc7a92d5ccc7
|
Embedding4bit and Embedding8bit implementation (#1292)
|
<0>:<add> fix_4bit_weight_quant_state_from_module(self)
<add>
<4>:<del> if getattr(self.weight, "quant_state", None) is None:
<5>:<del> if getattr(self, "quant_state", None) is not None:
<6>:<del> # the quant state got lost when the parameter got converted. This happens for example for fsdp
<7>:<del> # since we registered the module, we can recover the state here
<8>:<del> assert self.weight.shape[1] == 1
<9>:<del> if not isinstance(self.weight, Params4bit):
<10>:<del> self.weight = Params4bit(self.weight, quant_storage=self.quant_storage, bnb_quantized=True)
<11>:<del> self.weight.quant_state = self.quant_state
<12>:<del> else:
<13>:<del> print(
<14>:<del> "FP4 quantization state not initialized. Please call .cuda() or .to(device) on the LinearFP4 layer first.",
<15>:<del> )
|
# module: bitsandbytes.nn.modules
class Linear4bit(nn.Linear):
def forward(self, x: torch.Tensor):
<0> # weights are cast automatically as Int8Params, but the bias has to be cast manually
<1> if self.bias is not None and self.bias.dtype != x.dtype:
<2> self.bias.data = self.bias.data.to(x.dtype)
<3>
<4> if getattr(self.weight, "quant_state", None) is None:
<5> if getattr(self, "quant_state", None) is not None:
<6> # the quant state got lost when the parameter got converted. This happens for example for fsdp
<7> # since we registered the module, we can recover the state here
<8> assert self.weight.shape[1] == 1
<9> if not isinstance(self.weight, Params4bit):
<10> self.weight = Params4bit(self.weight, quant_storage=self.quant_storage, bnb_quantized=True)
<11> self.weight.quant_state = self.quant_state
<12> else:
<13> print(
<14> "FP4 quantization state not initialized. Please call .cuda() or .to(device) on the LinearFP4 layer first.",
<15> )
<16> if not self.compute_type_is_set:
<17> self.set_compute_type(x)
<18> self.compute_type_is_set = True
<19>
<20> inp_dtype = x.dtype
<21> if self.compute_dtype is not None:
<22> x = x.to(self.compute_dtype)
<23>
<24> bias = None if self.bias is None else self.bias.to(self.compute_dtype)
<25> out = bnb.matmul_4bit(x, self.weight.t(), bias=bias, quant_state=self.weight.quant_state)
<26>
<27> out = out.to(inp_dtype)
<28>
<29> return out
<30>
|
===========changed ref 0===========
# module: bitsandbytes.nn.modules
+ def fix_4bit_weight_quant_state_from_module(module: Union["Embedding4bit", "Linear4bit"]):
+ if getattr(module.weight, "quant_state", None) is not None:
+ return
+
+ if getattr(module, "quant_state", None) is None:
+ warnings.warn(
+ "FP4 quantization state not initialized. Please call .cuda() or .to(device) on the LinearFP4 layer first.",
+ )
+
+ # the quant state got lost when the parameter got converted. This happens for example for fsdp
+ # since we registered the module, we can recover the state here
+ assert module.weight.shape[1] == 1
+ if not isinstance(module.weight, Params4bit):
+ module.weight = Params4bit(module.weight, quant_storage=module.quant_storage, bnb_quantized=True)
+ module.weight.quant_state = module.quant_state
+
|
bitsandbytes.cextension/get_cuda_bnb_library_path
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
a4875fc0c38a15f704a884af63d3658eb00c417f
|
Bugfix: Load correct nocublaslt library variant when BNB_CUDA_VERSION override is set (#1318)
|
<14>:<del> library_name_stem, _, library_name_ext = library_name.rpartition(".")
<15>:<del> # `library_name_stem` will now be e.g. `libbitsandbytes_cuda118`;
<16>:<del> # let's remove any trailing numbers:
<17>:<del> library_name_stem = library_name_stem.rstrip("0123456789")
<18>:<del> # `library_name_stem` will now be e.g. `libbitsandbytes_cuda`;
<19>:<del> # let's tack the new version number and the original extension back on.
<20>:<del> library_name = f"{library_name_stem}{override_value}.{library_name_ext}"
<21>:<add> library_name = re.sub("cuda\d+", f"cuda{override_value}", library_name, count=1)
|
# module: bitsandbytes.cextension
def get_cuda_bnb_library_path(cuda_specs: CUDASpecs) -> Path:
<0> """
<1> Get the disk path to the CUDA BNB native library specified by the
<2> given CUDA specs, taking into account the `BNB_CUDA_VERSION` override environment variable.
<3>
<4> The library is not guaranteed to exist at the returned path.
<5> """
<6> library_name = f"libbitsandbytes_cuda{cuda_specs.cuda_version_string}"
<7> if not cuda_specs.has_cublaslt:
<8> # if not has_cublaslt (CC < 7.5), then we have to choose _nocublaslt
<9> library_name += "_nocublaslt"
<10> library_name = f"{library_name}{DYNAMIC_LIBRARY_SUFFIX}"
<11>
<12> override_value = os.environ.get("BNB_CUDA_VERSION")
<13> if override_value:
<14> library_name_stem, _, library_name_ext = library_name.rpartition(".")
<15> # `library_name_stem` will now be e.g. `libbitsandbytes_cuda118`;
<16> # let's remove any trailing numbers:
<17> library_name_stem = library_name_stem.rstrip("0123456789")
<18> # `library_name_stem` will now be e.g. `libbitsandbytes_cuda`;
<19> # let's tack the new version number and the original extension back on.
<20> library_name = f"{library_name_stem}{override_value}.{library_name_ext}"
<21> logger.warning(
<22> f"WARNING: BNB_CUDA_VERSION={override_value} environment variable detected; loading {library_name}.\n"
<23> "This can be used to load a bitsandbytes version that is different from the PyTorch CUDA version.\n"
<24> "If this was unintended set the BNB_CUDA_VERSION variable to an empty string: export BNB_CUDA_VERSION=\n"
<25> "If you use the manual override</s>
|
===========below chunk 0===========
# module: bitsandbytes.cextension
def get_cuda_bnb_library_path(cuda_specs: CUDASpecs) -> Path:
# offset: 1
"For example by adding the following to your .bashrc: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<path_to_cuda_dir/lib64\n",
)
return PACKAGE_DIR / library_name
|
bitsandbytes.functional/dequantize_blockwise
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
a685654b208115bed25eb9d1a06272f822659b52
|
Enable certain CUDA kernels to accept specified cuda stream (#1330)
|
# module: bitsandbytes.functional
def dequantize_blockwise(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
code: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 4096,
nested=False,
) -> Tensor:
<0> """
<1> Dequantizes blockwise quantized values.
<2>
<3> Dequantizes the tensor A with maximum absolute values absmax in
<4> blocks of size 4096.
<5>
<6> Parameters
<7> ----------
<8> A : torch.Tensor
<9> The input 8-bit tensor.
<10> quant_state : QuantState
<11> Object with code, absmax and other quantization state components.
<12> absmax : torch.Tensor
<13> The absmax values.
<14> code : torch.Tensor
<15> The quantization map.
<16> out : torch.Tensor
<17> Dequantized output tensor (default: float32)
<18>
<19>
<20> Returns
<21> -------
<22> torch.Tensor:
<23> Dequantized tensor (default: float32)
<24> """
<25> assert quant_state is not None or absmax is not None
<26> if code is None and quant_state is None:
<27> if "dynamic" not in name2qmap:
<28> name2qmap["dynamic"] = create_dynamic_map().to(A.device)
<29> code = name2qmap["dynamic"]
<30>
<31> if quant_state is None:
<32> quant_state = QuantState(absmax=absmax, code=code, blocksize=blocksize, dtype=torch.float32)
<33>
<34> absmax = quant_state.absmax
<35> if quant_state.nested:
<36> absmax = dequantize_blockwise(quant_state.absmax, quant_state.state2)
<37> absmax += quant_state.offset
<38> if absmax.dtype != torch.float32:
<39> absmax = absmax.float()
<40>
<41> if out is None:
<42> </s>
|
===========below chunk 0===========
# module: bitsandbytes.functional
def dequantize_blockwise(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
code: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 4096,
nested=False,
) -> Tensor:
# offset: 1
if A.device.type != "cpu":
device = pre_call(A.device)
code = quant_state.code.to(A.device)
if quant_state.blocksize not in [2048, 4096, 1024, 512, 256, 128, 64]:
raise ValueError(
f"The blockwise of {quant_state.blocksize} is not supported. Supported values: [2048, 4096, 1024, 512, 256, 128, 64]",
)
is_on_gpu([A, absmax, out])
if out.dtype == torch.float32:
lib.cdequantize_blockwise_fp32(
get_ptr(quant_state.code),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(A.numel()),
)
elif out.dtype == torch.float16:
lib.cdequantize_blockwise_fp16(
get_ptr(quant_state.code),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(A.numel()),
)
elif out.dtype == torch.bfloat16:
lib.cdequantize_blockwise_bf16(
get_ptr(quant_state.code),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct</s>
===========below chunk 1===========
# module: bitsandbytes.functional
def dequantize_blockwise(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
code: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 4096,
nested=False,
) -> Tensor:
# offset: 2
<s>(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(A.numel()),
)
else:
raise ValueError(f"Blockwise quantization only supports 16/32-bit floats, but got {A.dtype}")
post_call(A.device)
else:
code = quant_state.code.cpu()
lib.cdequantize_blockwise_cpu_fp32(
get_ptr(code),
get_ptr(A),
get_ptr(quant_state.absmax),
get_ptr(out),
ct.c_longlong(quant_state.blocksize),
ct.c_longlong(A.numel()),
)
return out
===========changed ref 0===========
# module: bitsandbytes.functional
+ def get_tensor_stream(tensor: Tensor) -> torch.cuda.Stream:
+ stream = torch.cuda.current_stream(tensor.device)
+ return stream
+
|
|
bitsandbytes.functional/dequantize_4bit
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
a685654b208115bed25eb9d1a06272f822659b52
|
Enable certain CUDA kernels to accept specified cuda stream (#1330)
|
# module: bitsandbytes.functional
def dequantize_4bit(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 64,
quant_type="fp4",
) -> Tensor:
<0> """
<1> Dequantizes FP4 blockwise quantized values.
<2>
<3> Dequantizes the tensor A with maximum absolute values absmax in blocks of size blocksize.
<4>
<5> Parameters
<6> ----------
<7> A : torch.Tensor
<8> The input tensor (packed 4-bit values).
<9> quant_state : QuantState
<10> object with quantisation stats, incl. absmax values, original tensor shape and original dtype.
<11> absmax : torch.Tensor
<12> The absmax values.
<13> out : torch.Tensor
<14> Dequantized output tensor.
<15> blocksize : int
<16> The blocksize used in quantization.
<17> quant_type : str
<18> The 4-bit quantization data type {fp4, nf4}
<19>
<20>
<21> Returns
<22> -------
<23> torch.Tensor:
<24> Dequantized tensor.
<25> """
<26> if blocksize not in [2048, 4096, 1024, 512, 256, 128, 64]:
<27> raise ValueError(
<28> f"The blockwise of {blocksize} is not supported. Supported values: [2048, 4096, 1024, 512, 256, 128, 64]",
<29> )
<30> if quant_type not in ["fp4", "nf4"]:
<31> raise NotImplementedError(f"4-bit quantization data type {quant_type} is not implemented.")
<32>
<33> if quant_state is None:
<34> assert absmax is not None and out is not None
<35>
<36> quant_state = QuantState(
<37> absmax=absmax,
<38> shape=out.shape,
<39> dtype=out.dtype,
<40> blocksize=blocksize,
<41> quant_type=quant_type,
<42> )
<43>
<44> else:</s>
|
===========below chunk 0===========
# module: bitsandbytes.functional
def dequantize_4bit(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 64,
quant_type="fp4",
) -> Tensor:
# offset: 1
if quant_state.nested:
absmax = dequantize_blockwise(quant_state.absmax, quant_state.state2)
absmax += quant_state.offset
if absmax.dtype != torch.float32:
absmax = absmax.float()
if out is None:
out = torch.empty(quant_state.shape, dtype=quant_state.dtype, device=A.device)
n = out.numel()
device = pre_call(A.device)
is_on_gpu([A, absmax, out])
if out.dtype == torch.float32:
if quant_state.quant_type == "fp4":
lib.cdequantize_blockwise_fp32_fp4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
)
else:
lib.cdequantize_blockwise_fp32_nf4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
)
elif out.dtype == torch.float16:
if quant_state.quant_type == "fp4":
lib.cdequantize_blockwise_fp16_fp4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_</s>
===========below chunk 1===========
# module: bitsandbytes.functional
def dequantize_4bit(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 64,
quant_type="fp4",
) -> Tensor:
# offset: 2
<s> get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
)
else:
lib.cdequantize_blockwise_fp16_nf4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
)
elif out.dtype == torch.bfloat16:
if quant_state.quant_type == "fp4":
lib.cdequantize_blockwise_bf16_fp4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
)
else:
lib.cdequantize_blockwise_bf16_nf4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
)
else:
raise ValueError(f"Blockwise quantization only supports 16/32-bit floats, but got {A.dtype}")
post_call(A.device)
is_transposed = True if A.shape[0
===========changed ref 0===========
# module: bitsandbytes.functional
+ def get_tensor_stream(tensor: Tensor) -> torch.cuda.Stream:
+ stream = torch.cuda.current_stream(tensor.device)
+ return stream
+
===========changed ref 1===========
# module: bitsandbytes.functional
def dequantize_blockwise(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
code: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 4096,
nested=False,
) -> Tensor:
"""
Dequantizes blockwise quantized values.
Dequantizes the tensor A with maximum absolute values absmax in
blocks of size 4096.
Parameters
----------
A : torch.Tensor
The input 8-bit tensor.
quant_state : QuantState
Object with code, absmax and other quantization state components.
absmax : torch.Tensor
The absmax values.
code : torch.Tensor
The quantization map.
out : torch.Tensor
Dequantized output tensor (default: float32)
Returns
-------
torch.Tensor:
Dequantized tensor (default: float32)
"""
assert quant_state is not None or absmax is not None
if code is None and quant_state is None:
if "dynamic" not in name2qmap:
name2qmap["dynamic"] = create_dynamic_map().to(A.device)
code = name2qmap["dynamic"]
if quant_state is None:
quant_state = QuantState(absmax=absmax, code=code, blocksize=blocksize, dtype=torch.float32)
absmax = quant_state.absmax
if quant_state.nested:
absmax = dequantize_blockwise(quant_state.absmax, quant_state.state2)
absmax += quant_state.offset
if absmax.dtype != torch.float32:
absmax = absmax.float()
if out is None:
out = torch.empty(A.shape, dtype=quant_state.dtype, device=A.device)
if A.device.type != "cpu":
device = pre</s>
|
|
bitsandbytes.functional/dequantize_no_absmax
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
a685654b208115bed25eb9d1a06272f822659b52
|
Enable certain CUDA kernels to accept specified cuda stream (#1330)
|
<24>:<add> stream = get_tensor_stream(A)
<add> lib.cdequantize(get_ptr(code), get_ptr(A), get_ptr(out), ct.c_int(A.numel()), stream)
<del> lib.cdequantize(get_ptr(code), get_ptr(A), get_ptr(out), ct.c_int(A.numel()))
|
# module: bitsandbytes.functional
def dequantize_no_absmax(A: Tensor, code: Tensor, out: Optional[torch.Tensor] = None) -> Tensor:
<0> """
<1> Dequantizes the 8-bit tensor to 32-bit.
<2>
<3> Dequantizes the 8-bit tensor `A` to the 32-bit tensor `out` via
<4> the quantization map `code`.
<5>
<6> Parameters
<7> ----------
<8> A : torch.Tensor
<9> The 8-bit input tensor.
<10> code : torch.Tensor
<11> The quantization map.
<12> out : torch.Tensor
<13> The 32-bit output tensor.
<14>
<15> Returns
<16> -------
<17> torch.Tensor:
<18> 32-bit output tensor.
<19> """
<20> prev_device = pre_call(A.device)
<21> if out is None:
<22> out = torch.zeros_like(A, dtype=torch.float32)
<23> is_on_gpu([code, A, out])
<24> lib.cdequantize(get_ptr(code), get_ptr(A), get_ptr(out), ct.c_int(A.numel()))
<25> post_call(prev_device)
<26> return out
<27>
|
===========changed ref 0===========
# module: bitsandbytes.functional
+ def get_tensor_stream(tensor: Tensor) -> torch.cuda.Stream:
+ stream = torch.cuda.current_stream(tensor.device)
+ return stream
+
===========changed ref 1===========
# module: bitsandbytes.functional
def dequantize_4bit(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 64,
quant_type="fp4",
) -> Tensor:
"""
Dequantizes FP4 blockwise quantized values.
Dequantizes the tensor A with maximum absolute values absmax in blocks of size blocksize.
Parameters
----------
A : torch.Tensor
The input tensor (packed 4-bit values).
quant_state : QuantState
object with quantisation stats, incl. absmax values, original tensor shape and original dtype.
absmax : torch.Tensor
The absmax values.
out : torch.Tensor
Dequantized output tensor.
blocksize : int
The blocksize used in quantization.
quant_type : str
The 4-bit quantization data type {fp4, nf4}
Returns
-------
torch.Tensor:
Dequantized tensor.
"""
if blocksize not in [2048, 4096, 1024, 512, 256, 128, 64]:
raise ValueError(
f"The blockwise of {blocksize} is not supported. Supported values: [2048, 4096, 1024, 512, 256, 128, 64]",
)
if quant_type not in ["fp4", "nf4"]:
raise NotImplementedError(f"4-bit quantization data type {quant_type} is not implemented.")
if quant_state is None:
assert absmax is not None and out is not None
quant_state = QuantState(
absmax=absmax,
shape=out.shape,
dtype=out.dtype,
blocksize=blocksize,
quant_type=quant_type,
)
else:
absmax = quant_state.absmax
if quant_state.nested:
absmax = dequantize_blockwise(quant_state.absmax, quant_state.state</s>
===========changed ref 2===========
# module: bitsandbytes.functional
def dequantize_4bit(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 64,
quant_type="fp4",
) -> Tensor:
# offset: 1
<s> quant_state.nested:
absmax = dequantize_blockwise(quant_state.absmax, quant_state.state2)
absmax += quant_state.offset
if absmax.dtype != torch.float32:
absmax = absmax.float()
if out is None:
out = torch.empty(quant_state.shape, dtype=quant_state.dtype, device=A.device)
n = out.numel()
device = pre_call(A.device)
is_on_gpu([A, absmax, out])
+ stream = get_tensor_stream(A)
if out.dtype == torch.float32:
if quant_state.quant_type == "fp4":
lib.cdequantize_blockwise_fp32_fp4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
+ stream,
)
else:
lib.cdequantize_blockwise_fp32_nf4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
+ stream,
)
elif out.dtype == torch.float16:
if quant_state.quant_type == "fp4":
lib.</s>
===========changed ref 3===========
# module: bitsandbytes.functional
def dequantize_4bit(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 64,
quant_type="fp4",
) -> Tensor:
# offset: 2
<s>quantize_blockwise_fp16_fp4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
+ stream,
)
else:
lib.cdequantize_blockwise_fp16_nf4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
+ stream,
)
elif out.dtype == torch.bfloat16:
if quant_state.quant_type == "fp4":
lib.cdequantize_blockwise_bf16_fp4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
+ stream,
)
else:
lib.cdequantize_blockwise_bf16_nf4(
get_ptr(None),
get_ptr(A),
get_ptr(absmax),
get_ptr(out),
ct.c_int(quant_state.blocksize),
ct.c_int(n),
+ stream,
)
else:
raise ValueError(f"Blockwise quantization</s>
===========changed ref 4===========
# module: bitsandbytes.functional
def dequantize_4bit(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 64,
quant_type="fp4",
) -> Tensor:
# offset: 3
<s> 16/32-bit floats, but got {A.dtype}")
post_call(A.device)
is_transposed = True if A.shape[0] == 1 else False
if is_transposed:
return out.t()
else:
return out
|
bitsandbytes.functional/gemv_4bit
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
a685654b208115bed25eb9d1a06272f822659b52
|
Enable certain CUDA kernels to accept specified cuda stream (#1330)
|
# module: bitsandbytes.functional
def gemv_4bit(
A: Tensor,
B: Tensor,
out: Optional[torch.Tensor] = None,
transposed_A=False,
transposed_B=False,
state=None,
):
<0> prev_device = pre_call(A.device)
<1> # sout = check_matmul(A, B, out, transposed_A, transposed_B, expected_type=A.dtype)
<2> if state is None:
<3> raise ValueError("state cannot None. gem_4bit( ) requires the state from quantize_4bit( )")
<4>
<5> if A.numel() != A.shape[-1]:
<6> raise ValueError(
<7> 'Dimensions of A are invalid. Must be a vector with the leading dimensions of "1", e.g. [1, 1, 2048]',
<8> )
<9>
<10> Bshape = state.shape
<11> bout = Bshape[0]
<12> absmax = state.absmax
<13> if state.nested:
<14> absmax = dequantize_blockwise(state.absmax, state.state2)
<15> absmax += state.offset
<16>
<17> if out is None:
<18> if len(A.shape) == 3:
<19> out = torch.empty(size=(A.shape[0], A.shape[1], bout), dtype=A.dtype, device=A.device)
<20> else:
<21> out = torch.empty(size=(A.shape[0], bout), dtype=A.dtype, device=A.device)
<22>
<23> n = 1
<24> m = Bshape[0]
<25> k = Bshape[1]
<26> lda = Bshape[0]
<27> ldc = Bshape[0]
<28> ldb = (A.shape[-1] + 1) // 2
<29> is_on_gpu([B, A, out, absmax, state.code])
<30> m = ct.c_int32(m)
<31> n = ct.c_int32(n)
<32> k = ct.c</s>
|
===========below chunk 0===========
# module: bitsandbytes.functional
def gemv_4bit(
A: Tensor,
B: Tensor,
out: Optional[torch.Tensor] = None,
transposed_A=False,
transposed_B=False,
state=None,
):
# offset: 1
lda = ct.c_int32(lda)
ldb = ct.c_int32(ldb)
ldc = ct.c_int32(ldc)
if B.dtype in [torch.uint8, torch.bfloat16, torch.float16, torch.float32]:
if A.dtype == torch.float16:
lib.cgemm_4bit_inference_naive_fp16(
m,
n,
k,
get_ptr(A),
get_ptr(B),
get_ptr(absmax),
get_ptr(state.code),
get_ptr(out),
lda,
ldb,
ldc,
ct.c_int32(state.blocksize),
)
elif A.dtype == torch.bfloat16:
lib.cgemm_4bit_inference_naive_bf16(
m,
n,
k,
get_ptr(A),
get_ptr(B),
get_ptr(absmax),
get_ptr(state.code),
get_ptr(out),
lda,
ldb,
ldc,
ct.c_int32(state.blocksize),
)
elif A.dtype == torch.float32:
lib.cgemm_4bit_inference_naive_fp32(
m,
n,
k,
get_ptr(A),
get_ptr(B),
get_ptr(absmax),
get_ptr(state.code),
get_ptr(out),
lda,
ldb,
ldc,
ct.c_int32(state.blocksize),
)
else</s>
===========below chunk 1===========
# module: bitsandbytes.functional
def gemv_4bit(
A: Tensor,
B: Tensor,
out: Optional[torch.Tensor] = None,
transposed_A=False,
transposed_B=False,
state=None,
):
# offset: 2
<s>
ldb,
ldc,
ct.c_int32(state.blocksize),
)
else:
raise NotImplementedError(f"Matmul not implemented for data type {A.dtype}")
else:
raise NotImplementedError(f"Matmul not implemented for data type {A.dtype}")
post_call(prev_device)
return out
===========changed ref 0===========
# module: bitsandbytes.functional
def dequantize_no_absmax(A: Tensor, code: Tensor, out: Optional[torch.Tensor] = None) -> Tensor:
"""
Dequantizes the 8-bit tensor to 32-bit.
Dequantizes the 8-bit tensor `A` to the 32-bit tensor `out` via
the quantization map `code`.
Parameters
----------
A : torch.Tensor
The 8-bit input tensor.
code : torch.Tensor
The quantization map.
out : torch.Tensor
The 32-bit output tensor.
Returns
-------
torch.Tensor:
32-bit output tensor.
"""
prev_device = pre_call(A.device)
if out is None:
out = torch.zeros_like(A, dtype=torch.float32)
is_on_gpu([code, A, out])
+ stream = get_tensor_stream(A)
+ lib.cdequantize(get_ptr(code), get_ptr(A), get_ptr(out), ct.c_int(A.numel()), stream)
- lib.cdequantize(get_ptr(code), get_ptr(A), get_ptr(out), ct.c_int(A.numel()))
post_call(prev_device)
return out
===========changed ref 1===========
# module: bitsandbytes.functional
+ def get_tensor_stream(tensor: Tensor) -> torch.cuda.Stream:
+ stream = torch.cuda.current_stream(tensor.device)
+ return stream
+
===========changed ref 2===========
# module: bitsandbytes.functional
def dequantize_4bit(
A: Tensor,
quant_state: Optional[QuantState] = None,
absmax: Optional[torch.Tensor] = None,
out: Optional[torch.Tensor] = None,
blocksize: int = 64,
quant_type="fp4",
) -> Tensor:
"""
Dequantizes FP4 blockwise quantized values.
Dequantizes the tensor A with maximum absolute values absmax in blocks of size blocksize.
Parameters
----------
A : torch.Tensor
The input tensor (packed 4-bit values).
quant_state : QuantState
object with quantisation stats, incl. absmax values, original tensor shape and original dtype.
absmax : torch.Tensor
The absmax values.
out : torch.Tensor
Dequantized output tensor.
blocksize : int
The blocksize used in quantization.
quant_type : str
The 4-bit quantization data type {fp4, nf4}
Returns
-------
torch.Tensor:
Dequantized tensor.
"""
if blocksize not in [2048, 4096, 1024, 512, 256, 128, 64]:
raise ValueError(
f"The blockwise of {blocksize} is not supported. Supported values: [2048, 4096, 1024, 512, 256, 128, 64]",
)
if quant_type not in ["fp4", "nf4"]:
raise NotImplementedError(f"4-bit quantization data type {quant_type} is not implemented.")
if quant_state is None:
assert absmax is not None and out is not None
quant_state = QuantState(
absmax=absmax,
shape=out.shape,
dtype=out.dtype,
blocksize=blocksize,
quant_type=quant_type,
)
else:
absmax = quant_state.absmax
if quant_state.nested:
absmax = dequantize_blockwise(quant_state.absmax, quant_state.state</s>
|
|
bitsandbytes.optim.optimizer/Optimizer8bit.load_state_dict
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
8fc789249f6bbcde5ade57866707235a11369f2d
|
Add `move_to_device` kwarg to the optimizer's `load_state_dict` (#1344)
|
<5>:<add> move_to_device (`bool`, defaults to `True`):
<add> Whether to move the optimizer's state to the device.
|
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
+ def load_state_dict(self, state_dict, move_to_device=True):
- def load_state_dict(self, state_dict):
<0> """Load an optimizer state.
<1>
<2> Arguments:
<3> state_dict (`dict`):
<4> An optimizer state (should be returned from a call to `state_dict`) to load.
<5> """
<6> # deepcopy, to be consistent with module API
<7> state_dict = deepcopy(state_dict)
<8> # Validate the state_dict
<9> groups = self.param_groups
<10> saved_groups = state_dict["param_groups"]
<11>
<12> if len(groups) != len(saved_groups):
<13> raise ValueError("loaded state dict has a different number of parameter groups")
<14> param_lens = (len(g["params"]) for g in groups)
<15> saved_lens = (len(g["params"]) for g in saved_groups)
<16> if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens)):
<17> raise ValueError(
<18> "loaded state dict contains a parameter group that doesn't match the size of optimizer's group",
<19> )
<20>
<21> # Update the state
<22> id_map = {
<23> old_id: p
<24> for old_id, p in zip(
<25> chain.from_iterable(g["params"] for g in saved_groups),
<26> chain.from_iterable(g["params"] for g in groups),
<27> )
<28> }
<29>
<30> def cast(param, value):
<31> r"""Make a deep copy of value, casting all tensors to device of param."""
<32> if isinstance(value, torch.Tensor):
<33> # Floating-point types are a bit special here. They are the only ones
<34> # that are assumed to always match the type of params.
<35> if param.is_floating_point() and value.dtype != torch.uint8:
<36> value = value.to(param</s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
+ def load_state_dict(self, state_dict, move_to_device=True):
- def load_state_dict(self, state_dict):
# offset: 1
return value
elif isinstance(value, dict):
for k, v in value.items():
if k in self.non_castable_tensor_keys:
value[k] = v.to(param.device)
else:
value[k] = cast(param, v)
return value
elif isinstance(value, container_abcs.Iterable):
return type(value)(cast(param, v) for v in value)
else:
return value
# Copy state assigned to params (and cast tensors to appropriate types).
# State that is not assigned to params is copied as is (needed for
# backward compatibility).
state = defaultdict(dict)
for k, v in state_dict["state"].items():
if k in id_map:
param = id_map[k]
state[param] = cast(param, v)
else:
state[k] = v
# Update parameter groups, setting their 'params' value
def update_group(group, new_group):
new_group["params"] = group["params"]
return new_group
param_groups = [update_group(g, ng) for g, ng in zip(groups, saved_groups)]
self.__setstate__({"state": state, "param_groups": param_groups})
|
bitsandbytes.optim.optimizer/Optimizer8bit.load_state_dict
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
d9645465de5212cf65e5a1baeed6f1840ea7913b
|
Add AdEMAMix optimizer (#1360)
|
<18>:<add> if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens, strict=True)):
<del> if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens)):
<29>:<add> strict=True,
|
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def load_state_dict(self, state_dict, move_to_device=True):
<0> """Load an optimizer state.
<1>
<2> Arguments:
<3> state_dict (`dict`):
<4> An optimizer state (should be returned from a call to `state_dict`) to load.
<5> move_to_device (`bool`, defaults to `True`):
<6> Whether to move the optimizer's state to the device.
<7> """
<8> # deepcopy, to be consistent with module API
<9> state_dict = deepcopy(state_dict)
<10> # Validate the state_dict
<11> groups = self.param_groups
<12> saved_groups = state_dict["param_groups"]
<13>
<14> if len(groups) != len(saved_groups):
<15> raise ValueError("loaded state dict has a different number of parameter groups")
<16> param_lens = (len(g["params"]) for g in groups)
<17> saved_lens = (len(g["params"]) for g in saved_groups)
<18> if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens)):
<19> raise ValueError(
<20> "loaded state dict contains a parameter group that doesn't match the size of optimizer's group",
<21> )
<22>
<23> # Update the state
<24> id_map = {
<25> old_id: p
<26> for old_id, p in zip(
<27> chain.from_iterable(g["params"] for g in saved_groups),
<28> chain.from_iterable(g["params"] for g in groups),
<29> )
<30> }
<31>
<32> def cast(param, value):
<33> r"""Make a deep copy of value, casting all tensors to device of param."""
<34> if isinstance(value, torch.Tensor):
<35> # Floating-point types are a bit special here. They are the only ones
<36> # that are assumed to always match the type of params.
<37> if param.is_floating_point() and value.dtype != torch</s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def load_state_dict(self, state_dict, move_to_device=True):
# offset: 1
value = value.to(param.dtype)
return value
elif isinstance(value, dict):
for k, v in value.items():
if k in self.non_castable_tensor_keys:
if move_to_device:
value[k] = v.to(param.device)
else:
value[k] = cast(param, v)
return value
elif isinstance(value, container_abcs.Iterable):
return type(value)(cast(param, v) for v in value)
else:
return value
# Copy state assigned to params (and cast tensors to appropriate types).
# State that is not assigned to params is copied as is (needed for
# backward compatibility).
state = defaultdict(dict)
for k, v in state_dict["state"].items():
if k in id_map:
param = id_map[k]
state[param] = cast(param, v)
else:
state[k] = v
# Update parameter groups, setting their 'params' value
def update_group(group, new_group):
new_group["params"] = group["params"]
return new_group
param_groups = [update_group(g, ng) for g, ng in zip(groups, saved_groups)]
self.__setstate__({"state": state, "param_groups": param_groups})
|
bitsandbytes.optim.optimizer/Optimizer8bit.get_config
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
d9645465de5212cf65e5a1baeed6f1840ea7913b
|
Add AdEMAMix optimizer (#1360)
|
<5>:<add> config["alpha"] = group.get("alpha")
<add> config["t_alpha"] = group.get("t_alpha")
<add> config["t_beta3"] = group.get("t_beta3")
|
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def get_config(self, gindex, pindex, group):
<0> config = {}
<1> config["betas"] = group["betas"]
<2> config["eps"] = group["eps"]
<3> config["weight_decay"] = group["weight_decay"]
<4> config["lr"] = group["lr"]
<5> config["optim_bits"] = self.args.optim_bits
<6> config["min_8bit_size"] = self.args.min_8bit_size
<7> config["percentile_clipping"] = self.args.percentile_clipping
<8> config["block_wise"] = self.args.block_wise
<9> config["max_unorm"] = self.args.max_unorm
<10> config["skip_zeros"] = self.args.skip_zeros
<11>
<12> if (gindex, pindex) in self.mng.index2config:
<13> config.update(self.mng.index2config[(gindex, pindex)])
<14> return config
<15>
|
===========changed ref 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def load_state_dict(self, state_dict, move_to_device=True):
"""Load an optimizer state.
Arguments:
state_dict (`dict`):
An optimizer state (should be returned from a call to `state_dict`) to load.
move_to_device (`bool`, defaults to `True`):
Whether to move the optimizer's state to the device.
"""
# deepcopy, to be consistent with module API
state_dict = deepcopy(state_dict)
# Validate the state_dict
groups = self.param_groups
saved_groups = state_dict["param_groups"]
if len(groups) != len(saved_groups):
raise ValueError("loaded state dict has a different number of parameter groups")
param_lens = (len(g["params"]) for g in groups)
saved_lens = (len(g["params"]) for g in saved_groups)
+ if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens, strict=True)):
- if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens)):
raise ValueError(
"loaded state dict contains a parameter group that doesn't match the size of optimizer's group",
)
# Update the state
id_map = {
old_id: p
for old_id, p in zip(
chain.from_iterable(g["params"] for g in saved_groups),
chain.from_iterable(g["params"] for g in groups),
+ strict=True,
)
}
def cast(param, value):
r"""Make a deep copy of value, casting all tensors to device of param."""
if isinstance(value, torch.Tensor):
# Floating-point types are a bit special here. They are the only ones
# that are assumed to always match the type of params.
if param.is_floating_point</s>
===========changed ref 1===========
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def load_state_dict(self, state_dict, move_to_device=True):
# offset: 1
<s> They are the only ones
# that are assumed to always match the type of params.
if param.is_floating_point() and value.dtype != torch.uint8:
value = value.to(param.dtype)
return value
elif isinstance(value, dict):
for k, v in value.items():
if k in self.non_castable_tensor_keys:
if move_to_device:
value[k] = v.to(param.device)
else:
value[k] = cast(param, v)
return value
elif isinstance(value, container_abcs.Iterable):
return type(value)(cast(param, v) for v in value)
else:
return value
# Copy state assigned to params (and cast tensors to appropriate types).
# State that is not assigned to params is copied as is (needed for
# backward compatibility).
state = defaultdict(dict)
for k, v in state_dict["state"].items():
if k in id_map:
param = id_map[k]
state[param] = cast(param, v)
else:
state[k] = v
# Update parameter groups, setting their 'params' value
def update_group(group, new_group):
new_group["params"] = group["params"]
return new_group
+ param_groups = [update_group(g, ng) for g, ng in zip(groups, saved_groups, strict=True)]
- param_groups = [update_group(g, ng) for g, ng in zip(groups, saved_groups)]
self.__setstate__({"state": state, "param_groups": param_groups})
|
bitsandbytes.optim.optimizer/Optimizer2State.__init__
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
d9645465de5212cf65e5a1baeed6f1840ea7913b
|
Add AdEMAMix optimizer (#1360)
|
<s>8,
weight_decay=0.0,
optim_bits=32,
args=None,
min_8bit_size=4096,
percentile_clipping=100,
block_wise=True,
max_unorm=0.0,
skip_zeros=False,
is_paged=False,
+ alpha=0.0,
+ t_alpha: Optional[int] = None,
+ t_beta3: Optional[int] = None,
):
<0> """
<1> Base 2-state update optimizer class.
<2>
<3> Arguments:
<4> optimizer_name (`str`):
<5> The name of the optimizer.
<6> params (`torch.tensor`):
<7> The input parameters to optimize.
<8> lr (`float`, defaults to 1e-3):
<9> The learning rate.
<10> betas (`tuple`, defaults to (0.9, 0.999)):
<11> The beta values for the optimizer.
<12> eps (`float`, defaults to 1e-8):
<13> The epsilon value for the optimizer.
<14> weight_decay (`float`, defaults to 0.0):
<15> The weight decay value for the optimizer.
<16> optim_bits (`int`, defaults to 32):
<17> The number of bits of the optimizer state.
<18> args (`object`, defaults to `None`):
<19> An object with additional arguments.
<20> min_8bit_size (`int`, defaults to 4096):
<21> The minimum number of elements of the parameter tensors for 8-bit optimization.
<22> percentile_clipping (`int`, defaults to 100):
<23> Adapts clipping threshold automatically by tracking the last 100 gradient norms and clipping the gradient at a certain percentile to improve stability.
<24> block_wise (`bool`, defaults to `True`):
<25> Whether to independently quantize each block of tensors to reduce outlier effects and improve stability.
<26> max_unorm (`float`, defaults to 0.0):
<27> The maximum value to normalize each block with.
<28> skip_zeros (`bool`, defaults to `False`):
<29> Whether to skip zero values for sparse gradients and models to ensure correct</s>
|
===========below chunk 0===========
<s>_decay=0.0,
optim_bits=32,
args=None,
min_8bit_size=4096,
percentile_clipping=100,
block_wise=True,
max_unorm=0.0,
skip_zeros=False,
is_paged=False,
+ alpha=0.0,
+ t_alpha: Optional[int] = None,
+ t_beta3: Optional[int] = None,
):
# offset: 1
is_paged (`bool`, defaults to `False`):
Whether the optimizer is a paged optimizer or not.
"""
if not 0.0 <= lr:
raise ValueError(f"Invalid learning rate: {lr}")
if not 0.0 <= eps:
raise ValueError(f"Invalid epsilon value: {eps}")
if isinstance(betas, str):
# format: '(beta1, beta2)'
betas = betas.replace("(", "").replace(")", "").strip().split(",")
betas = [float(b) for b in betas]
for i in range(len(betas)):
if not 0.0 <= betas[i] < 1.0:
raise ValueError(f"Invalid beta parameter at index {i}: {betas[i]}")
if not 0.0 <= weight_decay:
raise ValueError(f"Invalid weight_decay value: {weight_decay}")
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
super().__init__(params, defaults, optim_bits, is_paged)
if args is None:
args = {}
args["optim_bits"] = optim_bits
args["percentile_clipping"] = 100
args["min_8bit_size"] = min_8bit_size
args["percentile_clipping"] = percentile_clipping
args["block_wise"] = block_wise
args["max_unorm"] = max_unorm
args["skip_zeros"] = skip_zeros</s>
===========below chunk 1===========
<s>_decay=0.0,
optim_bits=32,
args=None,
min_8bit_size=4096,
percentile_clipping=100,
block_wise=True,
max_unorm=0.0,
skip_zeros=False,
is_paged=False,
+ alpha=0.0,
+ t_alpha: Optional[int] = None,
+ t_beta3: Optional[int] = None,
):
# offset: 2
<s> = block_wise
args["max_unorm"] = max_unorm
args["skip_zeros"] = skip_zeros
self.args = MockArgs(args)
else:
self.args = args
self.optimizer_name = optimizer_name
===========changed ref 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def get_config(self, gindex, pindex, group):
config = {}
config["betas"] = group["betas"]
config["eps"] = group["eps"]
config["weight_decay"] = group["weight_decay"]
config["lr"] = group["lr"]
+ config["alpha"] = group.get("alpha")
+ config["t_alpha"] = group.get("t_alpha")
+ config["t_beta3"] = group.get("t_beta3")
config["optim_bits"] = self.args.optim_bits
config["min_8bit_size"] = self.args.min_8bit_size
config["percentile_clipping"] = self.args.percentile_clipping
config["block_wise"] = self.args.block_wise
config["max_unorm"] = self.args.max_unorm
config["skip_zeros"] = self.args.skip_zeros
if (gindex, pindex) in self.mng.index2config:
config.update(self.mng.index2config[(gindex, pindex)])
return config
===========changed ref 1===========
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def load_state_dict(self, state_dict, move_to_device=True):
"""Load an optimizer state.
Arguments:
state_dict (`dict`):
An optimizer state (should be returned from a call to `state_dict`) to load.
move_to_device (`bool`, defaults to `True`):
Whether to move the optimizer's state to the device.
"""
# deepcopy, to be consistent with module API
state_dict = deepcopy(state_dict)
# Validate the state_dict
groups = self.param_groups
saved_groups = state_dict["param_groups"]
if len(groups) != len(saved_groups):
raise ValueError("loaded state dict has a different number of parameter groups")
param_lens = (len(g["params"]) for g in groups)
saved_lens = (len(g["params"]) for g in saved_groups)
+ if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens, strict=True)):
- if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens)):
raise ValueError(
"loaded state dict contains a parameter group that doesn't match the size of optimizer's group",
)
# Update the state
id_map = {
old_id: p
for old_id, p in zip(
chain.from_iterable(g["params"] for g in saved_groups),
chain.from_iterable(g["params"] for g in groups),
+ strict=True,
)
}
def cast(param, value):
r"""Make a deep copy of value, casting all tensors to device of param."""
if isinstance(value, torch.Tensor):
# Floating-point types are a bit special here. They are the only ones
# that are assumed to always match the type of params.
if param.is_floating_point</s>
===========changed ref 2===========
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def load_state_dict(self, state_dict, move_to_device=True):
# offset: 1
<s> They are the only ones
# that are assumed to always match the type of params.
if param.is_floating_point() and value.dtype != torch.uint8:
value = value.to(param.dtype)
return value
elif isinstance(value, dict):
for k, v in value.items():
if k in self.non_castable_tensor_keys:
if move_to_device:
value[k] = v.to(param.device)
else:
value[k] = cast(param, v)
return value
elif isinstance(value, container_abcs.Iterable):
return type(value)(cast(param, v) for v in value)
else:
return value
# Copy state assigned to params (and cast tensors to appropriate types).
# State that is not assigned to params is copied as is (needed for
# backward compatibility).
state = defaultdict(dict)
for k, v in state_dict["state"].items():
if k in id_map:
param = id_map[k]
state[param] = cast(param, v)
else:
state[k] = v
# Update parameter groups, setting their 'params' value
def update_group(group, new_group):
new_group["params"] = group["params"]
return new_group
+ param_groups = [update_group(g, ng) for g, ng in zip(groups, saved_groups, strict=True)]
- param_groups = [update_group(g, ng) for g, ng in zip(groups, saved_groups)]
self.__setstate__({"state": state, "param_groups": param_groups})
|
|
bitsandbytes.optim.optimizer/Optimizer2State.update_step
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
d9645465de5212cf65e5a1baeed6f1840ea7913b
|
Add AdEMAMix optimizer (#1360)
|
<34>:<add> config["betas"][2] if len(config["betas"]) >= 3 else 0.0,
<add> config["alpha"],
|
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def update_step(self, group, p, gindex, pindex):
<0> # avoid update error from non-contiguous memory layout
<1> p.data = p.data.contiguous()
<2> p.grad = p.grad.contiguous()
<3>
<4> state = self.state[p]
<5> grad = p.grad
<6>
<7> config = self.get_config(gindex, pindex, group)
<8>
<9> state["step"] += 1
<10> step = state["step"]
<11>
<12> if config["percentile_clipping"] < 100:
<13> current_gnorm, clip_value, gnorm_scale = F.percentile_clipping(
<14> grad,
<15> state["gnorm_vec"],
<16> step,
<17> config["percentile_clipping"],
<18> )
<19> else:
<20> gnorm_scale = 1.0
<21>
<22> if state["state1"].dtype == torch.float:
<23> F.optimizer_update_32bit(
<24> self.optimizer_name,
<25> grad,
<26> p,
<27> state["state1"],
<28> config["betas"][0],
<29> config["eps"],
<30> step,
<31> config["lr"],
<32> state["state2"],
<33> config["betas"][1],
<34> config["weight_decay"],
<35> gnorm_scale,
<36> state["unorm_vec"] if config["max_unorm"] > 0.0 else None,
<37> max_unorm=config["max_unorm"],
<38> skip_zeros=config["skip_zeros"],
<39> )
<40>
<41> elif state["state1"].dtype == torch.uint8 and not config["block_wise"]:
<42> F.optimizer_update_8bit(
<43> self.optimizer_name,
<44> grad,
<45> p,
<46> state["state1"],
<47> state["state2"],
<48> config["</s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def update_step(self, group, p, gindex, pindex):
# offset: 1
config["betas"][1],
config["eps"],
step,
config["lr"],
state["qmap1"],
state["qmap2"],
state["max1"],
state["max2"],
state["new_max1"],
state["new_max2"],
config["weight_decay"],
gnorm_scale=gnorm_scale,
unorm_vec=state["unorm_vec"] if config["max_unorm"] > 0.0 else None,
max_unorm=config["max_unorm"],
)
# swap maxes
state["max1"], state["new_max1"] = state["new_max1"], state["max1"]
state["max2"], state["new_max2"] = state["new_max2"], state["max2"]
elif state["state1"].dtype == torch.uint8 and config["block_wise"]:
F.optimizer_update_8bit_blockwise(
self.optimizer_name,
grad,
p,
state["state1"],
state["state2"],
config["betas"][0],
config["betas"][1],
config["eps"],
step,
config["lr"],
state["qmap1"],
state["qmap2"],
state["absmax1"],
state["absmax2"],
config["weight_decay"],
gnorm_scale=gnorm_scale,
skip_zeros=config["skip_zeros"],
)
===========changed ref 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def get_config(self, gindex, pindex, group):
config = {}
config["betas"] = group["betas"]
config["eps"] = group["eps"]
config["weight_decay"] = group["weight_decay"]
config["lr"] = group["lr"]
+ config["alpha"] = group.get("alpha")
+ config["t_alpha"] = group.get("t_alpha")
+ config["t_beta3"] = group.get("t_beta3")
config["optim_bits"] = self.args.optim_bits
config["min_8bit_size"] = self.args.min_8bit_size
config["percentile_clipping"] = self.args.percentile_clipping
config["block_wise"] = self.args.block_wise
config["max_unorm"] = self.args.max_unorm
config["skip_zeros"] = self.args.skip_zeros
if (gindex, pindex) in self.mng.index2config:
config.update(self.mng.index2config[(gindex, pindex)])
return config
===========changed ref 1===========
<s>8,
weight_decay=0.0,
optim_bits=32,
args=None,
min_8bit_size=4096,
percentile_clipping=100,
block_wise=True,
max_unorm=0.0,
skip_zeros=False,
is_paged=False,
+ alpha=0.0,
+ t_alpha: Optional[int] = None,
+ t_beta3: Optional[int] = None,
):
"""
Base 2-state update optimizer class.
Arguments:
optimizer_name (`str`):
The name of the optimizer.
params (`torch.tensor`):
The input parameters to optimize.
lr (`float`, defaults to 1e-3):
The learning rate.
betas (`tuple`, defaults to (0.9, 0.999)):
The beta values for the optimizer.
eps (`float`, defaults to 1e-8):
The epsilon value for the optimizer.
weight_decay (`float`, defaults to 0.0):
The weight decay value for the optimizer.
optim_bits (`int`, defaults to 32):
The number of bits of the optimizer state.
args (`object`, defaults to `None`):
An object with additional arguments.
min_8bit_size (`int`, defaults to 4096):
The minimum number of elements of the parameter tensors for 8-bit optimization.
percentile_clipping (`int`, defaults to 100):
Adapts clipping threshold automatically by tracking the last 100 gradient norms and clipping the gradient at a certain percentile to improve stability.
block_wise (`bool`, defaults to `True`):
Whether to independently quantize each block of tensors to reduce outlier effects and improve stability.
max_unorm (`float`, defaults to 0.0):
The maximum value to normalize each block with.
skip_zeros (`bool`, defaults to `False`):
Whether to skip zero values for sparse gradients and models to ensure correct updates.
is_paged (`bool`, defaults to `False`):
Whether the optimizer is a paged optimizer or not.</s>
===========changed ref 2===========
<s>_decay=0.0,
optim_bits=32,
args=None,
min_8bit_size=4096,
percentile_clipping=100,
block_wise=True,
max_unorm=0.0,
skip_zeros=False,
is_paged=False,
+ alpha=0.0,
+ t_alpha: Optional[int] = None,
+ t_beta3: Optional[int] = None,
):
# offset: 1
<s> updates.
is_paged (`bool`, defaults to `False`):
Whether the optimizer is a paged optimizer or not.
+ alpha (`float`, defaults to 0.0):
+ The alpha value for the AdEMAMix optimizer.
+ t_alpha (`Optional[int]`, defaults to `None`):
+ Number of iterations for alpha scheduling with AdEMAMix.
+ t_beta3 (`Optional[int]`, defaults to `None`):
+ Number of iterations for beta scheduling with AdEMAMix.
+
"""
if not 0.0 <= lr:
raise ValueError(f"Invalid learning rate: {lr}")
if not 0.0 <= eps:
raise ValueError(f"Invalid epsilon value: {eps}")
if isinstance(betas, str):
# format: '(beta1, beta2)'
betas = betas.replace("(", "").replace(")", "").strip().split(",")
betas = [float(b) for b in betas]
for i in range(len(betas)):
if not 0.0 <= betas[i] < 1.0:
raise ValueError(f"Invalid beta parameter at index {i}: {betas[i]}")
if not 0.0 <= weight_decay:
raise ValueError(f"Invalid weight_decay value: {weight_decay}")
+
+ defaults = dict(
+ lr=lr, betas=betas, eps</s>
|
bitsandbytes.optim.optimizer/Optimizer1State.update_step
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
d9645465de5212cf65e5a1baeed6f1840ea7913b
|
Add AdEMAMix optimizer (#1360)
|
<34>:<add> 0.0,
<add> 0.0,
|
# module: bitsandbytes.optim.optimizer
class Optimizer1State(Optimizer8bit):
@torch.no_grad()
def update_step(self, group, p, gindex, pindex):
<0> # avoid update error from non-contiguous memory layout
<1> p.data = p.data.contiguous()
<2> p.grad = p.grad.contiguous()
<3>
<4> state = self.state[p]
<5> grad = p.grad
<6>
<7> config = self.get_config(gindex, pindex, group)
<8>
<9> state["step"] += 1
<10> step = state["step"]
<11>
<12> if config["percentile_clipping"] < 100:
<13> current_gnorm, clip_value, gnorm_scale = F.percentile_clipping(
<14> grad,
<15> state["gnorm_vec"],
<16> step,
<17> config["percentile_clipping"],
<18> )
<19> else:
<20> gnorm_scale = 1.0
<21>
<22> if state["state1"].dtype == torch.float:
<23> F.optimizer_update_32bit(
<24> self.optimizer_name,
<25> grad,
<26> p,
<27> state["state1"],
<28> config["betas"][0],
<29> config["eps"],
<30> step,
<31> config["lr"],
<32> None,
<33> config["betas"][1],
<34> config["weight_decay"],
<35> gnorm_scale,
<36> state["unorm_vec"] if config["max_unorm"] > 0.0 else None,
<37> max_unorm=config["max_unorm"],
<38> skip_zeros=config["skip_zeros"],
<39> )
<40>
<41> elif state["state1"].dtype == torch.uint8 and not config["block_wise"]:
<42> F.optimizer_update_8bit(
<43> self.optimizer_name,
<44> grad,
<45> p,
<46> state["state1"],
<47> None,
<48> config["betas"][0],
<49> </s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer1State(Optimizer8bit):
@torch.no_grad()
def update_step(self, group, p, gindex, pindex):
# offset: 1
config["eps"],
step,
config["lr"],
state["qmap1"],
None,
state["max1"],
None,
state["new_max1"],
None,
config["weight_decay"],
gnorm_scale,
state["unorm_vec"] if config["max_unorm"] > 0.0 else None,
max_unorm=config["max_unorm"],
)
state["max1"], state["new_max1"] = state["new_max1"], state["max1"]
elif state["state1"].dtype == torch.uint8 and config["block_wise"]:
F.optimizer_update_8bit_blockwise(
self.optimizer_name,
grad,
p,
state["state1"],
None,
config["betas"][0],
config["betas"][1],
config["eps"],
step,
config["lr"],
state["qmap1"],
None,
state["absmax1"],
None,
config["weight_decay"],
gnorm_scale=gnorm_scale,
skip_zeros=config["skip_zeros"],
)
===========changed ref 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def get_config(self, gindex, pindex, group):
config = {}
config["betas"] = group["betas"]
config["eps"] = group["eps"]
config["weight_decay"] = group["weight_decay"]
config["lr"] = group["lr"]
+ config["alpha"] = group.get("alpha")
+ config["t_alpha"] = group.get("t_alpha")
+ config["t_beta3"] = group.get("t_beta3")
config["optim_bits"] = self.args.optim_bits
config["min_8bit_size"] = self.args.min_8bit_size
config["percentile_clipping"] = self.args.percentile_clipping
config["block_wise"] = self.args.block_wise
config["max_unorm"] = self.args.max_unorm
config["skip_zeros"] = self.args.skip_zeros
if (gindex, pindex) in self.mng.index2config:
config.update(self.mng.index2config[(gindex, pindex)])
return config
===========changed ref 1===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def update_step(self, group, p, gindex, pindex):
# avoid update error from non-contiguous memory layout
p.data = p.data.contiguous()
p.grad = p.grad.contiguous()
state = self.state[p]
grad = p.grad
config = self.get_config(gindex, pindex, group)
state["step"] += 1
step = state["step"]
if config["percentile_clipping"] < 100:
current_gnorm, clip_value, gnorm_scale = F.percentile_clipping(
grad,
state["gnorm_vec"],
step,
config["percentile_clipping"],
)
else:
gnorm_scale = 1.0
if state["state1"].dtype == torch.float:
F.optimizer_update_32bit(
self.optimizer_name,
grad,
p,
state["state1"],
config["betas"][0],
config["eps"],
step,
config["lr"],
state["state2"],
config["betas"][1],
+ config["betas"][2] if len(config["betas"]) >= 3 else 0.0,
+ config["alpha"],
config["weight_decay"],
gnorm_scale,
state["unorm_vec"] if config["max_unorm"] > 0.0 else None,
max_unorm=config["max_unorm"],
skip_zeros=config["skip_zeros"],
)
elif state["state1"].dtype == torch.uint8 and not config["block_wise"]:
F.optimizer_update_8bit(
self.optimizer_name,
grad,
p,
state["state1"],
state["state2"],
config["betas"][0],
config["betas"][</s>
===========changed ref 2===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def update_step(self, group, p, gindex, pindex):
# offset: 1
<s>state1"],
state["state2"],
config["betas"][0],
config["betas"][1],
config["eps"],
step,
config["lr"],
state["qmap1"],
state["qmap2"],
state["max1"],
state["max2"],
state["new_max1"],
state["new_max2"],
config["weight_decay"],
gnorm_scale=gnorm_scale,
unorm_vec=state["unorm_vec"] if config["max_unorm"] > 0.0 else None,
max_unorm=config["max_unorm"],
)
# swap maxes
state["max1"], state["new_max1"] = state["new_max1"], state["max1"]
state["max2"], state["new_max2"] = state["new_max2"], state["max2"]
elif state["state1"].dtype == torch.uint8 and config["block_wise"]:
F.optimizer_update_8bit_blockwise(
self.optimizer_name,
grad,
p,
state["state1"],
state["state2"],
config["betas"][0],
config["betas"][1],
+ config["betas"][2] if len(config["betas"]) >= 3 else 0.0,
+ config["alpha"],
config["eps"],
step,
config["lr"],
state["qmap1"],
state["qmap2"],
state["absmax1"],
state["absmax2"],
config["weight_decay"
|
bitsandbytes.functional/optimizer_update_32bit
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
d9645465de5212cf65e5a1baeed6f1840ea7913b
|
Add AdEMAMix optimizer (#1360)
|
<29>:<add> beta3 : float
<add> Optimizer beta3.
<add> alpha : float
<add> Optimizer alpha.
|
<s>: int,
lr: float,
state2: Optional[torch.Tensor] = None,
beta2: float = 0.0,
+ beta3: float = 0.0,
+ alpha: float = 0.0,
weight_decay: float = 0.0,
gnorm_scale: float = 1.0,
unorm_vec: Optional[torch.Tensor] = None,
max_unorm: float = 0.0,
skip_zeros=False,
) -> None:
<0> """
<1> Performs an inplace optimizer update with one or two optimizer states.
<2>
<3> Universal optimizer update for 32-bit state and 32/16-bit gradients/weights.
<4>
<5> Parameters
<6> ----------
<7> optimizer_name : str
<8> The name of the optimizer: {adam}.
<9> g : torch.Tensor
<10> Gradient tensor.
<11> p : torch.Tensor
<12> Parameter tensor.
<13> state1 : torch.Tensor
<14> Optimizer state 1.
<15> beta1 : float
<16> Optimizer beta1.
<17> eps : float
<18> Optimizer epsilon.
<19> weight_decay : float
<20> Weight decay.
<21> step : int
<22> Current optimizer step.
<23> lr : float
<24> The learning rate.
<25> state2 : torch.Tensor
<26> Optimizer state 2.
<27> beta2 : float
<28> Optimizer beta2.
<29> gnorm_scale : float
<30> The factor to rescale the gradient to the max clip value.
<31> unorm_vec : torch.Tensor
<32> The tensor for the update norm.
<33> max_unorm : float
<34> The maximum update norm relative to the weight norm.
<35> skip_zeros : bool
<36> Whether to skip zero-valued gradients or not (default: False).
<37> """
<38>
<39> param_norm = 0.0
<40> if max_unorm > 0.0:
<41> param_norm = torch.norm(p.data.float())
<42>
<43> optim_func = None
<44> if g.dtype == torch.float32:
<45> optim</s>
|
===========below chunk 0===========
<s> lr: float,
state2: Optional[torch.Tensor] = None,
beta2: float = 0.0,
+ beta3: float = 0.0,
+ alpha: float = 0.0,
weight_decay: float = 0.0,
gnorm_scale: float = 1.0,
unorm_vec: Optional[torch.Tensor] = None,
max_unorm: float = 0.0,
skip_zeros=False,
) -> None:
# offset: 1
elif g.dtype == torch.float16:
optim_func = str2optimizer32bit[optimizer_name][1]
elif g.dtype == torch.bfloat16 and len(str2optimizer32bit[optimizer_name]) == 3:
optim_func = str2optimizer32bit[optimizer_name][2]
else:
raise ValueError(
f"Gradient+optimizer bit data type combination not supported: grad {g.dtype}, optimizer {state1.dtype}",
)
is_on_gpu([g, p, state1, state2, unorm_vec])
prev_device = pre_call(g.device)
optim_func(
get_ptr(g),
get_ptr(p),
get_ptr(state1),
get_ptr(state2),
get_ptr(unorm_vec),
ct.c_float(max_unorm),
ct.c_float(param_norm),
ct.c_float(beta1),
ct.c_float(beta2),
ct.c_float(eps),
ct.c_float(weight_decay),
ct.c_int32(step),
ct.c_float(lr),
ct.c_float(gnorm_scale),
ct.c_bool(skip_zeros),
ct.c_int32(g.numel()),
)
post_call(prev_device)
===========changed ref 0===========
+ # module: bitsandbytes.optim.ademamix
+
+
===========changed ref 1===========
+ # module: bitsandbytes.optim.ademamix
+ class _ReferenceAdEMAMix(torch.optim.Optimizer):
+ """
+ Reference: https://hf.co/papers/2409.03137
+ """
+
===========changed ref 2===========
<s>.Parameter],
+ lr: float = 1e-3,
+ betas: Tuple[float, float, float] = (0.9, 0.999, 0.9999),
+ alpha: float = 5.0,
+ eps: float = 1e-8,
+ weight_decay: float = 1e-2, # default 0.0 or 1e-2?
+ t_beta3: Optional[int] = None,
+ t_alpha: Optional[int] = None,
+ ):
+ defaults = dict(
+ lr=lr, betas=betas, alpha=alpha, eps=eps, weight_decay=weight_decay, t_beta3=t_beta3, t_alpha=t_alpha
+ )
+
+ super().__init__(params, defaults)
+
===========changed ref 3===========
<s>],
+ lr: float = 1e-3,
+ betas: Tuple[float, float, float] = (0.9, 0.999, 0.9999),
+ alpha: float = 5.0,
+ t_alpha: Optional[int] = None,
+ t_beta3: Optional[int] = None,
+ eps: float = 1e-8,
+ weight_decay: float = 1e-2,
+ min_8bit_size: int = 4096,
+ ):
+ super().__init__(
+ params,
+ lr=lr,
+ betas=betas,
+ alpha=alpha,
+ t_alpha=t_alpha,
+ t_beta3=t_beta3,
+ eps=eps,
+ weight_decay=weight_decay,
+ min_8bit_size=min_8bit_size,
+ is_paged=True,
+ )
+
===========changed ref 4===========
<s>],
+ lr: float = 1e-3,
+ betas: Tuple[float, float, float] = (0.9, 0.999, 0.9999),
+ alpha: float = 5.0,
+ t_alpha: Optional[int] = None,
+ t_beta3: Optional[int] = None,
+ eps: float = 1e-8,
+ weight_decay: float = 1e-2,
+ min_8bit_size: int = 4096,
+ ):
+ super().__init__(
+ params,
+ lr=lr,
+ betas=betas,
+ alpha=alpha,
+ t_alpha=t_alpha,
+ t_beta3=t_beta3,
+ eps=eps,
+ weight_decay=weight_decay,
+ min_8bit_size=min_8bit_size,
+ is_paged=True,
+ )
+
===========changed ref 5===========
<s> betas: Tuple[float, float, float] = (0.9, 0.999, 0.9999),
+ alpha: float = 5.0,
+ t_alpha: Optional[int] = None,
+ t_beta3: Optional[int] = None,
+ eps: float = 1e-8,
+ weight_decay: float = 1e-2,
+ optim_bits: Literal[8, 32] = 32,
+ min_8bit_size: int = 4096,
+ ):
+ super().__init__(
+ params,
+ lr=lr,
+ betas=betas,
+ alpha=alpha,
+ t_alpha=t_alpha,
+ t_beta3=t_beta3,
+ eps=eps,
+ weight_decay=weight_decay,
+ optim_bits=optim_bits,
+ min_8bit_size=min_8bit_size,
+ is_paged=True,
+ )
+
===========changed ref 6===========
<s>,
+ betas: Tuple[float, float, float] = (0.9, 0.999, 0.9999),
+ alpha: float = 5.0,
+ t_alpha: Optional[int] = None,
+ t_beta3: Optional[int] = None,
+ eps: float = 1e-8,
+ weight_decay: float = 1e-2,
+ min_8bit_size: int = 4096,
+ is_paged: bool = False,
+ ):
+ super().__init__(
+ params,
+ lr=lr,
+ betas=betas,
+ alpha=alpha,
+ t_alpha=t_alpha,
+ t_beta3=t_beta3,
+ eps=eps,
+ weight_decay=weight_decay,
+ optim_bits=8,
+ min_8bit_size=min_8bit_size,
+ is_paged=is_paged,
+ )
+
===========changed ref 7===========
+ # module: bitsandbytes.optim.ademamix
+ class AdEMAMix(Optimizer2State):
+ def _get_state_double_buffer(self, p, dtype=torch.float32):
+ if not self.is_paged or p.numel() < 1e5:
+ return torch.zeros((2, *p.size()), dtype=dtype, device=p.device)
+ else:
+ buff = F.get_paged(*(2, *p.size()), dtype=dtype, device=p.device)
+ F.fill(buff, 0)
+ self.page_mng.paged_tensors.append(buff)
+ return buff
+
|
bitsandbytes.functional/optimizer_update_8bit_blockwise
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
d9645465de5212cf65e5a1baeed6f1840ea7913b
|
Add AdEMAMix optimizer (#1360)
|
<s> beta1: float,
beta2: float,
+ beta3: float,
+ alpha: float,
eps: float,
step: int,
lr: float,
qmap1: Tensor,
qmap2: Optional[torch.Tensor],
absmax1: Tensor,
absmax2: Optional[torch.Tensor],
weight_decay: float = 0.0,
gnorm_scale: float = 1.0,
skip_zeros=False,
) -> None:
<0> optim_func = None
<1> prev_device = pre_call(g.device)
<2> is_on_gpu([g, p, state1, state2, qmap1, qmap2, absmax1, absmax2])
<3> if g.dtype == torch.float32 and state1.dtype == torch.uint8:
<4> optim_func = str2optimizer8bit_blockwise[optimizer_name][0]
<5> elif g.dtype == torch.float16 and state1.dtype == torch.uint8:
<6> optim_func = str2optimizer8bit_blockwise[optimizer_name][1]
<7> elif (
<8> g.dtype == torch.bfloat16
<9> and state1.dtype == torch.uint8
<10> and len(str2optimizer8bit_blockwise[optimizer_name]) == 3
<11> ):
<12> optim_func = str2optimizer8bit_blockwise[optimizer_name][2]
<13> else:
<14> raise ValueError(
<15> f"Gradient+optimizer bit data type combination not supported: grad {g.dtype}, optimizer {state1.dtype}",
<16> )
<17> post_call(prev_device)
<18>
<19> is_on_gpu([p, g, state1, state2, qmap1, qmap2, absmax1, absmax2])
<20>
<21> prev_device = pre_call(g.device)
<22> optim_func(
<23> get_ptr(p),
<24> get_ptr(g),
<25> get_ptr(state1),
<26> get_ptr(state2),
<27> ct</s>
|
===========below chunk 0===========
<s>,
beta2: float,
+ beta3: float,
+ alpha: float,
eps: float,
step: int,
lr: float,
qmap1: Tensor,
qmap2: Optional[torch.Tensor],
absmax1: Tensor,
absmax2: Optional[torch.Tensor],
weight_decay: float = 0.0,
gnorm_scale: float = 1.0,
skip_zeros=False,
) -> None:
# offset: 1
ct.c_float(beta2),
ct.c_float(eps),
ct.c_int32(step),
ct.c_float(lr),
get_ptr(qmap1),
get_ptr(qmap2),
get_ptr(absmax1),
get_ptr(absmax2),
ct.c_float(weight_decay),
ct.c_float(gnorm_scale),
ct.c_bool(skip_zeros),
ct.c_int32(g.numel()),
)
post_call(prev_device)
===========changed ref 0===========
<s>: int,
lr: float,
state2: Optional[torch.Tensor] = None,
beta2: float = 0.0,
+ beta3: float = 0.0,
+ alpha: float = 0.0,
weight_decay: float = 0.0,
gnorm_scale: float = 1.0,
unorm_vec: Optional[torch.Tensor] = None,
max_unorm: float = 0.0,
skip_zeros=False,
) -> None:
"""
Performs an inplace optimizer update with one or two optimizer states.
Universal optimizer update for 32-bit state and 32/16-bit gradients/weights.
Parameters
----------
optimizer_name : str
The name of the optimizer: {adam}.
g : torch.Tensor
Gradient tensor.
p : torch.Tensor
Parameter tensor.
state1 : torch.Tensor
Optimizer state 1.
beta1 : float
Optimizer beta1.
eps : float
Optimizer epsilon.
weight_decay : float
Weight decay.
step : int
Current optimizer step.
lr : float
The learning rate.
state2 : torch.Tensor
Optimizer state 2.
beta2 : float
Optimizer beta2.
+ beta3 : float
+ Optimizer beta3.
+ alpha : float
+ Optimizer alpha.
gnorm_scale : float
The factor to rescale the gradient to the max clip value.
unorm_vec : torch.Tensor
The tensor for the update norm.
max_unorm : float
The maximum update norm relative to the weight norm.
skip_zeros : bool
Whether to skip zero-valued gradients or not (default: False).
"""
param_norm = 0.0
if max_unorm > 0.0:
param_norm = torch.norm(p.data.float())
optim_func = None
if g.dtype == torch.float32:
optim_func = str2optimizer32bit[optimizer_name][0]
elif</s>
===========changed ref 1===========
<s> lr: float,
state2: Optional[torch.Tensor] = None,
beta2: float = 0.0,
+ beta3: float = 0.0,
+ alpha: float = 0.0,
weight_decay: float = 0.0,
gnorm_scale: float = 1.0,
unorm_vec: Optional[torch.Tensor] = None,
max_unorm: float = 0.0,
skip_zeros=False,
) -> None:
# offset: 1
<s> g.dtype == torch.float32:
optim_func = str2optimizer32bit[optimizer_name][0]
elif g.dtype == torch.float16:
optim_func = str2optimizer32bit[optimizer_name][1]
elif g.dtype == torch.bfloat16 and len(str2optimizer32bit[optimizer_name]) == 3:
optim_func = str2optimizer32bit[optimizer_name][2]
else:
raise ValueError(
f"Gradient+optimizer bit data type combination not supported: grad {g.dtype}, optimizer {state1.dtype}",
)
is_on_gpu([g, p, state1, state2, unorm_vec])
prev_device = pre_call(g.device)
optim_func(
get_ptr(g),
get_ptr(p),
get_ptr(state1),
get_ptr(state2),
get_ptr(unorm_vec),
ct.c_float(max_unorm),
ct.c_float(param_norm),
ct.c_float(beta1),
ct.c_float(beta2),
+ ct.c_float(beta3),
+ ct.c_float(alpha),
ct.c_float(eps),
ct.c_float(weight_decay),
ct.c_int32(step),
ct.c_float(lr),
ct.c</s>
===========changed ref 2===========
<s> lr: float,
state2: Optional[torch.Tensor] = None,
beta2: float = 0.0,
+ beta3: float = 0.0,
+ alpha: float = 0.0,
weight_decay: float = 0.0,
gnorm_scale: float = 1.0,
unorm_vec: Optional[torch.Tensor] = None,
max_unorm: float = 0.0,
skip_zeros=False,
) -> None:
# offset: 2
<s>(gnorm_scale),
ct.c_bool(skip_zeros),
ct.c_int32(g.numel()),
)
post_call(prev_device)
===========changed ref 3===========
+ # module: bitsandbytes.optim.ademamix
+
+
===========changed ref 4===========
+ # module: bitsandbytes.optim.ademamix
+ class _ReferenceAdEMAMix(torch.optim.Optimizer):
+ """
+ Reference: https://hf.co/papers/2409.03137
+ """
+
===========changed ref 5===========
<s>.Parameter],
+ lr: float = 1e-3,
+ betas: Tuple[float, float, float] = (0.9, 0.999, 0.9999),
+ alpha: float = 5.0,
+ eps: float = 1e-8,
+ weight_decay: float = 1e-2, # default 0.0 or 1e-2?
+ t_beta3: Optional[int] = None,
+ t_alpha: Optional[int] = None,
+ ):
+ defaults = dict(
+ lr=lr, betas=betas, alpha=alpha, eps=eps, weight_decay=weight_decay, t_beta3=t_beta3, t_alpha=t_alpha
+ )
+
+ super().__init__(params, defaults)
+
===========changed ref 6===========
<s>],
+ lr: float = 1e-3,
+ betas: Tuple[float, float, float] = (0.9, 0.999, 0.9999),
+ alpha: float = 5.0,
+ t_alpha: Optional[int] = None,
+ t_beta3: Optional[int] = None,
+ eps: float = 1e-8,
+ weight_decay: float = 1e-2,
+ min_8bit_size: int = 4096,
+ ):
+ super().__init__(
+ params,
+ lr=lr,
+ betas=betas,
+ alpha=alpha,
+ t_alpha=t_alpha,
+ t_beta3=t_beta3,
+ eps=eps,
+ weight_decay=weight_decay,
+ min_8bit_size=min_8bit_size,
+ is_paged=True,
+ )
+
|
|
bitsandbytes.optim.optimizer/Optimizer2State.init_state
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
aa57bd891cc856e249316aea22f0e55f4d146de9
|
Change 8bit optimizer blocksize 2048->256; additional bf16 support (#1365)
|
<33>:<add> blocks = n // 256
<del> blocks = n // 2048
<34>:<add> blocks += 1 if n % 256 > 0 else 0
<del> blocks += 1 if n % 2048 >
|
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
<0> config = self.get_config(gindex, pindex, group)
<1>
<2> if config["optim_bits"] == 32:
<3> dtype = torch.float32
<4> elif config["optim_bits"] == 8:
<5> dtype = torch.uint8
<6> else:
<7> raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}')
<8>
<9> if p.numel() < config["min_8bit_size"]:
<10> dtype = torch.float32
<11>
<12> state = self.state[p]
<13> state["step"] = 0
<14>
<15> if dtype == torch.float32:
<16> state["state1"] = self.get_state_buffer(p, dtype=torch.float32)
<17> state["state2"] = self.get_state_buffer(p, dtype=torch.float32)
<18> elif dtype == torch.uint8:
<19> if state["step"] == 0:
<20> if "dynamic" not in self.name2qmap:
<21> self.fill_qmap()
<22> self.name2qmap["dynamic"] = self.name2qmap["dynamic"].to(p.device)
<23> self.name2qmap["udynamic"] = self.name2qmap["udynamic"].to(p.device)
<24>
<25> state["state1"] = self.get_state_buffer(p, dtype=torch.uint8)
<26> state["qmap1"] = self.name2qmap["dynamic"]
<27>
<28> state["state2"] = self.get_state_buffer(p, dtype=torch.uint8)
<29> state["qmap2"] = self.name2qmap["udynamic"]
<30>
<31> if config["block_wise"]:
<32> n = p.numel()
<33> blocks = n // 2048
<34> blocks += 1 if n % 2048 ></s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
# offset: 1
state["absmax1"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
state["absmax2"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
else:
state["max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["new_max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["max2"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["new_max2"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
if config["percentile_clipping"] < 100:
state["gnorm_vec"] = torch.zeros((100,), device=p.device)
if config["max_unorm"] > 0.0:
state["unorm_vec"] = torch.zeros((1,), device=p.device)
===========unchanged ref 0===========
at: bitsandbytes.optim.optimizer.Optimizer8bit
fill_qmap()
get_config(gindex, pindex, group)
init_state(self, group, p, gindex, pindex)
get_state_buffer(p, dtype=torch.float32)
at: bitsandbytes.optim.optimizer.Optimizer8bit.__init__
self.name2qmap = {}
at: torch._C
float32: dtype = ...
uint8: dtype = ...
at: torch._C._VariableFunctions
zeros(*size: _int, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: _size, *, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(*size: _int, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: Sequence[Union[_int, SymInt]], *, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
at: torch.autograd.grad_mode
no_grad()
===========unchanged ref 1===========
at: torch.optim.optimizer.Optimizer.__init__
self.state: DefaultDict[torch.Tensor, Any] = defaultdict(dict)
|
bitsandbytes.optim.optimizer/Optimizer1State.init_state
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
aa57bd891cc856e249316aea22f0e55f4d146de9
|
Change 8bit optimizer blocksize 2048->256; additional bf16 support (#1365)
|
<28>:<add> blocks = n // 256
<del> blocks = n // 2048
<29>:<add> blocks += 1 if n % 256 > 0 else 0
<del> blocks += 1 if n % 2048 > 0 else 0
|
# module: bitsandbytes.optim.optimizer
class Optimizer1State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
<0> config = self.get_config(gindex, pindex, group)
<1>
<2> if config["optim_bits"] == 32:
<3> dtype = torch.float32
<4> elif config["optim_bits"] == 8:
<5> dtype = torch.uint8
<6> else:
<7> raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}')
<8>
<9> if p.numel() < config["min_8bit_size"]:
<10> dtype = torch.float32
<11>
<12> state = self.state[p]
<13> state["step"] = 0
<14>
<15> if dtype == torch.float32:
<16> state["state1"] = self.get_state_buffer(p, dtype=torch.float32)
<17> elif dtype == torch.uint8:
<18> if state["step"] == 0:
<19> if "dynamic" not in self.name2qmap:
<20> self.fill_qmap()
<21> self.name2qmap["dynamic"] = self.name2qmap["dynamic"].to(p.device)
<22>
<23> state["state1"] = self.get_state_buffer(p, dtype=torch.uint8)
<24> state["qmap1"] = self.name2qmap["dynamic"]
<25>
<26> if config["block_wise"]:
<27> n = p.numel()
<28> blocks = n // 2048
<29> blocks += 1 if n % 2048 > 0 else 0
<30>
<31> state["absmax1"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
<32> else:
<33> state["max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
<34> state["new_max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
<35>
<36> </s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer1State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
# offset: 1
state["gnorm_vec"] = torch.zeros((100,), device=p.device)
if config["max_unorm"] > 0.0:
state["unorm_vec"] = torch.zeros((1,), device=p.device)
===========unchanged ref 0===========
at: bitsandbytes.optim.optimizer.Optimizer8bit
fill_qmap()
get_config(gindex, pindex, group)
init_state(self, group, p, gindex, pindex)
get_state_buffer(p, dtype=torch.float32)
at: bitsandbytes.optim.optimizer.Optimizer8bit.__init__
self.name2qmap = {}
at: torch._C
float32: dtype = ...
uint8: dtype = ...
at: torch._C._VariableFunctions
zeros(*size: _int, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: _size, *, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(*size: _int, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: Sequence[Union[_int, SymInt]], *, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
at: torch.autograd.grad_mode
no_grad()
===========unchanged ref 1===========
at: torch.optim.optimizer.Optimizer.__init__
self.state: DefaultDict[torch.Tensor, Any] = defaultdict(dict)
===========changed ref 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
config = self.get_config(gindex, pindex, group)
if config["optim_bits"] == 32:
dtype = torch.float32
elif config["optim_bits"] == 8:
dtype = torch.uint8
else:
raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}')
if p.numel() < config["min_8bit_size"]:
dtype = torch.float32
state = self.state[p]
state["step"] = 0
if dtype == torch.float32:
state["state1"] = self.get_state_buffer(p, dtype=torch.float32)
state["state2"] = self.get_state_buffer(p, dtype=torch.float32)
elif dtype == torch.uint8:
if state["step"] == 0:
if "dynamic" not in self.name2qmap:
self.fill_qmap()
self.name2qmap["dynamic"] = self.name2qmap["dynamic"].to(p.device)
self.name2qmap["udynamic"] = self.name2qmap["udynamic"].to(p.device)
state["state1"] = self.get_state_buffer(p, dtype=torch.uint8)
state["qmap1"] = self.name2qmap["dynamic"]
state["state2"] = self.get_state_buffer(p, dtype=torch.uint8)
state["qmap2"] = self.name2qmap["udynamic"]
if config["block_wise"]:
n = p.numel()
+ blocks = n // 256
- blocks = n // 2048
+ blocks += 1 if n % 256 > 0 else 0
- blocks += 1 if n % 2048 > 0 else 0
state["absmax1</s>
===========changed ref 1===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
# offset: 1
<s> if n % 256 > 0 else 0
- blocks += 1 if n % 2048 > 0 else 0
state["absmax1"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
state["absmax2"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
else:
state["max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["new_max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["max2"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["new_max2"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
if config["percentile_clipping"] < 100:
state["gnorm_vec"] = torch.zeros((100,), device=p.device)
if config["max_unorm"] > 0.0:
state["unorm_vec"] = torch.zeros((1,), device=p.device)
|
bitsandbytes.optim.ademamix/AdEMAMix.init_state
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
aa57bd891cc856e249316aea22f0e55f4d146de9
|
Change 8bit optimizer blocksize 2048->256; additional bf16 support (#1365)
|
<28>:<add> blocks = (n // 256) + bool(n % 256)
<del> blocks = (n // 2048) + bool(n % 2048)
|
# module: bitsandbytes.optim.ademamix
class AdEMAMix(Optimizer2State):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
<0> # In our AdEMAMix implementation, we use `state` to hold
<1> # both the fast and slow EMAs. Here we override the base
<2> # `Optimizer2State` to allocate a buffer twice as large.
<3> # Additional consideration: we do not support block_wise=False,
<4> # percentile clipping, or max_unorm.
<5>
<6> config = self.get_config(gindex, pindex, group)
<7>
<8> if config["optim_bits"] == 32:
<9> dtype = torch.float32
<10> elif config["optim_bits"] == 8:
<11> dtype = torch.uint8
<12> else:
<13> raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}')
<14>
<15> if p.numel() < config["min_8bit_size"]:
<16> dtype = torch.float32
<17>
<18> state = self.state[p]
<19> state["step"] = 0
<20>
<21> if dtype == torch.uint8:
<22> if "dynamic" not in self.name2qmap:
<23> self.fill_qmap()
<24> self.name2qmap["dynamic"] = state["qmap1"] = self.name2qmap["dynamic"].to(p.device)
<25> self.name2qmap["udynamic"] = state["qmap2"] = self.name2qmap["udynamic"].to(p.device)
<26>
<27> n = p.numel()
<28> blocks = (n // 2048) + bool(n % 2048)
<29>
<30> state["absmax1"] = torch.zeros((2, blocks), dtype=torch.float32, device=p.device)
<31> state["absmax2"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
<32>
<33> state["state1"] = self._get_state_double</s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.ademamix
class AdEMAMix(Optimizer2State):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
# offset: 1
state["state2"] = self.get_state_buffer(p, dtype=dtype)
===========unchanged ref 0===========
at: bitsandbytes.optim.optimizer.Optimizer2State
init_state(self, group, p, gindex, pindex)
at: bitsandbytes.optim.optimizer.Optimizer8bit
fill_qmap()
get_config(gindex, pindex, group)
at: bitsandbytes.optim.optimizer.Optimizer8bit.__init__
self.name2qmap = {}
at: torch._C
float32: dtype = ...
uint8: dtype = ...
at: torch._C._VariableFunctions
zeros(*size: _int, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: _size, *, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(*size: _int, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
zeros(size: Sequence[Union[_int, SymInt]], *, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
at: torch.autograd.grad_mode
no_grad()
===========unchanged ref 1===========
at: torch.optim.optimizer.Optimizer.__init__
self.state: DefaultDict[torch.Tensor, Any] = defaultdict(dict)
===========changed ref 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
config = self.get_config(gindex, pindex, group)
if config["optim_bits"] == 32:
dtype = torch.float32
elif config["optim_bits"] == 8:
dtype = torch.uint8
else:
raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}')
if p.numel() < config["min_8bit_size"]:
dtype = torch.float32
state = self.state[p]
state["step"] = 0
if dtype == torch.float32:
state["state1"] = self.get_state_buffer(p, dtype=torch.float32)
state["state2"] = self.get_state_buffer(p, dtype=torch.float32)
elif dtype == torch.uint8:
if state["step"] == 0:
if "dynamic" not in self.name2qmap:
self.fill_qmap()
self.name2qmap["dynamic"] = self.name2qmap["dynamic"].to(p.device)
self.name2qmap["udynamic"] = self.name2qmap["udynamic"].to(p.device)
state["state1"] = self.get_state_buffer(p, dtype=torch.uint8)
state["qmap1"] = self.name2qmap["dynamic"]
state["state2"] = self.get_state_buffer(p, dtype=torch.uint8)
state["qmap2"] = self.name2qmap["udynamic"]
if config["block_wise"]:
n = p.numel()
+ blocks = n // 256
- blocks = n // 2048
+ blocks += 1 if n % 256 > 0 else 0
- blocks += 1 if n % 2048 > 0 else 0
state["absmax1</s>
===========changed ref 1===========
# module: bitsandbytes.optim.optimizer
class Optimizer2State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
# offset: 1
<s> if n % 256 > 0 else 0
- blocks += 1 if n % 2048 > 0 else 0
state["absmax1"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
state["absmax2"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
else:
state["max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["new_max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["max2"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["new_max2"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
if config["percentile_clipping"] < 100:
state["gnorm_vec"] = torch.zeros((100,), device=p.device)
if config["max_unorm"] > 0.0:
state["unorm_vec"] = torch.zeros((1,), device=p.device)
===========changed ref 2===========
# module: bitsandbytes.optim.optimizer
class Optimizer1State(Optimizer8bit):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
config = self.get_config(gindex, pindex, group)
if config["optim_bits"] == 32:
dtype = torch.float32
elif config["optim_bits"] == 8:
dtype = torch.uint8
else:
raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}')
if p.numel() < config["min_8bit_size"]:
dtype = torch.float32
state = self.state[p]
state["step"] = 0
if dtype == torch.float32:
state["state1"] = self.get_state_buffer(p, dtype=torch.float32)
elif dtype == torch.uint8:
if state["step"] == 0:
if "dynamic" not in self.name2qmap:
self.fill_qmap()
self.name2qmap["dynamic"] = self.name2qmap["dynamic"].to(p.device)
state["state1"] = self.get_state_buffer(p, dtype=torch.uint8)
state["qmap1"] = self.name2qmap["dynamic"]
if config["block_wise"]:
n = p.numel()
+ blocks = n // 256
- blocks = n // 2048
+ blocks += 1 if n % 256 > 0 else 0
- blocks += 1 if n % 2048 > 0 else 0
state["absmax1"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
else:
state["max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
state["new_max1"] = torch.zeros((1,), dtype=torch.float32, device=p.device)
if config["percentile_clipping"] < 100:
</s>
|
bitsandbytes.functional/create_dynamic_map
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
aa57bd891cc856e249316aea22f0e55f4d146de9
|
Change 8bit optimizer blocksize 2048->256; additional bf16 support (#1365)
|
# module: bitsandbytes.functional
def create_dynamic_map(signed=True, max_exponent_bits=7, total_bits=8):
<0> """
<1> Creates the dynamic quantiztion map.
<2>
<3> The dynamic data type is made up of a dynamic exponent and
<4> fraction. As the exponent increase from 0 to -7 the number
<5> of bits available for the fraction shrinks.
<6>
<7> This is a generalization of the dynamic type where a certain
<8> number of the bits and be reserved for the linear quantization
<9> region (the fraction). n determines the maximum number of
<10> exponent bits.
<11>
<12> For more details see
<13> (8-Bit Approximations for Parallelism in Deep Learning)[https://arxiv.org/abs/1511.04561]
<14> """
<15>
<16> data = []
<17> # these are additional items that come from the case
<18> # where all the exponent bits are zero and no
<19> # indicator bit is present
<20> non_sign_bits = total_bits - (1 if signed else 1)
<21> additional_items = 2 ** (non_sign_bits - max_exponent_bits) - 1
<22> for i in range(max_exponent_bits):
<23> fraction_items = int(
<24> 2 ** (i + non_sign_bits - max_exponent_bits) + 1
<25> if signed
<26> else 2 ** (i + non_sign_bits - max_exponent_bits + 1) + 1,
<27> )
<28> boundaries = torch.linspace(0.1, 1, fraction_items)
<29> means = (boundaries[:-1] + boundaries[1:]) / 2.0
<30> data += ((10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
<31> if signed:
<32> data += (-(10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
<33>
<34> if additional_items > 0:
<35> boundaries = torch.linspace(0.1, 1, additional_items + 1)
<36> means = (boundaries[:-1]</s>
|
===========below chunk 0===========
# module: bitsandbytes.functional
def create_dynamic_map(signed=True, max_exponent_bits=7, total_bits=8):
# offset: 1
data += ((10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
if signed:
data += (-(10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
data.append(0)
data.append(1.0)
assert len(data) == 2**total_bits
gap = 256 - len(data)
for i in range(gap):
data.append(0)
data.sort()
return Tensor(data)
===========unchanged ref 0===========
at: bitsandbytes.functional.create_fp8_map
code /= code.max()
at: torch._C._VariableFunctions
linspace(start: Number, end: Number, steps: Optional[_int]=None, *, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, device: Device=None, requires_grad: _bool=False) -> Tensor
linspace(start: Union[Number, _complex], end: Union[Number, _complex], steps: _int, *, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
===========changed ref 0===========
# module: bitsandbytes.functional
name2qmap = {}
if lib and lib.compiled_with_cuda:
"""C FUNCTIONS FOR OPTIMIZERS"""
str2optimizer32bit = {
"adam": (
lib.cadam32bit_grad_fp32,
lib.cadam32bit_grad_fp16,
lib.cadam32bit_grad_bf16,
),
"momentum": (
lib.cmomentum32bit_grad_32,
lib.cmomentum32bit_grad_16,
),
"rmsprop": (
lib.crmsprop32bit_grad_32,
lib.crmsprop32bit_grad_16,
),
"lion": (
lib.clion32bit_grad_fp32,
lib.clion32bit_grad_fp16,
lib.clion32bit_grad_bf16,
),
"adagrad": (
lib.cadagrad32bit_grad_32,
lib.cadagrad32bit_grad_16,
),
"lamb": (
lib.cadam32bit_grad_fp32,
lib.cadam32bit_grad_fp16,
+ lib.cadam32bit_grad_bf16,
),
"ademamix": (
lib.cademamix32bit_grad_fp32,
lib.cademamix32bit_grad_fp16,
lib.cademamix32bit_grad_bf16,
),
}
str2optimizer8bit = {
"adam": (
lib.cadam_static_8bit_grad_32,
lib.cadam_static_8bit_grad_16,
),
"momentum": (
lib.cmomentum_static_8bit_grad_32,
lib.cmomentum_static_8bit_grad_16,
),
"rmsprop": (
lib</s>
===========changed ref 1===========
# module: bitsandbytes.functional
# offset: 1
<s> lib.cmomentum_static_8bit_grad_16,
),
"rmsprop": (
lib.crmsprop_static_8bit_grad_32,
lib.crmsprop_static_8bit_grad_16,
),
"lion": (
lib.clion_static_8bit_grad_32,
lib.clion_static_8bit_grad_16,
),
"lamb": (
lib.cadam_static_8bit_grad_32,
lib.cadam_static_8bit_grad_16,
),
"lars": (
lib.cmomentum_static_8bit_grad_32,
lib.cmomentum_static_8bit_grad_16,
),
}
str2optimizer8bit_blockwise = {
"adam": (
lib.cadam_8bit_blockwise_grad_fp32,
lib.cadam_8bit_blockwise_grad_fp16,
lib.cadam_8bit_blockwise_grad_bf16,
),
"momentum": (
lib.cmomentum_8bit_blockwise_grad_fp32,
lib.cmomentum_8bit_blockwise_grad_fp16,
+ lib.cmomentum_8bit_blockwise_grad_bf16,
),
"rmsprop": (
lib.crmsprop_8bit_blockwise_grad_fp32,
lib.crmsprop_8bit_blockwise_grad_fp16,
+ lib.crmsprop_8bit_blockwise_grad_bf16,
),
"lion": (
lib.clion_8bit_blockwise_grad_fp32,
lib.clion_8bit_blockwise_grad_fp16,</s>
===========changed ref 2===========
# module: bitsandbytes.functional
# offset: 2
<s> lib.clion_8bit_blockwise_grad_bf16,
),
"adagrad": (
lib.cadagrad_8bit_blockwise_grad_fp32,
lib.cadagrad_8bit_blockwise_grad_fp16,
+ lib.cadagrad_8bit_blockwise_grad_bf16,
),
"ademamix": (
lib.cademamix_8bit_blockwise_grad_fp32,
lib.cademamix_8bit_blockwise_grad_fp16,
lib.cademamix_8bit_blockwise_grad_bf16,
),
}
|
|
tests.test_optim/test_benchmark_blockwise
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
aa57bd891cc856e249316aea22f0e55f4d146de9
|
Change 8bit optimizer blocksize 2048->256; additional bf16 support (#1365)
|
<8>:<add> total_steps = 500
<add> for i in range(total_steps):
<del> for i in range(k):
<9>:<add> if i == total_steps // 5:
<del> if i == k // 5:
<19>:<add> params = (total_steps - total_steps // 5) * dim1 * dim2
<del> params = (k - k // 5) * dim1 * dim2
<20>:<add> print(optim_name, gtype, s, params, s / params)
<del> print(optim_name, gtype, s / params)
|
<s>etrize("gtype", [torch.float32, torch.bfloat16, torch.float16], ids=describe_dtype)
- @pytest.mark.parametrize("gtype", [torch.float32, torch.float16], ids=describe_dtype)
@pytest.mark.parametrize("optim_name", optimizer_names_benchmark, ids=id_formatter("opt"))
@pytest.mark.benchmark
def test_benchmark_blockwise(dim1, dim2, gtype, optim_name):
<0> if dim1 == 1 and dim2 == 1:
<1> return
<2> p1 = torch.randn(dim1, dim2, device="cuda", dtype=gtype) * 0.1
<3>
<4> bnb_optimizer = str2optimizers[optim_name][1]([p1])
<5>
<6> g = torch.randn(dim1, dim2, device="cuda", dtype=gtype) * 0.01
<7> p1.grad = g
<8> for i in range(k):
<9> if i == k // 5:
<10> # 100 iterations for burn-in
<11> torch.cuda.synchronize()
<12> t0 = time.time()
<13>
<14> bnb_optimizer.step()
<15>
<16> torch.cuda.synchronize()
<17> s = time.time() - t0
<18> print("")
<19> params = (k - k // 5) * dim1 * dim2
<20> print(optim_name, gtype, s / params)
<21>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: _pytest.mark.structures.MarkGenerator
skip: _SkipMarkDecorator
skipif: _SkipifMarkDecorator
xfail: _XfailMarkDecorator
parametrize: _ParametrizeMarkDecorator
usefixtures: _UsefixturesMarkDecorator
filterwarnings: _FilterwarningsMarkDecorator
at: tests.helpers
id_formatter(label: str)
describe_dtype(dtype: torch.dtype) -> str
at: tests.test_optim
str2optimizers["rmsprop8bit_blockwise"] = (
lambda pxx: torch.optim.RMSprop(pxx, 0.01, 0.9),
lambda pxx: bnb.optim.RMSprop8bit(pxx, 0.01, 0.9, block_wise=True),
)
optimizer_names_benchmark = [
"adam8bit_blockwise",
"paged_adam8bit_blockwise",
"ademamix8bit_blockwise",
"paged_ademamix8bit_blockwise",
"ademamix8bit_blockwise_scheduled",
"paged_ademamix8bit_blockwise_scheduled",
"lion8bit_blockwise",
"paged_lion8bit_blockwise",
"paged_ademamix8bit_blockwise",
]
at: torch._C
float32: dtype = ...
float16: dtype = ...
bfloat16: dtype = ...
===========unchanged ref 1===========
at: torch._C._VariableFunctions
randn(size: Sequence[Union[_int, SymInt]], *, generator: Optional[Generator], out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
randn(*size: _int, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
randn(*size: _int, out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
randn(size: Sequence[Union[_int, SymInt]], *, generator: Optional[Generator], names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
randn(*size: _int, generator: Optional[Generator], out: Optional[Tensor]=None, dtype: Optional[_dtype]=None, layout: Optional[_layout]=None, device: Optional[Union[_device, str, None]]=None, pin_memory: Optional[_bool]=False, requires_grad: Optional[_bool]=False) -> Tensor
randn(size: Sequence[Union[_int, SymInt]], *, names: Optional[Sequence[Union[str, ellipsis, None]]], dtype: Optional[_dtype]=None, layout: Optional</s>
===========changed ref 0===========
# module: tests.test_optim
optimizer_names_benchmark = [
"adam8bit_blockwise",
"paged_adam8bit_blockwise",
+ "ademamix8bit_blockwise",
+ "paged_ademamix8bit_blockwise",
- "paged_adamw8bit_blockwise",
+ "ademamix8bit_blockwise_scheduled",
+ "paged_ademamix8bit_blockwise_scheduled",
+ "lion8bit_blockwise",
"paged_lion8bit_blockwise",
"paged_ademamix8bit_blockwise",
]
===========changed ref 1===========
# module: bitsandbytes.optim.ademamix
class AdEMAMix(Optimizer2State):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
# In our AdEMAMix implementation, we use `state` to hold
# both the fast and slow EMAs. Here we override the base
# `Optimizer2State` to allocate a buffer twice as large.
# Additional consideration: we do not support block_wise=False,
# percentile clipping, or max_unorm.
config = self.get_config(gindex, pindex, group)
if config["optim_bits"] == 32:
dtype = torch.float32
elif config["optim_bits"] == 8:
dtype = torch.uint8
else:
raise NotImplementedError(f'Amount of optimizer bits not supported: {config["optim_bits"]}')
if p.numel() < config["min_8bit_size"]:
dtype = torch.float32
state = self.state[p]
state["step"] = 0
if dtype == torch.uint8:
if "dynamic" not in self.name2qmap:
self.fill_qmap()
self.name2qmap["dynamic"] = state["qmap1"] = self.name2qmap["dynamic"].to(p.device)
self.name2qmap["udynamic"] = state["qmap2"] = self.name2qmap["udynamic"].to(p.device)
n = p.numel()
+ blocks = (n // 256) + bool(n % 256)
- blocks = (n // 2048) + bool(n % 2048)
state["absmax1"] = torch.zeros((2, blocks), dtype=torch.float32, device=p.device)
state["absmax2"] = torch.zeros((blocks,), dtype=torch.float32, device=p.device)
state["state1"] = self._get_state_double_buffer(p, dtype=dtype)
state["state2"]</s>
===========changed ref 2===========
# module: bitsandbytes.optim.ademamix
class AdEMAMix(Optimizer2State):
@torch.no_grad()
def init_state(self, group, p, gindex, pindex):
# offset: 1
<s> state["state1"] = self._get_state_double_buffer(p, dtype=dtype)
state["state2"] = self.get_state_buffer(p, dtype=dtype)
|
bitsandbytes.optim.optimizer/Optimizer8bit.load_state_dict
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
51294d909e914f80d2f2c85f9e9229dd4386ef85
|
Fix optimizer support for Python <= 3.9 (#1379)
|
<18>:<add> if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens)):
<del> if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens, strict=True)):
<29>:<del> strict=True,
|
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def load_state_dict(self, state_dict, move_to_device=True):
<0> """Load an optimizer state.
<1>
<2> Arguments:
<3> state_dict (`dict`):
<4> An optimizer state (should be returned from a call to `state_dict`) to load.
<5> move_to_device (`bool`, defaults to `True`):
<6> Whether to move the optimizer's state to the device.
<7> """
<8> # deepcopy, to be consistent with module API
<9> state_dict = deepcopy(state_dict)
<10> # Validate the state_dict
<11> groups = self.param_groups
<12> saved_groups = state_dict["param_groups"]
<13>
<14> if len(groups) != len(saved_groups):
<15> raise ValueError("loaded state dict has a different number of parameter groups")
<16> param_lens = (len(g["params"]) for g in groups)
<17> saved_lens = (len(g["params"]) for g in saved_groups)
<18> if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens, strict=True)):
<19> raise ValueError(
<20> "loaded state dict contains a parameter group that doesn't match the size of optimizer's group",
<21> )
<22>
<23> # Update the state
<24> id_map = {
<25> old_id: p
<26> for old_id, p in zip(
<27> chain.from_iterable(g["params"] for g in saved_groups),
<28> chain.from_iterable(g["params"] for g in groups),
<29> strict=True,
<30> )
<31> }
<32>
<33> def cast(param, value):
<34> r"""Make a deep copy of value, casting all tensors to device of param."""
<35> if isinstance(value, torch.Tensor):
<36> # Floating-point types are a bit special here. They are the only ones
<37> # that are assumed to always match the type of params.
<38> if param.is_</s>
|
===========below chunk 0===========
# module: bitsandbytes.optim.optimizer
class Optimizer8bit(torch.optim.Optimizer):
def load_state_dict(self, state_dict, move_to_device=True):
# offset: 1
value = value.to(param.dtype)
return value
elif isinstance(value, dict):
for k, v in value.items():
if k in self.non_castable_tensor_keys:
if move_to_device:
value[k] = v.to(param.device)
else:
value[k] = cast(param, v)
return value
elif isinstance(value, container_abcs.Iterable):
return type(value)(cast(param, v) for v in value)
else:
return value
# Copy state assigned to params (and cast tensors to appropriate types).
# State that is not assigned to params is copied as is (needed for
# backward compatibility).
state = defaultdict(dict)
for k, v in state_dict["state"].items():
if k in id_map:
param = id_map[k]
state[param] = cast(param, v)
else:
state[k] = v
# Update parameter groups, setting their 'params' value
def update_group(group, new_group):
new_group["params"] = group["params"]
return new_group
param_groups = [update_group(g, ng) for g, ng in zip(groups, saved_groups, strict=True)]
self.__setstate__({"state": state, "param_groups": param_groups})
|
setup/read
|
Modified
|
bitsandbytes-foundation~bitsandbytes
|
9264f02d6c39245136074f28f100e32304f89d2c
|
Fix Windows build.
|
<0>:<add> return open(os.path.join(os.path.dirname(__file__), fname), encoding="utf8").read()
<del> return open(os.path.join(os.path.dirname(__file__), fname)).read()
|
# module: setup
def read(fname):
<0> return open(os.path.join(os.path.dirname(__file__), fname)).read()
<1>
|
===========unchanged ref 0===========
at: io.BufferedRandom
read(self, size: Optional[int]=..., /) -> bytes
at: os.path
join(a: StrPath, *paths: StrPath) -> str
join(a: BytesPath, *paths: BytesPath) -> bytes
dirname(p: _PathLike[AnyStr]) -> AnyStr
dirname(p: AnyStr) -> AnyStr
at: typing.IO
__slots__ = ()
read(n: int=...) -> AnyStr
|
backend.external.github_api.user/get_user
|
Modified
|
avgupta456~github-trends
|
c4299f28eb7553daebb14f9b51af0b145d2749bf
|
started repo functions
|
<3>:<add> r = s.get(BASE_URL + user_id)
<del> r = s.get(BASE_URL + "users/" + user_id)
<4>:<del> data = r.json()
<5>:<del> return data
<6>:<add> return r.json()
|
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
<0> """
<1> Returns raw user data
<2> """
<3> r = s.get(BASE_URL + "users/" + user_id)
<4> data = r.json()
<5> return data
<6>
|
===========unchanged ref 0===========
at: backend.external.github_api.user
s = requests.session()
BASE_URL = "https://api.github.com/users/"
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
get(url: Union[Text, bytes], **kwargs) -> Response
===========changed ref 0===========
# module: backend.external.github_api.user
s = requests.session()
+ BASE_URL = "https://api.github.com/users/"
- BASE_URL = "https://api.github.com/"
|
backend.external.github_api.user/get_user_followers
|
Modified
|
avgupta456~github-trends
|
c4299f28eb7553daebb14f9b51af0b145d2749bf
|
started repo functions
|
<3>:<add> r = s.get(BASE_URL + user_id + "/followers")
<del> r = s.get(BASE_URL + "users/" + user_id + "/followers")
<4>:<del> data = r.json()
<5>:<del> return data
<6>:<add> return r.json()
|
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
<0> """
<1> Returns list of followers
<2> """
<3> r = s.get(BASE_URL + "users/" + user_id + "/followers")
<4> data = r.json()
<5> return data
<6>
|
===========unchanged ref 0===========
at: backend.external.github_api.user
s = requests.session()
BASE_URL = "https://api.github.com/users/"
at: requests.models.Response
json(**kwargs) -> Any
at: requests.sessions.Session
get(url: Union[Text, bytes], **kwargs) -> Response
===========changed ref 0===========
# module: backend.external.github_api.user
s = requests.session()
+ BASE_URL = "https://api.github.com/users/"
- BASE_URL = "https://api.github.com/"
===========changed ref 1===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
"""
Returns raw user data
"""
+ r = s.get(BASE_URL + user_id)
- r = s.get(BASE_URL + "users/" + user_id)
- data = r.json()
- return data
+ return r.json()
|
backend.external.github_api.user/get_user_following
|
Modified
|
avgupta456~github-trends
|
c4299f28eb7553daebb14f9b51af0b145d2749bf
|
started repo functions
|
<0>:<del> """
<1>:<add> """Returns list of following"""
<del> Returns list of following
<2>:<del> """
<3>:<add> r = s.get(BASE_URL + user_id + "/following")
<del> r = s.get(BASE_URL + "users/" + user_id + "/following")
<4>:<del> data = r.json()
<5>:<del> return data
<6>:<add> return r.json()
|
# module: backend.external.github_api.user
def get_user_following(user_id: str) -> dict:
<0> """
<1> Returns list of following
<2> """
<3> r = s.get(BASE_URL + "users/" + user_id + "/following")
<4> data = r.json()
<5> return data
<6>
|
===========unchanged ref 0===========
at: backend.external.github_api.user
s = requests.session()
BASE_URL = "https://api.github.com/users/"
at: requests.models.Response
json(**kwargs) -> Any
at: requests.sessions.Session
get(url: Union[Text, bytes], **kwargs) -> Response
===========changed ref 0===========
# module: backend.external.github_api.user
s = requests.session()
+ BASE_URL = "https://api.github.com/users/"
- BASE_URL = "https://api.github.com/"
===========changed ref 1===========
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
"""
Returns list of followers
"""
+ r = s.get(BASE_URL + user_id + "/followers")
- r = s.get(BASE_URL + "users/" + user_id + "/followers")
- data = r.json()
- return data
+ return r.json()
===========changed ref 2===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
"""
Returns raw user data
"""
+ r = s.get(BASE_URL + user_id)
- r = s.get(BASE_URL + "users/" + user_id)
- data = r.json()
- return data
+ return r.json()
|
backend.external.github_api.user/get_user_starred_repos
|
Modified
|
avgupta456~github-trends
|
c4299f28eb7553daebb14f9b51af0b145d2749bf
|
started repo functions
|
<0>:<del> """
<1>:<add> """Returns list of starred repos"""
<del> Returns list of starred repos
<2>:<del> """
<3>:<add> r = s.get(BASE_URL + user_id + "/starred")
<del> r = s.get(BASE_URL + "users/" + user_id + "/starred")
<4>:<del> data = r.json()
<5>:<del> return data
<6>:<add> return r.json()
|
# module: backend.external.github_api.user
def get_user_starred_repos(user_id: str) -> dict:
<0> """
<1> Returns list of starred repos
<2> """
<3> r = s.get(BASE_URL + "users/" + user_id + "/starred")
<4> data = r.json()
<5> return data
<6>
|
===========unchanged ref 0===========
at: backend.external.github_api.user
s = requests.session()
BASE_URL = "https://api.github.com/users/"
at: requests.models.Response
json(**kwargs) -> Any
at: requests.sessions.Session
get(url: Union[Text, bytes], **kwargs) -> Response
===========changed ref 0===========
# module: backend.external.github_api.user
s = requests.session()
+ BASE_URL = "https://api.github.com/users/"
- BASE_URL = "https://api.github.com/"
===========changed ref 1===========
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
"""
Returns list of followers
"""
+ r = s.get(BASE_URL + user_id + "/followers")
- r = s.get(BASE_URL + "users/" + user_id + "/followers")
- data = r.json()
- return data
+ return r.json()
===========changed ref 2===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
"""
Returns raw user data
"""
+ r = s.get(BASE_URL + user_id)
- r = s.get(BASE_URL + "users/" + user_id)
- data = r.json()
- return data
+ return r.json()
===========changed ref 3===========
# module: backend.external.github_api.user
def get_user_following(user_id: str) -> dict:
- """
+ """Returns list of following"""
- Returns list of following
- """
+ r = s.get(BASE_URL + user_id + "/following")
- r = s.get(BASE_URL + "users/" + user_id + "/following")
- data = r.json()
- return data
+ return r.json()
|
backend.external.github_api.user/get_user_orgs
|
Modified
|
avgupta456~github-trends
|
c4299f28eb7553daebb14f9b51af0b145d2749bf
|
started repo functions
|
<0>:<del> """
<1>:<add> """Returns list of user organizations"""
<del> Returns list of user organizations
<2>:<del> """
<3>:<add> r = s.get(BASE_URL + user_id + "/orgs")
<del> r = s.get(BASE_URL + "users/" + user_id + "/orgs")
<4>:<del> data = r.json()
<5>:<del> return data
<6>:<add> return r.json()
|
# module: backend.external.github_api.user
def get_user_orgs(user_id: str) -> dict:
<0> """
<1> Returns list of user organizations
<2> """
<3> r = s.get(BASE_URL + "users/" + user_id + "/orgs")
<4> data = r.json()
<5> return data
<6>
|
===========unchanged ref 0===========
at: backend.external.github_api.user
s = requests.session()
BASE_URL = "https://api.github.com/users/"
at: requests.models.Response
json(**kwargs) -> Any
at: requests.sessions.Session
get(url: Union[Text, bytes], **kwargs) -> Response
===========changed ref 0===========
# module: backend.external.github_api.user
s = requests.session()
+ BASE_URL = "https://api.github.com/users/"
- BASE_URL = "https://api.github.com/"
===========changed ref 1===========
# module: backend.external.github_api.user
def get_user_starred_repos(user_id: str) -> dict:
- """
+ """Returns list of starred repos"""
- Returns list of starred repos
- """
+ r = s.get(BASE_URL + user_id + "/starred")
- r = s.get(BASE_URL + "users/" + user_id + "/starred")
- data = r.json()
- return data
+ return r.json()
===========changed ref 2===========
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
"""
Returns list of followers
"""
+ r = s.get(BASE_URL + user_id + "/followers")
- r = s.get(BASE_URL + "users/" + user_id + "/followers")
- data = r.json()
- return data
+ return r.json()
===========changed ref 3===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
"""
Returns raw user data
"""
+ r = s.get(BASE_URL + user_id)
- r = s.get(BASE_URL + "users/" + user_id)
- data = r.json()
- return data
+ return r.json()
===========changed ref 4===========
# module: backend.external.github_api.user
def get_user_following(user_id: str) -> dict:
- """
+ """Returns list of following"""
- Returns list of following
- """
+ r = s.get(BASE_URL + user_id + "/following")
- r = s.get(BASE_URL + "users/" + user_id + "/following")
- data = r.json()
- return data
+ return r.json()
|
backend.external.github_api.user/get_user_repos
|
Modified
|
avgupta456~github-trends
|
c4299f28eb7553daebb14f9b51af0b145d2749bf
|
started repo functions
|
<0>:<del> """
<1>:<add> """Returns list of user repositories"""
<del> Returns list of user repositories
<2>:<del> """
<3>:<add> r = s.get(BASE_URL + user_id + "/repos")
<del> r = s.get(BASE_URL + "users/" + user_id + "/repos")
<4>:<del> data = r.json()
<5>:<del> return data
<6>:<add> return r.json()
|
# module: backend.external.github_api.user
def get_user_repos(user_id: str) -> dict:
<0> """
<1> Returns list of user repositories
<2> """
<3> r = s.get(BASE_URL + "users/" + user_id + "/repos")
<4> data = r.json()
<5> return data
<6>
|
===========changed ref 0===========
# module: backend.external.github_api.user
s = requests.session()
+ BASE_URL = "https://api.github.com/users/"
- BASE_URL = "https://api.github.com/"
===========changed ref 1===========
# module: backend.external.github_api.user
def get_user_orgs(user_id: str) -> dict:
- """
+ """Returns list of user organizations"""
- Returns list of user organizations
- """
+ r = s.get(BASE_URL + user_id + "/orgs")
- r = s.get(BASE_URL + "users/" + user_id + "/orgs")
- data = r.json()
- return data
+ return r.json()
===========changed ref 2===========
# module: backend.external.github_api.user
def get_user_starred_repos(user_id: str) -> dict:
- """
+ """Returns list of starred repos"""
- Returns list of starred repos
- """
+ r = s.get(BASE_URL + user_id + "/starred")
- r = s.get(BASE_URL + "users/" + user_id + "/starred")
- data = r.json()
- return data
+ return r.json()
===========changed ref 3===========
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
"""
Returns list of followers
"""
+ r = s.get(BASE_URL + user_id + "/followers")
- r = s.get(BASE_URL + "users/" + user_id + "/followers")
- data = r.json()
- return data
+ return r.json()
===========changed ref 4===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
"""
Returns raw user data
"""
+ r = s.get(BASE_URL + user_id)
- r = s.get(BASE_URL + "users/" + user_id)
- data = r.json()
- return data
+ return r.json()
===========changed ref 5===========
# module: backend.external.github_api.user
def get_user_following(user_id: str) -> dict:
- """
+ """Returns list of following"""
- Returns list of following
- """
+ r = s.get(BASE_URL + user_id + "/following")
- r = s.get(BASE_URL + "users/" + user_id + "/following")
- data = r.json()
- return data
+ return r.json()
|
backend.external.github_api.user/get_user
|
Modified
|
avgupta456~github-trends
|
32af92e58d1ca52b19aa2de6db4bf6e8aa944211
|
use get_template
|
<0>:<del> """
<1>:<add> """Returns raw user data"""
<del> Returns raw user data
<2>:<del> """
<3>:<add> return get_template(BASE_URL + user_id)
<del> r = s.get(BASE_URL + user_id)
<4>:<del> return r.json()
|
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
<0> """
<1> Returns raw user data
<2> """
<3> r = s.get(BASE_URL + user_id)
<4> return r.json()
<5>
|
===========unchanged ref 0===========
at: backend.external.github_api.user
BASE_URL = "https://api.github.com/users/"
at: external.github_api.template
get_template(query: str, plural: Optional[bool]=False, per_page: Optional[str]="100", accept_header: Optional[str]="application/vnd.github.v3+json") -> dict
===========changed ref 0===========
# module: backend.external.github_api.user
- s = requests.session()
-
BASE_URL = "https://api.github.com/users/"
|
backend.external.github_api.user/get_user_followers
|
Modified
|
avgupta456~github-trends
|
32af92e58d1ca52b19aa2de6db4bf6e8aa944211
|
use get_template
|
<0>:<del> """
<1>:<add> """Returns list of followers"""
<del> Returns list of followers
<2>:<del> """
<3>:<del> r = s.get(BASE_URL + user_id + "/followers")
<4>:<del> return r.json()
<5>:<add> return get_template(BASE_URL + user_id + "/followers", plural=True)
|
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
<0> """
<1> Returns list of followers
<2> """
<3> r = s.get(BASE_URL + user_id + "/followers")
<4> return r.json()
<5>
|
===========unchanged ref 0===========
at: backend.external.github_api.user
BASE_URL = "https://api.github.com/users/"
at: external.github_api.template
get_template(query: str, plural: Optional[bool]=False, per_page: Optional[str]="100", accept_header: Optional[str]="application/vnd.github.v3+json") -> dict
===========changed ref 0===========
# module: backend.external.github_api.user
- s = requests.session()
-
BASE_URL = "https://api.github.com/users/"
===========changed ref 1===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
- """
+ """Returns raw user data"""
- Returns raw user data
- """
+ return get_template(BASE_URL + user_id)
- r = s.get(BASE_URL + user_id)
- return r.json()
|
backend.external.github_api.user/get_user_following
|
Modified
|
avgupta456~github-trends
|
32af92e58d1ca52b19aa2de6db4bf6e8aa944211
|
use get_template
|
<1>:<del> r = s.get(BASE_URL + user_id + "/following")
<2>:<del> return r.json()
<3>:<add> return get_template(BASE_URL + user_id + "/following", plural=True)
|
# module: backend.external.github_api.user
def get_user_following(user_id: str) -> dict:
<0> """Returns list of following"""
<1> r = s.get(BASE_URL + user_id + "/following")
<2> return r.json()
<3>
|
===========unchanged ref 0===========
at: backend.external.github_api.user
BASE_URL = "https://api.github.com/users/"
at: external.github_api.template
get_template(query: str, plural: Optional[bool]=False, per_page: Optional[str]="100", accept_header: Optional[str]="application/vnd.github.v3+json") -> dict
===========changed ref 0===========
# module: backend.external.github_api.user
- s = requests.session()
-
BASE_URL = "https://api.github.com/users/"
===========changed ref 1===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
- """
+ """Returns raw user data"""
- Returns raw user data
- """
+ return get_template(BASE_URL + user_id)
- r = s.get(BASE_URL + user_id)
- return r.json()
===========changed ref 2===========
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
- """
+ """Returns list of followers"""
- Returns list of followers
- """
- r = s.get(BASE_URL + user_id + "/followers")
- return r.json()
+ return get_template(BASE_URL + user_id + "/followers", plural=True)
|
backend.external.github_api.user/get_user_starred_repos
|
Modified
|
avgupta456~github-trends
|
32af92e58d1ca52b19aa2de6db4bf6e8aa944211
|
use get_template
|
<1>:<add> return get_template(
<add> BASE_URL + user_id + "/starred",
<del> r = s.get(BASE_URL + user_id + "/starred")
<2>:<add> plural=True,
<add> per_page=per_page,
<add> accept_header="application/vnd.github.v3.star+json",
<add> )
<del> return r.json()
|
# module: backend.external.github_api.user
+ def get_user_starred_repos(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_starred_repos(user_id: str) -> dict:
<0> """Returns list of starred repos"""
<1> r = s.get(BASE_URL + user_id + "/starred")
<2> return r.json()
<3>
|
===========changed ref 0===========
# module: backend.external.github_api.user
- s = requests.session()
-
BASE_URL = "https://api.github.com/users/"
===========changed ref 1===========
# module: backend.external.github_api.user
def get_user_following(user_id: str) -> dict:
"""Returns list of following"""
- r = s.get(BASE_URL + user_id + "/following")
- return r.json()
+ return get_template(BASE_URL + user_id + "/following", plural=True)
===========changed ref 2===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
- """
+ """Returns raw user data"""
- Returns raw user data
- """
+ return get_template(BASE_URL + user_id)
- r = s.get(BASE_URL + user_id)
- return r.json()
===========changed ref 3===========
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
- """
+ """Returns list of followers"""
- Returns list of followers
- """
- r = s.get(BASE_URL + user_id + "/followers")
- return r.json()
+ return get_template(BASE_URL + user_id + "/followers", plural=True)
|
backend.external.github_api.user/get_user_orgs
|
Modified
|
avgupta456~github-trends
|
32af92e58d1ca52b19aa2de6db4bf6e8aa944211
|
use get_template
|
<1>:<del> r = s.get(BASE_URL + user_id + "/orgs")
<2>:<del> return r.json()
<3>:<add> return get_template(BASE_URL + user_id + "/orgs", plural=True, per_page=per_page)
|
# module: backend.external.github_api.user
+ def get_user_orgs(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_orgs(user_id: str) -> dict:
<0> """Returns list of user organizations"""
<1> r = s.get(BASE_URL + user_id + "/orgs")
<2> return r.json()
<3>
|
===========changed ref 0===========
# module: backend.external.github_api.user
- s = requests.session()
-
BASE_URL = "https://api.github.com/users/"
===========changed ref 1===========
# module: backend.external.github_api.user
def get_user_following(user_id: str) -> dict:
"""Returns list of following"""
- r = s.get(BASE_URL + user_id + "/following")
- return r.json()
+ return get_template(BASE_URL + user_id + "/following", plural=True)
===========changed ref 2===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
- """
+ """Returns raw user data"""
- Returns raw user data
- """
+ return get_template(BASE_URL + user_id)
- r = s.get(BASE_URL + user_id)
- return r.json()
===========changed ref 3===========
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
- """
+ """Returns list of followers"""
- Returns list of followers
- """
- r = s.get(BASE_URL + user_id + "/followers")
- return r.json()
+ return get_template(BASE_URL + user_id + "/followers", plural=True)
===========changed ref 4===========
# module: backend.external.github_api.user
+ def get_user_starred_repos(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_starred_repos(user_id: str) -> dict:
"""Returns list of starred repos"""
+ return get_template(
+ BASE_URL + user_id + "/starred",
- r = s.get(BASE_URL + user_id + "/starred")
+ plural=True,
+ per_page=per_page,
+ accept_header="application/vnd.github.v3.star+json",
+ )
- return r.json()
|
backend.external.github_api.user/get_user_repos
|
Modified
|
avgupta456~github-trends
|
32af92e58d1ca52b19aa2de6db4bf6e8aa944211
|
use get_template
|
<1>:<del> r = s.get(BASE_URL + user_id + "/repos")
<2>:<del> return r.json()
<3>:<add> return get_template(BASE_URL + user_id + "/repos", plural=True, per_page=per_page)
|
# module: backend.external.github_api.user
+ def get_user_repos(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_repos(user_id: str) -> dict:
<0> """Returns list of user repositories"""
<1> r = s.get(BASE_URL + user_id + "/repos")
<2> return r.json()
<3>
|
===========changed ref 0===========
# module: backend.external.github_api.user
- s = requests.session()
-
BASE_URL = "https://api.github.com/users/"
===========changed ref 1===========
# module: backend.external.github_api.user
+ def get_user_orgs(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_orgs(user_id: str) -> dict:
"""Returns list of user organizations"""
- r = s.get(BASE_URL + user_id + "/orgs")
- return r.json()
+ return get_template(BASE_URL + user_id + "/orgs", plural=True, per_page=per_page)
===========changed ref 2===========
# module: backend.external.github_api.user
def get_user_following(user_id: str) -> dict:
"""Returns list of following"""
- r = s.get(BASE_URL + user_id + "/following")
- return r.json()
+ return get_template(BASE_URL + user_id + "/following", plural=True)
===========changed ref 3===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
- """
+ """Returns raw user data"""
- Returns raw user data
- """
+ return get_template(BASE_URL + user_id)
- r = s.get(BASE_URL + user_id)
- return r.json()
===========changed ref 4===========
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
- """
+ """Returns list of followers"""
- Returns list of followers
- """
- r = s.get(BASE_URL + user_id + "/followers")
- return r.json()
+ return get_template(BASE_URL + user_id + "/followers", plural=True)
===========changed ref 5===========
# module: backend.external.github_api.user
+ def get_user_starred_repos(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_starred_repos(user_id: str) -> dict:
"""Returns list of starred repos"""
+ return get_template(
+ BASE_URL + user_id + "/starred",
- r = s.get(BASE_URL + user_id + "/starred")
+ plural=True,
+ per_page=per_page,
+ accept_header="application/vnd.github.v3.star+json",
+ )
- return r.json()
|
backend.external.github_api.repo/get_repo
|
Modified
|
avgupta456~github-trends
|
32af92e58d1ca52b19aa2de6db4bf6e8aa944211
|
use get_template
|
<1>:<add> return get_template(BASE_URL + owner + "/" + repo)
<del> r = s.get(BASE_URL + owner + "/" + repo)
<2>:<del> return r.json()
|
# module: backend.external.github_api.repo
def get_repo(owner: str, repo: str) -> dict:
<0> """Returns raw repository data"""
<1> r = s.get(BASE_URL + owner + "/" + repo)
<2> return r.json()
<3>
|
===========unchanged ref 0===========
at: backend.external.github_api.repo
BASE_URL = "https://api.github.com/repos/"
at: external.github_api.template
get_template(query: str, plural: Optional[bool]=False, per_page: Optional[str]="100", accept_header: Optional[str]="application/vnd.github.v3+json") -> dict
===========changed ref 0===========
# module: backend.external.github_api.repo
- s = requests.session()
-
BASE_URL = "https://api.github.com/repos/"
===========changed ref 1===========
# module: backend.external.github_api.user
- s = requests.session()
-
BASE_URL = "https://api.github.com/users/"
===========changed ref 2===========
# module: backend.external.github_api.user
def get_user_following(user_id: str) -> dict:
"""Returns list of following"""
- r = s.get(BASE_URL + user_id + "/following")
- return r.json()
+ return get_template(BASE_URL + user_id + "/following", plural=True)
===========changed ref 3===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
- """
+ """Returns raw user data"""
- Returns raw user data
- """
+ return get_template(BASE_URL + user_id)
- r = s.get(BASE_URL + user_id)
- return r.json()
===========changed ref 4===========
# module: backend.external.github_api.user
+ def get_user_repos(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_repos(user_id: str) -> dict:
"""Returns list of user repositories"""
- r = s.get(BASE_URL + user_id + "/repos")
- return r.json()
+ return get_template(BASE_URL + user_id + "/repos", plural=True, per_page=per_page)
===========changed ref 5===========
# module: backend.external.github_api.user
+ def get_user_orgs(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_orgs(user_id: str) -> dict:
"""Returns list of user organizations"""
- r = s.get(BASE_URL + user_id + "/orgs")
- return r.json()
+ return get_template(BASE_URL + user_id + "/orgs", plural=True, per_page=per_page)
===========changed ref 6===========
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
- """
+ """Returns list of followers"""
- Returns list of followers
- """
- r = s.get(BASE_URL + user_id + "/followers")
- return r.json()
+ return get_template(BASE_URL + user_id + "/followers", plural=True)
===========changed ref 7===========
# module: backend.external.github_api.user
+ def get_user_starred_repos(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_starred_repos(user_id: str) -> dict:
"""Returns list of starred repos"""
+ return get_template(
+ BASE_URL + user_id + "/starred",
- r = s.get(BASE_URL + user_id + "/starred")
+ plural=True,
+ per_page=per_page,
+ accept_header="application/vnd.github.v3.star+json",
+ )
- return r.json()
|
backend.external.github_api.repo/get_repo_languages
|
Modified
|
avgupta456~github-trends
|
32af92e58d1ca52b19aa2de6db4bf6e8aa944211
|
use get_template
|
<1>:<add> return get_template(BASE_URL + owner + "/" + repo + "/languages", plural=True)
<del> r = s.get(BASE_URL + owner + "/" + repo + "/languages")
<2>:<del> return r.json()
|
# module: backend.external.github_api.repo
def get_repo_languages(owner: str, repo: str) -> dict:
<0> """Returns repository language breakdown"""
<1> r = s.get(BASE_URL + owner + "/" + repo + "/languages")
<2> return r.json()
<3>
|
===========changed ref 0===========
# module: backend.external.github_api.repo
- s = requests.session()
-
BASE_URL = "https://api.github.com/repos/"
===========changed ref 1===========
# module: backend.external.github_api.repo
def get_repo(owner: str, repo: str) -> dict:
"""Returns raw repository data"""
+ return get_template(BASE_URL + owner + "/" + repo)
- r = s.get(BASE_URL + owner + "/" + repo)
- return r.json()
===========changed ref 2===========
# module: backend.external.github_api.user
- s = requests.session()
-
BASE_URL = "https://api.github.com/users/"
===========changed ref 3===========
# module: backend.external.github_api.user
def get_user_following(user_id: str) -> dict:
"""Returns list of following"""
- r = s.get(BASE_URL + user_id + "/following")
- return r.json()
+ return get_template(BASE_URL + user_id + "/following", plural=True)
===========changed ref 4===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
- """
+ """Returns raw user data"""
- Returns raw user data
- """
+ return get_template(BASE_URL + user_id)
- r = s.get(BASE_URL + user_id)
- return r.json()
===========changed ref 5===========
# module: backend.external.github_api.user
+ def get_user_repos(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_repos(user_id: str) -> dict:
"""Returns list of user repositories"""
- r = s.get(BASE_URL + user_id + "/repos")
- return r.json()
+ return get_template(BASE_URL + user_id + "/repos", plural=True, per_page=per_page)
===========changed ref 6===========
# module: backend.external.github_api.user
+ def get_user_orgs(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_orgs(user_id: str) -> dict:
"""Returns list of user organizations"""
- r = s.get(BASE_URL + user_id + "/orgs")
- return r.json()
+ return get_template(BASE_URL + user_id + "/orgs", plural=True, per_page=per_page)
===========changed ref 7===========
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
- """
+ """Returns list of followers"""
- Returns list of followers
- """
- r = s.get(BASE_URL + user_id + "/followers")
- return r.json()
+ return get_template(BASE_URL + user_id + "/followers", plural=True)
===========changed ref 8===========
# module: backend.external.github_api.user
+ def get_user_starred_repos(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_starred_repos(user_id: str) -> dict:
"""Returns list of starred repos"""
+ return get_template(
+ BASE_URL + user_id + "/starred",
- r = s.get(BASE_URL + user_id + "/starred")
+ plural=True,
+ per_page=per_page,
+ accept_header="application/vnd.github.v3.star+json",
+ )
- return r.json()
|
backend.external.github_api.repo/get_repo_stargazers
|
Modified
|
avgupta456~github-trends
|
32af92e58d1ca52b19aa2de6db4bf6e8aa944211
|
use get_template
|
<1>:<del> headers = {"Accept": "application/vnd.github.v3.star+json"}
<2>:<del> r = s.get(
<3>:<add> return get_template(
<add> BASE_URL + owner + "/" + repo + "/stargazers",
<del> BASE_URL + owner + "/" + repo + "/stargazers?per_page=" + str(per_page),
<4>:<add> plural=True,
<add> per_page=per_page,
<add> accept_header="applicaiton/vnd.github.v3.star+json",
<del> headers=headers,
<6>:<del> print(r.headers)
<7>:<del> return r.json()
|
# module: backend.external.github_api.repo
def get_repo_stargazers(owner: str, repo: str, per_page: Optional[int] = 100) -> dict:
<0> """Returns stargazers with timestamp for repository"""
<1> headers = {"Accept": "application/vnd.github.v3.star+json"}
<2> r = s.get(
<3> BASE_URL + owner + "/" + repo + "/stargazers?per_page=" + str(per_page),
<4> headers=headers,
<5> )
<6> print(r.headers)
<7> return r.json()
<8>
|
===========changed ref 0===========
# module: backend.external.github_api.repo
- s = requests.session()
-
BASE_URL = "https://api.github.com/repos/"
===========changed ref 1===========
# module: backend.external.github_api.repo
def get_repo(owner: str, repo: str) -> dict:
"""Returns raw repository data"""
+ return get_template(BASE_URL + owner + "/" + repo)
- r = s.get(BASE_URL + owner + "/" + repo)
- return r.json()
===========changed ref 2===========
# module: backend.external.github_api.repo
def get_repo_languages(owner: str, repo: str) -> dict:
"""Returns repository language breakdown"""
+ return get_template(BASE_URL + owner + "/" + repo + "/languages", plural=True)
- r = s.get(BASE_URL + owner + "/" + repo + "/languages")
- return r.json()
===========changed ref 3===========
# module: backend.external.github_api.user
- s = requests.session()
-
BASE_URL = "https://api.github.com/users/"
===========changed ref 4===========
# module: backend.external.github_api.user
def get_user_following(user_id: str) -> dict:
"""Returns list of following"""
- r = s.get(BASE_URL + user_id + "/following")
- return r.json()
+ return get_template(BASE_URL + user_id + "/following", plural=True)
===========changed ref 5===========
# module: backend.external.github_api.user
def get_user(user_id: str) -> dict:
- """
+ """Returns raw user data"""
- Returns raw user data
- """
+ return get_template(BASE_URL + user_id)
- r = s.get(BASE_URL + user_id)
- return r.json()
===========changed ref 6===========
# module: backend.external.github_api.user
+ def get_user_repos(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_repos(user_id: str) -> dict:
"""Returns list of user repositories"""
- r = s.get(BASE_URL + user_id + "/repos")
- return r.json()
+ return get_template(BASE_URL + user_id + "/repos", plural=True, per_page=per_page)
===========changed ref 7===========
# module: backend.external.github_api.user
+ def get_user_orgs(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_orgs(user_id: str) -> dict:
"""Returns list of user organizations"""
- r = s.get(BASE_URL + user_id + "/orgs")
- return r.json()
+ return get_template(BASE_URL + user_id + "/orgs", plural=True, per_page=per_page)
===========changed ref 8===========
# module: backend.external.github_api.user
def get_user_followers(user_id: str) -> dict:
- """
+ """Returns list of followers"""
- Returns list of followers
- """
- r = s.get(BASE_URL + user_id + "/followers")
- return r.json()
+ return get_template(BASE_URL + user_id + "/followers", plural=True)
===========changed ref 9===========
# module: backend.external.github_api.user
+ def get_user_starred_repos(user_id: str, per_page: Optional[str] = "100") -> dict:
- def get_user_starred_repos(user_id: str) -> dict:
"""Returns list of starred repos"""
+ return get_template(
+ BASE_URL + user_id + "/starred",
- r = s.get(BASE_URL + user_id + "/starred")
+ plural=True,
+ per_page=per_page,
+ accept_header="application/vnd.github.v3.star+json",
+ )
- return r.json()
|
backend.external.github_api.rest.template/get_template
|
Modified
|
avgupta456~github-trends
|
861b4a0e3800b65e370e187dfb12c30d40fbd4e0
|
updated templates
|
<7>:<add> raise RESTError(
<add> "Invalid status code "
<del> raise HTTPError("Invalid status code")
<8>:<add> + str(r.status_code)
<add> + ": "
<add> + str(r.json()["message"])
<add> + " Documentation at "
<add> + str(r.json()["documentation_url"])
<add> )
|
# module: backend.external.github_api.rest.template
def get_template(
query: str,
plural: Optional[bool] = False,
per_page: Optional[str] = "100",
accept_header: Optional[str] = "application/vnd.github.v3+json",
) -> dict:
<0> """Template for interacting with the GitHub API"""
<1> headers = {"Accept": accept_header}
<2> params = {"per_page": per_page} if plural else {}
<3> r = s.get(query, params=params, headers=headers)
<4> if r.status_code == 200:
<5> return r.json()
<6> else:
<7> raise HTTPError("Invalid status code")
<8>
|
===========unchanged ref 0===========
at: backend.external.github_api.rest.template
s = requests.session()
RESTError(*args: object)
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.models.Response.__init__
self.status_code = None
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
get(url: Union[Text, bytes], **kwargs) -> Response
===========changed ref 0===========
# module: backend.external.github_api.rest.template
- class HTTPError(Exception):
- pass
-
===========changed ref 1===========
# module: backend.external.github_api.rest.template
- class HTTPError(Exception):
- pass
-
|
backend.external.github_api.rest.template/get_template
|
Modified
|
avgupta456~github-trends
|
bd20e334225455f341a73a76fbb47c0771d7877c
|
add typing
|
<1>:<add> headers: Dict[str, str] = {"Accept": accept_header}
<del> headers = {"Accept": accept_header}
<2>:<add> params: Dict[str, str] = {"per_page": str(per_page)} if plural else {}
<del> params = {"per_page": per_page} if plural else {}
|
# module: backend.external.github_api.rest.template
def get_template(
query: str,
plural: Optional[bool] = False,
+ per_page: Optional[int] = 100,
- per_page: Optional[str] = "100",
accept_header: Optional[str] = "application/vnd.github.v3+json",
+ ) -> Dict[str, Any]:
- ) -> dict:
<0> """Template for interacting with the GitHub API"""
<1> headers = {"Accept": accept_header}
<2> params = {"per_page": per_page} if plural else {}
<3> r = s.get(query, params=params, headers=headers)
<4> if r.status_code == 200:
<5> return r.json()
<6> else:
<7> raise RESTError(
<8> "Invalid status code "
<9> + str(r.status_code)
<10> + ": "
<11> + str(r.json()["message"])
<12> + " Documentation at "
<13> + str(r.json()["documentation_url"])
<14> )
<15>
|
===========unchanged ref 0===========
at: backend.external.github_api.rest.template
s = requests.session()
RESTError(*args: object)
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.models.Response.__init__
self.status_code = None
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
get(url: Union[Text, bytes], **kwargs) -> Response
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.external.github_api.graphql.template/get_template
|
Modified
|
avgupta456~github-trends
|
bd20e334225455f341a73a76fbb47c0771d7877c
|
add typing
|
<1>:<add> headers: Dict[str, str] = {"Authorization": "bearer " + token}
<del> headers = {"Authorization": "bearer " + token}
|
# module: backend.external.github_api.graphql.template
+ def get_template(query: Dict[str, Any]) -> Dict[str, Any]:
- def get_template(query: dict) -> dict:
<0> token = os.getenv("GITHUB_TOKEN", "")
<1> headers = {"Authorization": "bearer " + token}
<2> r = s.post("https://api.github.com/graphql", json=query, headers=headers)
<3> if r.status_code == 200:
<4> return r.json()
<5> else:
<6> raise GraphQlError(
<7> "Invalid status code "
<8> + str(r.status_code)
<9> + ": "
<10> + str(r.json()["message"])
<11> + " Documentation at "
<12> + str(r.json()["documentation_url"])
<13> )
<14>
|
===========unchanged ref 0===========
at: backend.external.github_api.graphql.template
s = requests.session()
GraphQlError(*args: object)
at: os
getenv(key: str, default: _T) -> Union[str, _T]
getenv(key: str) -> Optional[str]
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.models.Response.__init__
self.status_code = None
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.external.github_api.rest.template
def get_template(
query: str,
plural: Optional[bool] = False,
+ per_page: Optional[int] = 100,
- per_page: Optional[str] = "100",
accept_header: Optional[str] = "application/vnd.github.v3+json",
+ ) -> Dict[str, Any]:
- ) -> dict:
"""Template for interacting with the GitHub API"""
+ headers: Dict[str, str] = {"Accept": accept_header}
- headers = {"Accept": accept_header}
+ params: Dict[str, str] = {"per_page": str(per_page)} if plural else {}
- params = {"per_page": per_page} if plural else {}
r = s.get(query, params=params, headers=headers)
if r.status_code == 200:
return r.json()
else:
raise RESTError(
"Invalid status code "
+ str(r.status_code)
+ ": "
+ str(r.json()["message"])
+ " Documentation at "
+ str(r.json()["documentation_url"])
)
|
backend.external.github_api.graphql.user/get_user
|
Modified
|
avgupta456~github-trends
|
ad942a620e95697275b3511d54a69de21eaa3abd
|
create get_user_commit_contributions_by_repository
|
<10>:<add> totalCount:contributions(first: 1){
<add> totalCount
<add> }
<add> contributions(first: 100){
<del> contributions(first: 10){
<11>:<del> totalCount
<12>:<add> nodes{
<del> nodes{
<13>:<add> commitCount,
<del> commitCount,
<14>:<add> occurredAt,
<del> occurredAt,
<15>:<add> }
<add> pageInfo{
<add> hasNextPage,
<add> endCursor
<add> }
|
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
<0> query = {
<1> "variables": {"login": user_id},
<2> "query": """
<3> query getUser($login: String!) {
<4> user(login: $login){
<5> contributionsCollection{
<6> commitContributionsByRepository(maxRepositories: 10){
<7> repository{
<8> name,
<9> },
<10> contributions(first: 10){
<11> totalCount
<12> nodes{
<13> commitCount,
<14> occurredAt,
<15> }
<16> }
<17> },
<18> contributionCalendar{
<19> totalContributions,
<20> weeks{
<21> contributionDays{
<22> date,
<23> weekday,
<24> contributionCount,
<25> contributionLevel,
<26> }
<27> }
<28> colors,
<29> }
<30> contributionYears,
<31> issueContributions(first: 10){
<32> totalCount,
<33> nodes{
<34> occurredAt,
<35> issue{
<36> state
<37> }
<38> }
<39> }
<40> issueContributionsByRepository(maxRepositories: 10){
<41> repository{
<42> name
<43> },
<44> contributions(first: 10){
<45> totalCount,
<46> nodes{
<47> occurredAt,
<48> issue{
<49> state
<50> }
<51> }
<52> }
<53> }
<54> pullRequestContributions(first: 10){
<55> totalCount,
<56> nodes{
<57> occurredAt,
<58> pullRequest{
<59> state
<60> }
<61> }
<62> }
<63> pullRequestContributionsByRepository(maxRepositories:10){
<64> repository{
<65> name
<66> },
<67> contributions(first:10){
<68> totalCount,
<69> nodes{
<70> occurredAt,
<71> pullRequest{
<72> state,
<73> }
<74> }
<75> }
<76> }
<77> pullRequestReviewContributions(first: 10){
<78> totalCount,
<79> nodes{</s>
|
===========below chunk 0===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
# offset: 1
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state,
}
}
}
},
repositoryContributions(first:10){
totalCount,
nodes{
repository{
name,
}
occurredAt,
}
},
restrictedContributionsCount,
totalCommitContributions,
totalIssueContributions,
totalPullRequestContributions,
totalPullRequestReviewContributions,
totalRepositoryContributions,
totalRepositoriesWithContributedCommits,
totalRepositoriesWithContributedIssues,
totalRepositoriesWithContributedPullRequests,
totalRepositoriesWithContributedPullRequestReviews
},
followers(first:10){
totalCount,
nodes{
name,
url,
}
}
following(first:10){
totalCount,
nodes{
name,
url,
}
}
}
}
""",
}
return get_template(query)
===========unchanged ref 0===========
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.external.github_api.graphql.user/get_user
|
Modified
|
avgupta456~github-trends
|
d90dc77bb03a6b68f5c0a11dcb9a69e334a9c064
|
docstrings, exception handling
|
<0>:<add> """gets all user data from graphql"""
|
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
<0> query = {
<1> "variables": {"login": user_id},
<2> "query": """
<3> query getUser($login: String!) {
<4> user(login: $login){
<5> contributionsCollection{
<6> commitContributionsByRepository(maxRepositories: 10){
<7> repository{
<8> name,
<9> },
<10> totalCount:contributions(first: 1){
<11> totalCount
<12> }
<13> contributions(first: 100){
<14> nodes{
<15> commitCount,
<16> occurredAt,
<17> }
<18> pageInfo{
<19> hasNextPage,
<20> endCursor
<21> }
<22> }
<23> }
<24> },
<25> contributionCalendar{
<26> totalContributions,
<27> weeks{
<28> contributionDays{
<29> date,
<30> weekday,
<31> contributionCount,
<32> contributionLevel,
<33> }
<34> }
<35> colors,
<36> }
<37> contributionYears,
<38> issueContributions(first: 10){
<39> totalCount,
<40> nodes{
<41> occurredAt,
<42> issue{
<43> state
<44> }
<45> }
<46> }
<47> issueContributionsByRepository(maxRepositories: 10){
<48> repository{
<49> name
<50> },
<51> contributions(first: 10){
<52> totalCount,
<53> nodes{
<54> occurredAt,
<55> issue{
<56> state
<57> }
<58> }
<59> }
<60> }
<61> pullRequestContributions(first: 10){
<62> totalCount,
<63> nodes{
<64> occurredAt,
<65> pullRequest{
<66> state
<67> }
<68> }
<69> }
<70> pullRequestContributionsByRepository(maxRepositories:10){
<71> repository{
<72> name
<73> },
<74> contributions(first:10){
<75> totalCount,
<76> nodes{
<77> occurredAt,
<78> pullRequest{
<79> </s>
|
===========below chunk 0===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
# offset: 1
}
}
}
}
pullRequestReviewContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state,
}
}
}
},
repositoryContributions(first:10){
totalCount,
nodes{
repository{
name,
}
occurredAt,
}
},
restrictedContributionsCount,
totalCommitContributions,
totalIssueContributions,
totalPullRequestContributions,
totalPullRequestReviewContributions,
totalRepositoryContributions,
totalRepositoriesWithContributedCommits,
totalRepositoriesWithContributedIssues,
totalRepositoriesWithContributedPullRequests,
totalRepositoriesWithContributedPullRequestReviews
},
followers(first:10){
totalCount,
nodes{
name,
url,
}
}
following(first:10){
totalCount,
nodes{
name,
url,
}
}
}
}
""",
}
try:
return get_template(query)
except Exception as e:
raise e
===========unchanged ref 0===========
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.external.github_api.graphql.user/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
d90dc77bb03a6b68f5c0a11dcb9a69e334a9c064
|
docstrings, exception handling
|
<39>:<add> logging.exception(e)
|
# module: backend.external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: Optional[int] = 10,
first: Optional[int] = 100,
after: Optional[str] = "",
):
<0> """Runs an individual query, fetching at most 100 days of history"""
<1> query = {
<2> "variables": {
<3> "login": user_id,
<4> "maxRepos": max_repos,
<5> "first": first,
<6> "after": after,
<7> },
<8> "query": """
<9> query getUser($login: String! $maxRepos: Int!, $first: Int!, $after: String!) {
<10> user(login: $login){
<11> contributionsCollection{
<12> commitContributionsByRepository(maxRepositories: $maxRepos){
<13> repository{
<14> name,
<15> },
<16> totalCount:contributions(first: 1){
<17> totalCount
<18> }
<19> contributions(first: $first, after: $after){
<20> nodes{
<21> commitCount,
<22> occurredAt,
<23> }
<24> pageInfo{
<25> hasNextPage,
<26> endCursor
<27> }
<28> }
<29> }
<30> },
<31> },
<32> }
<33> """,
<34> }
<35>
<36> try:
<37> return get_template(query)
<38> except Exception as e:
<39> raise e
<40>
|
===========unchanged ref 0===========
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
+ """gets all user data from graphql"""
query = {
"variables": {"login": user_id},
"query": """
query getUser($login: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: 10){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: 100){
nodes{
commitCount,
occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
contributionCalendar{
totalContributions,
weeks{
contributionDays{
date,
weekday,
contributionCount,
contributionLevel,
}
}
colors,
}
contributionYears,
issueContributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
issueContributionsByRepository(maxRepositories: 10){
repository{
name
},
contributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
}
pullRequestContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequest{
state
}
}
}
pullRequestContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequest{
state,
}
}
}
}
pullRequestReviewContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories</s>
===========changed ref 1===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
# offset: 1
<s>
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state,
}
}
}
},
repositoryContributions(first:10){
totalCount,
nodes{
repository{
name,
}
occurredAt,
}
},
restrictedContributionsCount,
totalCommitContributions,
totalIssueContributions,
totalPullRequestContributions,
totalPullRequestReviewContributions,
totalRepositoryContributions,
totalRepositoriesWithContributedCommits,
totalRepositoriesWithContributedIssues,
totalRepositoriesWithContributedPullRequests,
totalRepositoriesWithContributedPullRequestReviews
},
followers(first:10){
totalCount,
nodes{
name,
url,
}
}
following(first:10){
totalCount,
nodes{
name,
url,
}
}
}
}
""",
}
try:
return get_template(query)
except Exception as e:
+ logging.exception(e)
raise e
|
backend.main/get_user
|
Modified
|
avgupta456~github-trends
|
d90dc77bb03a6b68f5c0a11dcb9a69e334a9c064
|
docstrings, exception handling
|
<0>:<add> try:
<add> data = list(map(lambda x: x.dict(), _get_user(user_id)))
<add> return {"data": data, "message": ""}
<add> except Exception as e:
<add> logging.exception(e)
<add> response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
<add> return {"data": [], "message": str(e)}
<del> return _get_user(user_id)
|
# module: backend.main
+ @app.get("/user/{user_id}", status_code=status.HTTP_200_OK)
+ def get_user(user_id: str, response: Response) -> Dict[str, Any]:
- @app.get("/user/{user_id}")
- def get_user(user_id: str) -> dict:
<0> return _get_user(user_id)
<1>
|
===========changed ref 0===========
# module: backend.external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: Optional[int] = 10,
first: Optional[int] = 100,
after: Optional[str] = "",
):
"""Runs an individual query, fetching at most 100 days of history"""
query = {
"variables": {
"login": user_id,
"maxRepos": max_repos,
"first": first,
"after": after,
},
"query": """
query getUser($login: String! $maxRepos: Int!, $first: Int!, $after: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: $maxRepos){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: $first, after: $after){
nodes{
commitCount,
occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
},
}
""",
}
try:
return get_template(query)
except Exception as e:
+ logging.exception(e)
raise e
===========changed ref 1===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
+ """gets all user data from graphql"""
query = {
"variables": {"login": user_id},
"query": """
query getUser($login: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: 10){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: 100){
nodes{
commitCount,
occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
contributionCalendar{
totalContributions,
weeks{
contributionDays{
date,
weekday,
contributionCount,
contributionLevel,
}
}
colors,
}
contributionYears,
issueContributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
issueContributionsByRepository(maxRepositories: 10){
repository{
name
},
contributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
}
pullRequestContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequest{
state
}
}
}
pullRequestContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequest{
state,
}
}
}
}
pullRequestReviewContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories</s>
===========changed ref 2===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
# offset: 1
<s>
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state,
}
}
}
},
repositoryContributions(first:10){
totalCount,
nodes{
repository{
name,
}
occurredAt,
}
},
restrictedContributionsCount,
totalCommitContributions,
totalIssueContributions,
totalPullRequestContributions,
totalPullRequestReviewContributions,
totalRepositoryContributions,
totalRepositoriesWithContributedCommits,
totalRepositoriesWithContributedIssues,
totalRepositoriesWithContributedPullRequests,
totalRepositoriesWithContributedPullRequestReviews
},
followers(first:10){
totalCount,
nodes{
name,
url,
}
}
following(first:10){
totalCount,
nodes{
name,
url,
}
}
}
}
""",
}
try:
return get_template(query)
except Exception as e:
+ logging.exception(e)
raise e
|
backend.main/get_repo
|
Modified
|
avgupta456~github-trends
|
d90dc77bb03a6b68f5c0a11dcb9a69e334a9c064
|
docstrings, exception handling
|
<0>:<add> try:
<add> data = _get_repo(user_id, repo_name)
<del> return _get_repo(user_id, repo_name)
<1>:<add> return {"data": data, "message": ""}
<add> except Exception as e:
<add> logging.exception(e)
<add> response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
<add> return {"data": [], "message": str(e)}
|
# module: backend.main
+ @app.get("/repo/{user_id}/{repo_name}", status_code=status.HTTP_200_OK)
- @app.get("/repo/{user_id}/{repo_name}")
+ def get_repo(user_id: str, repo_name: str, response: Response) -> Dict[str, Any]:
- def get_repo(user_id: str, repo_name: str) -> Dict[str, Any]:
<0> return _get_repo(user_id, repo_name)
<1>
|
===========changed ref 0===========
# module: backend.main
+ @app.get("/user/{user_id}", status_code=status.HTTP_200_OK)
+ def get_user(user_id: str, response: Response) -> Dict[str, Any]:
- @app.get("/user/{user_id}")
- def get_user(user_id: str) -> dict:
+ try:
+ data = list(map(lambda x: x.dict(), _get_user(user_id)))
+ return {"data": data, "message": ""}
+ except Exception as e:
+ logging.exception(e)
+ response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
+ return {"data": [], "message": str(e)}
- return _get_user(user_id)
===========changed ref 1===========
# module: backend.external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: Optional[int] = 10,
first: Optional[int] = 100,
after: Optional[str] = "",
):
"""Runs an individual query, fetching at most 100 days of history"""
query = {
"variables": {
"login": user_id,
"maxRepos": max_repos,
"first": first,
"after": after,
},
"query": """
query getUser($login: String! $maxRepos: Int!, $first: Int!, $after: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: $maxRepos){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: $first, after: $after){
nodes{
commitCount,
occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
},
}
""",
}
try:
return get_template(query)
except Exception as e:
+ logging.exception(e)
raise e
===========changed ref 2===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
+ """gets all user data from graphql"""
query = {
"variables": {"login": user_id},
"query": """
query getUser($login: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: 10){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: 100){
nodes{
commitCount,
occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
contributionCalendar{
totalContributions,
weeks{
contributionDays{
date,
weekday,
contributionCount,
contributionLevel,
}
}
colors,
}
contributionYears,
issueContributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
issueContributionsByRepository(maxRepositories: 10){
repository{
name
},
contributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
}
pullRequestContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequest{
state
}
}
}
pullRequestContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequest{
state,
}
}
}
}
pullRequestReviewContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories</s>
===========changed ref 3===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
# offset: 1
<s>
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state,
}
}
}
},
repositoryContributions(first:10){
totalCount,
nodes{
repository{
name,
}
occurredAt,
}
},
restrictedContributionsCount,
totalCommitContributions,
totalIssueContributions,
totalPullRequestContributions,
totalPullRequestReviewContributions,
totalRepositoryContributions,
totalRepositoriesWithContributedCommits,
totalRepositoriesWithContributedIssues,
totalRepositoriesWithContributedPullRequests,
totalRepositoriesWithContributedPullRequestReviews
},
followers(first:10){
totalCount,
nodes{
name,
url,
}
}
following(first:10){
totalCount,
nodes{
name,
url,
}
}
}
}
""",
}
try:
return get_template(query)
except Exception as e:
+ logging.exception(e)
raise e
|
backend.main/get_user
|
Modified
|
avgupta456~github-trends
|
10f2ba00d49bd4a94d1a6c726d99e1ce4cb6ed30
|
fix typing issues
|
<1>:<add> data: List[Dict[str, Any]] = list(map(lambda x: x.dict(), _get_user(user_id)))
<del> data = list(map(lambda x: x.dict(), _get_user(user_id)))
|
# module: backend.main
@app.get("/user/{user_id}", status_code=status.HTTP_200_OK)
def get_user(user_id: str, response: Response) -> Dict[str, Any]:
<0> try:
<1> data = list(map(lambda x: x.dict(), _get_user(user_id)))
<2> return {"data": data, "message": ""}
<3> except Exception as e:
<4> logging.exception(e)
<5> response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
<6> return {"data": [], "message": str(e)}
<7>
|
===========unchanged ref 0===========
at: backend.main
app = FastAPI()
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: processing.user.commit_contributions_by_repository
get_user_commit_contributions_by_repository(user_id: str, max_repos: Optional[int]=10, start_date: Optional[Date]=today - 365, end_date: Optional[Date]=today) -> List[CommitContributionsByRepository]
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.models.misc.date/Date.__init__
|
Modified
|
avgupta456~github-trends
|
10f2ba00d49bd4a94d1a6c726d99e1ce4cb6ed30
|
fix typing issues
|
<2>:<add> year: int = date.year
<add> month: int = date.month
<add> day: int = date.day
<add> date = "-".join([str(year), str(month), str(day)])
<del> date = "-".join([str(date.year), str(date.month), str(date.day)])
|
# module: backend.models.misc.date
class Date:
def __init__(self, date: Union[str, datetime]) -> None:
<0> self.date_obj: datetime
<1> if isinstance(date, datetime):
<2> date = "-".join([str(date.year), str(date.month), str(date.day)])
<3> date_str: str = date.split("T")[0] if "T" in date else date
<4> self.date_obj = datetime.strptime(date_str, "%Y-%m-%d")
<5>
|
===========unchanged ref 0===========
at: datetime
datetime()
===========changed ref 0===========
# module: backend.main
@app.get("/user/{user_id}", status_code=status.HTTP_200_OK)
def get_user(user_id: str, response: Response) -> Dict[str, Any]:
try:
+ data: List[Dict[str, Any]] = list(map(lambda x: x.dict(), _get_user(user_id)))
- data = list(map(lambda x: x.dict(), _get_user(user_id)))
return {"data": data, "message": ""}
except Exception as e:
logging.exception(e)
response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
return {"data": [], "message": str(e)}
|
backend.processing.user.commit_contributions_by_repository/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
90bb86ddbb755bbb8f2fa8aaa3181cbbc37b6eb4
|
cleanup
|
<27>:<del> print(raw_contribs[0])
<28>:<del> print(CommitContribution.parse_obj(raw_contribs[0]))
|
# module: backend.processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: Optional[int] = 10,
start_date: Optional[Date] = today - 365,
end_date: Optional[Date] = today,
) -> List[CommitContributionsByRepository]:
<0> """Gets the daily contribution history for a users top x repositories"""
<1> output = []
<2> index, cont, after = 0, True, ""
<3> while index < 10 and cont:
<4> try:
<5> data = run_query(user_id, max_repos, after=after)
<6> except Exception as e:
<7> logging.exception(e)
<8> raise e
<9>
<10> data = data["data"]["user"]["contributionsCollection"][
<11> "commitContributionsByRepository"
<12> ]
<13>
<14> cont = False
<15> repo: Dict[str, Any]
<16> for i, repo in enumerate(data):
<17> if index == 0:
<18> output.append(
<19> {
<20> "name": repo["repository"]["name"],
<21> "contributions": repo["totalCount"]["totalCount"],
<22> "timeline": [],
<23> }
<24> )
<25>
<26> raw_contribs = repo["contributions"]["nodes"]
<27> print(raw_contribs[0])
<28> print(CommitContribution.parse_obj(raw_contribs[0]))
<29> contribs = map(lambda x: CommitContribution.parse_obj(x), raw_contribs)
<30> output[i]["timeline"].extend(contribs)
<31>
<32> if repo["contributions"]["pageInfo"]["hasNextPage"]:
<33> after = repo["contributions"]["pageInfo"]["endCursor"]
<34> cont = True
<35>
<36> index += 1
<37>
<38> output = list(map(lambda x: CommitContributionsByRepository.parse_obj(x), output))
<39> return output
<40>
|
===========unchanged ref 0===========
at: external.github_api.graphql.user
get_user_commit_contributions_by_repository(user_id: str, max_repos: Optional[int]=10, first: Optional[int]=100, after: Optional[str]="")
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: models.misc.date
Date(date: Union[str, datetime])
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.external.github_api.rest.template/get_template
|
Modified
|
avgupta456~github-trends
|
90bb86ddbb755bbb8f2fa8aaa3181cbbc37b6eb4
|
cleanup
|
<1>:<add> headers: Dict[str, str] = {"Accept": str(accept_header)}
<del> headers: Dict[str, str] = {"Accept": accept_header}
<3>:<add> r = s.get(query, params=params, headers=headers) # type: ignore
<del> r = s.get(query, params=params, headers=headers)
<5>:<add> return r.json() # type: ignore
<del> return r.json()
<11>:<add> + str(r.json()["message"]) # type: ignore
<del> + str(r.json()["message"])
<13>:<add> + str(r.json()["documentation_url"]) # type: ignore
<del> + str(r.json()["documentation_url"])
|
# module: backend.external.github_api.rest.template
def get_template(
query: str,
plural: Optional[bool] = False,
per_page: Optional[int] = 100,
accept_header: Optional[str] = "application/vnd.github.v3+json",
) -> Dict[str, Any]:
<0> """Template for interacting with the GitHub REST API"""
<1> headers: Dict[str, str] = {"Accept": accept_header}
<2> params: Dict[str, str] = {"per_page": str(per_page)} if plural else {}
<3> r = s.get(query, params=params, headers=headers)
<4> if r.status_code == 200:
<5> return r.json()
<6> else:
<7> raise RESTError(
<8> "Invalid status code "
<9> + str(r.status_code)
<10> + ": "
<11> + str(r.json()["message"])
<12> + " Documentation at "
<13> + str(r.json()["documentation_url"])
<14> )
<15>
|
===========unchanged ref 0===========
at: backend.external.github_api.rest.template
s = requests.session()
RESTError(*args: object)
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.models.Response.__init__
self.status_code = None
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
get(url: Union[Text, bytes], **kwargs) -> Response
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: Optional[int] = 10,
start_date: Optional[Date] = today - 365,
end_date: Optional[Date] = today,
) -> List[CommitContributionsByRepository]:
"""Gets the daily contribution history for a users top x repositories"""
output = []
index, cont, after = 0, True, ""
while index < 10 and cont:
try:
data = run_query(user_id, max_repos, after=after)
except Exception as e:
logging.exception(e)
raise e
data = data["data"]["user"]["contributionsCollection"][
"commitContributionsByRepository"
]
cont = False
repo: Dict[str, Any]
for i, repo in enumerate(data):
if index == 0:
output.append(
{
"name": repo["repository"]["name"],
"contributions": repo["totalCount"]["totalCount"],
"timeline": [],
}
)
raw_contribs = repo["contributions"]["nodes"]
- print(raw_contribs[0])
- print(CommitContribution.parse_obj(raw_contribs[0]))
contribs = map(lambda x: CommitContribution.parse_obj(x), raw_contribs)
output[i]["timeline"].extend(contribs)
if repo["contributions"]["pageInfo"]["hasNextPage"]:
after = repo["contributions"]["pageInfo"]["endCursor"]
cont = True
index += 1
output = list(map(lambda x: CommitContributionsByRepository.parse_obj(x), output))
return output
|
backend.main/get_user
|
Modified
|
avgupta456~github-trends
|
83e083cea6ae9df13f1a73a7fce5335ddef4767b
|
fail_gracefully decorator
|
<0>:<del> try:
<1>:<add> return list(map(lambda x: x.dict(), _get_user(user_id)))
<del> data: List[Dict[str, Any]] = list(map(lambda x: x.dict(), _get_user(user_id)))
<2>:<del> return {"data": data, "message": ""}
<3>:<del> except Exception as e:
<4>:<del> logging.exception(e)
<5>:<del> response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
<6>:<del> return {"data": [], "message": str(e)}
|
# module: backend.main
@app.get("/user/{user_id}", status_code=status.HTTP_200_OK)
+ @fail_gracefully
+ def get_user(response: Response, user_id: str) -> List[Dict[str, Any]]:
- def get_user(user_id: str, response: Response) -> Dict[str, Any]:
<0> try:
<1> data: List[Dict[str, Any]] = list(map(lambda x: x.dict(), _get_user(user_id)))
<2> return {"data": data, "message": ""}
<3> except Exception as e:
<4> logging.exception(e)
<5> response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
<6> return {"data": [], "message": str(e)}
<7>
|
===========unchanged ref 0===========
at: functools
wraps(wrapped: _AnyCallable, assigned: Sequence[str]=..., updated: Sequence[str]=...) -> Callable[[_T], _T]
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.main/get_repo
|
Modified
|
avgupta456~github-trends
|
83e083cea6ae9df13f1a73a7fce5335ddef4767b
|
fail_gracefully decorator
|
<0>:<del> try:
<1>:<add> return _get_repo(user_id, repo_name)
<del> data = _get_repo(user_id, repo_name)
<2>:<del> return {"data": data, "message": ""}
<3>:<del> except Exception as e:
<4>:<del> logging.exception(e)
<5>:<del> response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
<6>:<del> return {"data": [], "message": str(e)}
|
# module: backend.main
@app.get("/repo/{user_id}/{repo_name}", status_code=status.HTTP_200_OK)
+ @fail_gracefully
+ def get_repo(response: Response, user_id: str, repo_name: str) -> Dict[str, Any]:
- def get_repo(user_id: str, repo_name: str, response: Response) -> Dict[str, Any]:
<0> try:
<1> data = _get_repo(user_id, repo_name)
<2> return {"data": data, "message": ""}
<3> except Exception as e:
<4> logging.exception(e)
<5> response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
<6> return {"data": [], "message": str(e)}
<7>
|
===========unchanged ref 0===========
at: backend.main
app = FastAPI()
fail_gracefully(func: Callable[..., Any])
at: backend.main.fail_gracefully
Callable(response: Response, *args: List[Any], **kwargs: Dict[str, Any]) -> Any
at: processing.user.commit_contributions_by_repository
get_user_commit_contributions_by_repository(user_id: str, max_repos: Optional[int]=10, start_date: Optional[Date]=today - 365, end_date: Optional[Date]=today) -> List[CommitContributionsByRepository]
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.main
+ def fail_gracefully(func: Callable[..., Any]):
+ @wraps(func) # needed to play nice with FastAPI decorator
+ def wrapper(response: Response, *args: List[Any], **kwargs: Dict[str, Any]) -> Any:
+ try:
+ data = func(response, *args, **kwargs)
+ return {"data": data, "message": "200 OK"}
+ except Exception as e:
+ logging.exception(e)
+ response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
+ return {"data": [], "message": "Error " + str(e)}
+
+ return wrapper
+
===========changed ref 1===========
# module: backend.main
@app.get("/user/{user_id}", status_code=status.HTTP_200_OK)
+ @fail_gracefully
+ def get_user(response: Response, user_id: str) -> List[Dict[str, Any]]:
- def get_user(user_id: str, response: Response) -> Dict[str, Any]:
- try:
+ return list(map(lambda x: x.dict(), _get_user(user_id)))
- data: List[Dict[str, Any]] = list(map(lambda x: x.dict(), _get_user(user_id)))
- return {"data": data, "message": ""}
- except Exception as e:
- logging.exception(e)
- response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
- return {"data": [], "message": str(e)}
|
backend.external.github_api.graphql.template/get_template
|
Modified
|
avgupta456~github-trends
|
48ebb323e20e519e040864f33b252bd125b8a147
|
log query execution time
|
<3>:<add> start = datetime.now()
<6>:<add> print("GraphQL", datetime.now() - start)
|
# module: backend.external.github_api.graphql.template
def get_template(query: Dict[str, Any]) -> Dict[str, Any]:
<0> """Template for interacting with the GitHub GraphQL API"""
<1> token = os.getenv("GITHUB_TOKEN", "")
<2> headers: Dict[str, str] = {"Authorization": "bearer " + token}
<3> r = s.post( # type: ignore
<4> "https://api.github.com/graphql", json=query, headers=headers
<5> )
<6> if r.status_code == 200:
<7> return r.json() # type: ignore
<8> else:
<9> raise GraphQlError(
<10> "Invalid status code "
<11> + str(r.status_code)
<12> + ": "
<13> + str(r.json()["message"]) # type: ignore
<14> + " Documentation at "
<15> + str(r.json()["documentation_url"]) # type: ignore
<16> )
<17>
|
===========unchanged ref 0===========
at: backend.external.github_api.graphql.template
s = requests.session()
GraphQlError(*args: object)
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: os
getenv(key: str, default: _T) -> Union[str, _T]
getenv(key: str) -> Optional[str]
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.models.Response.__init__
self.status_code = None
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.external.github_api.rest.template/get_template
|
Modified
|
avgupta456~github-trends
|
48ebb323e20e519e040864f33b252bd125b8a147
|
log query execution time
|
<1>:<add> start = datetime.now()
<5>:<add> print("REST API", datetime.now() - start)
|
# module: backend.external.github_api.rest.template
def get_template(
query: str,
plural: Optional[bool] = False,
per_page: Optional[int] = 100,
accept_header: Optional[str] = "application/vnd.github.v3+json",
) -> Dict[str, Any]:
<0> """Template for interacting with the GitHub REST API"""
<1> headers: Dict[str, str] = {"Accept": str(accept_header)}
<2> params: Dict[str, str] = {"per_page": str(per_page)} if plural else {}
<3> r = s.get(query, params=params, headers=headers) # type: ignore
<4> if r.status_code == 200:
<5> return r.json() # type: ignore
<6> else:
<7> raise RESTError(
<8> "Invalid status code "
<9> + str(r.status_code)
<10> + ": "
<11> + str(r.json()["message"]) # type: ignore
<12> + " Documentation at "
<13> + str(r.json()["documentation_url"]) # type: ignore
<14> )
<15>
|
===========unchanged ref 0===========
at: backend.external.github_api.rest.template
s = requests.session()
RESTError(*args: object)
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.models.Response.__init__
self.status_code = None
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
get(url: Union[Text, bytes], **kwargs) -> Response
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.external.github_api.graphql.template
def get_template(query: Dict[str, Any]) -> Dict[str, Any]:
"""Template for interacting with the GitHub GraphQL API"""
token = os.getenv("GITHUB_TOKEN", "")
headers: Dict[str, str] = {"Authorization": "bearer " + token}
+ start = datetime.now()
r = s.post( # type: ignore
"https://api.github.com/graphql", json=query, headers=headers
)
+ print("GraphQL", datetime.now() - start)
if r.status_code == 200:
return r.json() # type: ignore
else:
raise GraphQlError(
"Invalid status code "
+ str(r.status_code)
+ ": "
+ str(r.json()["message"]) # type: ignore
+ " Documentation at "
+ str(r.json()["documentation_url"]) # type: ignore
)
|
backend.main/fail_gracefully
|
Modified
|
avgupta456~github-trends
|
84a0021e27d24eda1ee183cf9b7860f02bed00af
|
log time
|
<2>:<add> start = datetime.now()
<4>:<add> return {"data": data, "message": "200 OK", "time": datetime.now() - start}
<del> return {"data": data, "message": "200 OK"}
<8>:<add> return {
<add> "data": [],
<add> "message": "Error " + str(e),
<del> return {"data": [], "message": "Error " + str(e)}
<9>:<add> "time": datetime.now() - start,
<add> }
|
# module: backend.main
def fail_gracefully(func: Callable[..., Any]):
<0> @wraps(func) # needed to play nice with FastAPI decorator
<1> def wrapper(response: Response, *args: List[Any], **kwargs: Dict[str, Any]) -> Any:
<2> try:
<3> data = func(response, *args, **kwargs)
<4> return {"data": data, "message": "200 OK"}
<5> except Exception as e:
<6> logging.exception(e)
<7> response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
<8> return {"data": [], "message": "Error " + str(e)}
<9>
<10> return wrapper
<11>
|
===========unchanged ref 0===========
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: functools
wraps(wrapped: _AnyCallable, assigned: Sequence[str]=..., updated: Sequence[str]=...) -> Callable[[_T], _T]
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.models.misc.date/Date.__sub__
|
Modified
|
avgupta456~github-trends
|
ee3bf11a8bf756858a150711c1af1bfabe7b511b
|
add, subtract, comparison for date
|
<0>:<add> if isinstance(other, int):
<add> return Date(self.date_obj - timedelta(days=other))
<del> new_date: Date = Date(self.date_obj - timedelta(days=other))
<1>:<add> else:
<add> return abs((self.date_obj - other.date_obj).days)
<del> return new_date
|
# module: backend.models.misc.date
class Date:
+ def __sub__(self, other: Union[int, Date]) -> Union[int, Date]:
- def __sub__(self, other: int) -> Date:
<0> new_date: Date = Date(self.date_obj - timedelta(days=other))
<1> return new_date
<2>
|
===========unchanged ref 0===========
at: backend.models.misc.date
Date(date: Union[str, datetime])
|
backend.external.github_api.graphql.user/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
2e746a650cb2b83e66b4ee47edd7244a29bc87da
|
fix optional usage
|
<0>:<add> max_repos: int = 100,
<add> first: int = 100,
<add> after: str = "",
|
# module: backend.external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
- max_repos: Optional[int] = 10,
- first: Optional[int] = 100,
- after: Optional[str] = "",
):
<0> """Runs an individual query, fetching at most 100 days of history"""
<1> query = {
<2> "variables": {
<3> "login": user_id,
<4> "maxRepos": max_repos,
<5> "first": first,
<6> "after": after,
<7> },
<8> "query": """
<9> query getUser($login: String! $maxRepos: Int!, $first: Int!, $after: String!) {
<10> user(login: $login){
<11> contributionsCollection{
<12> commitContributionsByRepository(maxRepositories: $maxRepos){
<13> repository{
<14> name,
<15> },
<16> totalCount:contributions(first: 1){
<17> totalCount
<18> }
<19> contributions(first: $first, after: $after){
<20> nodes{
<21> commitCount,
<22> occurredAt,
<23> }
<24> pageInfo{
<25> hasNextPage,
<26> endCursor
<27> }
<28> }
<29> }
<30> },
<31> },
<32> }
<33> """,
<34> }
<35>
<36> try:
<37> return get_template(query)
<38> except Exception as e:
<39> logging.exception(e)
<40> raise e
<41>
|
===========unchanged ref 0===========
at: external.github_api.graphql.template
get_template(query: Dict[str, Any]) -> Dict[str, Any]
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
|
backend.external.github_api.graphql.user/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
b5be3508d39f2ff7259368419b6edf768bee625a
|
updated processing logic
|
<0>:<del> max_repos: int = 100,
<1>:<del> first: int = 100,
<2>:<del> after: str = "",
<40>:<add> output_dict = get_template(query)["data"]["user"]["contributionsCollection"][
<add> "commitContributionsByRepository"
<add> ]
<add> return UserCommitContributionsByRepositoryAPIResponse(data=output_dict)
<del> return get_template(query)
|
# module: backend.external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
+ max_repos: int = 100,
+ first: int = 100,
+ after: str = "",
+ ) -> UserCommitContributionsByRepositoryAPIResponse:
- ):
<0> max_repos: int = 100,
<1> first: int = 100,
<2> after: str = "",
<3> """Runs an individual query, fetching at most 100 days of history"""
<4> query = {
<5> "variables": {
<6> "login": user_id,
<7> "maxRepos": max_repos,
<8> "first": first,
<9> "after": after,
<10> },
<11> "query": """
<12> query getUser($login: String! $maxRepos: Int!, $first: Int!, $after: String!) {
<13> user(login: $login){
<14> contributionsCollection{
<15> commitContributionsByRepository(maxRepositories: $maxRepos){
<16> repository{
<17> name,
<18> },
<19> totalCount:contributions(first: 1){
<20> totalCount
<21> }
<22> contributions(first: $first, after: $after){
<23> nodes{
<24> commitCount,
<25> occurredAt,
<26> }
<27> pageInfo{
<28> hasNextPage,
<29> endCursor
<30> }
<31> }
<32> }
<33> },
<34> },
<35> }
<36> """,
<37> }
<38>
<39> try:
<40> return get_template(query)
<41> except Exception as e:
<42> logging.exception(e)
<43> raise e
<44>
|
===========unchanged ref 0===========
at: external.github_api.graphql.template
get_template(query: Dict[str, Any]) -> Dict[str, Any]
|
backend.processing.user.commit_contributions_by_repository/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
b5be3508d39f2ff7259368419b6edf768bee625a
|
updated processing logic
|
<1>:<add>
<add> time_range = today - start_date # gets number of days to end date
<add> segments = min(math.ceil(time_range / 100), 10) # no more than three years
<add> raw_output: List[CommitContributionsByRepository] = []
<del> output = []
<2>:<add> index, cont, after = 0, True, "" # initialize variables
<del> index, cont, after = 0, True, ""
<3>:<add> while cont and index < segments:
<del> while index < 10 and cont:
<10>:<del> data = data["data"]["user"]["contributionsCollection"][
<11>:<del> "commitContributionsByRepository"
<12>:<del> ]
<13>:<del>
<15>:<del> repo: Dict[str, Any]
<16>:<add> for i, repo in enumerate(data.data):
<del> for i, repo in enumerate(data):
<18>:<add> raw_output.append(
<del> output.append(
<19>:<add> CommitContributionsByRepository.parse_obj(
<add> {
<add> "name": repo.repository.name,
<add> "contributions": repo.total_count.total_count,
<add> "contributions_in_range": 0,
<add> "timeline": [],
<add> }
<add> )
<del> {
<20>:<del> "name": repo["repository"]["name"],
<21>:<del> "contributions": repo["totalCount"]["totalCount"],
<22>:<del> "timeline": [],
<23>:<del> }
<26>:<add> raw_contribs = repo.contributions.nodes
<del> raw_contribs = repo["contributions"]["nodes"]
<27>:<add> contribs =
|
<s>.processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
+ max_repos: int = 100,
- max_repos: Optional[int] = 10,
+ start_date: Date = today - 365,
- start_date: Optional[Date] = today - 365,
+ end_date: Date = today,
- end_date: Optional[Date] = today,
) -> List[CommitContributionsByRepository]:
<0> """Gets the daily contribution history for a users top x repositories"""
<1> output = []
<2> index, cont, after = 0, True, ""
<3> while index < 10 and cont:
<4> try:
<5> data = run_query(user_id, max_repos, after=after)
<6> except Exception as e:
<7> logging.exception(e)
<8> raise e
<9>
<10> data = data["data"]["user"]["contributionsCollection"][
<11> "commitContributionsByRepository"
<12> ]
<13>
<14> cont = False
<15> repo: Dict[str, Any]
<16> for i, repo in enumerate(data):
<17> if index == 0:
<18> output.append(
<19> {
<20> "name": repo["repository"]["name"],
<21> "contributions": repo["totalCount"]["totalCount"],
<22> "timeline": [],
<23> }
<24> )
<25>
<26> raw_contribs = repo["contributions"]["nodes"]
<27> contribs = map(lambda x: CommitContribution.parse_obj(x), raw_contribs)
<28> output[i]["timeline"].extend(contribs)
<29>
<30> if repo["contributions"]["pageInfo"]["hasNextPage"]:
<31> after = repo["contributions"]["pageInfo"]["endCursor"]
<32> cont = True
<33>
<34> index += 1
<35>
<36> output = list(map(lambda x: CommitContributionsByRepository.parse_obj(x), output))
<37> return output
<38>
|
===========unchanged ref 0===========
at: external.github_api.graphql.user
get_user_commit_contributions_by_repository(user_id: str, max_repos: int=100, first: int=100, after: str="") -> UserCommitContributionsByRepositoryAPIResponse
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: math
ceil(x: SupportsFloat, /) -> int
at: models.misc.date
Date(date: Union[str, datetime])
at: models.user.commit_contributions_by_repository.APIResponse
data: List[APIResponse_Repo]
at: models.user.commit_contributions_by_repository.APIResponse_Repo
repository: APIResponse_Repo_Repo
total_count: APIResponse_Repo_TotalCount = Field(alias="totalCount")
contributions: APIResponse_Repo_Contribs
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Contribs
nodes: List[APIResponse_Repo_Contribs_Nodes]
page_info: APIResponse_Repo_Contribs_PageInfo = Field(alias="pageInfo")
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Repo
name: str
at: models.user.commit_contributions_by_repository.APIResponse_Repo_TotalCount
total_count: int = Field(alias="totalCount")
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
+ max_repos: int = 100,
+ first: int = 100,
+ after: str = "",
+ ) -> UserCommitContributionsByRepositoryAPIResponse:
- ):
- max_repos: int = 100,
- first: int = 100,
- after: str = "",
"""Runs an individual query, fetching at most 100 days of history"""
query = {
"variables": {
"login": user_id,
"maxRepos": max_repos,
"first": first,
"after": after,
},
"query": """
query getUser($login: String! $maxRepos: Int!, $first: Int!, $after: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: $maxRepos){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: $first, after: $after){
nodes{
commitCount,
occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
},
}
""",
}
try:
+ output_dict = get_template(query)["data"]["user"]["contributionsCollection"][
+ "commitContributionsByRepository"
+ ]
+ return UserCommitContributionsByRepositoryAPIResponse(data=output_dict)
- return get_template(query)
except Exception as e:
logging.exception(e)
raise e
|
backend.external.github_api.graphql.user/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
5b845bda46456eb15c85c56a513e01da5e02f66c
|
add get_user_contribution_calendar
|
<9>:<add> query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
<del> query getUser($login: String! $maxRepos: Int!, $first: Int!, $after: String!) {
<10>:<add> user(login: $login){
<del> user(login: $login){
<11>:<add> contributionsCollection{
<del> contributionsCollection{
<12>:<add> commitContributionsByRepository(maxRepositories: $maxRepos){
<del> commitContributionsByRepository(maxRepositories: $maxRepos){
<13>:<add> repository{
<del> repository{
<14>:<add> name,
<del> name,
<15>:<add> },
<del> },
<16>:<add> totalCount:contributions(first: 1){
<del> totalCount:contributions(first: 1){
<17>:<add> totalCount
<del> totalCount
<18>:<add> }
<add> contributions(first: $first, after: $after){
<add> nodes{
<add> commitCount,
<add> occurredAt,
<19>:<del> contributions(first: $first, after: $after){
<20>:<del> nodes{
<21>:<del> commitCount,
<22>:<del> occurredAt,
<23>:<del> }
<24>:<add> pageInfo{
<del> pageInfo{
<25>:<add> hasNextPage,
<del> hasNextPage,
<26>:<add> endCursor
<del> endCursor
<27>:<del> }
<30>:<add> }
<del> },
<32>:<add> },
<del> }
<33>:<add> }
<add> """,
<del> """,
|
# module: backend.external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
first: int = 100,
after: str = "",
) -> UserCommitContributionsByRepositoryAPIResponse:
<0> """Runs an individual query, fetching at most 100 days of history"""
<1> query = {
<2> "variables": {
<3> "login": user_id,
<4> "maxRepos": max_repos,
<5> "first": first,
<6> "after": after,
<7> },
<8> "query": """
<9> query getUser($login: String! $maxRepos: Int!, $first: Int!, $after: String!) {
<10> user(login: $login){
<11> contributionsCollection{
<12> commitContributionsByRepository(maxRepositories: $maxRepos){
<13> repository{
<14> name,
<15> },
<16> totalCount:contributions(first: 1){
<17> totalCount
<18> }
<19> contributions(first: $first, after: $after){
<20> nodes{
<21> commitCount,
<22> occurredAt,
<23> }
<24> pageInfo{
<25> hasNextPage,
<26> endCursor
<27> }
<28> }
<29> }
<30> },
<31> },
<32> }
<33> """,
<34> }
<35>
<36> try:
<37> output_dict = get_template(query)["data"]["user"]["contributionsCollection"][
<38> "commitContributionsByRepository"
<39> ]
<40> return UserCommitContributionsByRepositoryAPIResponse(data=output_dict)
<41> except Exception as e:
<42> logging.exception(e)
<43> raise e
<44>
|
===========unchanged ref 0===========
at: external.github_api.graphql.template
get_template(query: Dict[str, Any]) -> Dict[str, Any]
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
|
backend.main/get_user
|
Modified
|
avgupta456~github-trends
|
6543fac6963ed315a395e54b37fd7ac438c48714
|
misc
|
<0>:<add> return _get_user(user_id)
<del> return list(map(lambda x: x.dict(), _get_user(user_id)))
|
# module: backend.main
@app.get("/user/{user_id}", status_code=status.HTTP_200_OK)
@fail_gracefully
def get_user(response: Response, user_id: str) -> List[Dict[str, Any]]:
<0> return list(map(lambda x: x.dict(), _get_user(user_id)))
<1>
|
===========unchanged ref 0===========
at: backend.main
app = FastAPI()
fail_gracefully(func: Callable[..., Any])
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.processing.user.commit_contributions_by_repository/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
045d61ba3d89401b20c45b8ea50b8ed0eff4b120
|
add external contribution_calendar classes
|
<1>:<del>
<10>:<del> logging.exception(e)
|
# module: backend.processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> List[CommitContributionsByRepository]:
<0> """Gets the daily contribution history for a users top x repositories"""
<1>
<2> time_range = today - start_date # gets number of days to end date
<3> segments = min(math.ceil(time_range / 100), 10) # no more than three years
<4> raw_output: List[CommitContributionsByRepository] = []
<5> index, cont, after = 0, True, "" # initialize variables
<6> while cont and index < segments:
<7> try:
<8> data = run_query(user_id, max_repos, after=after)
<9> except Exception as e:
<10> logging.exception(e)
<11> raise e
<12>
<13> cont = False
<14> for i, repo in enumerate(data.data):
<15> if index == 0:
<16> raw_output.append(
<17> CommitContributionsByRepository.parse_obj(
<18> {
<19> "name": repo.repository.name,
<20> "contributions": repo.total_count.total_count,
<21> "contributions_in_range": 0,
<22> "timeline": [],
<23> }
<24> )
<25> )
<26>
<27> raw_contribs = repo.contributions.nodes
<28> contribs = map(
<29> lambda x: CommitContribution.parse_obj(
<30> {
<31> "commit_count": x.commit_count,
<32> "occurred_at": Date(x.occurred_at),
<33> }
<34> ),
<35> raw_contribs,
<36> )
<37> contribs = filter(
<38> lambda x: start_date <= x.occurred_at <= end_date, contribs
<39> )
<40> raw_output[i].timeline.extend(contribs)
<41>
<42> </s>
|
===========below chunk 0===========
# module: backend.processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> List[CommitContributionsByRepository]:
# offset: 1
after = repo.contributions.page_info.end_cursor
cont = True
index += 1
# adds contributionsInRange
for repo in raw_output:
repo.contributions_in_range = sum([x.commit_count for x in repo.timeline])
# converts to objects
output_objects = map(
lambda x: CommitContributionsByRepository.parse_obj(x), raw_output
)
# filters out empty results
output_objects = filter(lambda x: x.contributions_in_range > 0, output_objects)
return list(output_objects)
===========unchanged ref 0===========
at: external.github_api.graphql.user
get_user_commit_contributions_by_repository(user_id: str, max_repos: int=100, first: int=100, after: str="") -> UserCommitContributionsByRepositoryAPIResponse
at: math
ceil(x: SupportsFloat, /) -> int
at: models.misc.date
Date(date: Union[str, datetime])
at: models.user.commit_contributions_by_repository.APIResponse
data: List[APIResponse_Repo]
at: models.user.commit_contributions_by_repository.APIResponse_Repo
repository: APIResponse_Repo_Repo
total_count: APIResponse_Repo_TotalCount = Field(alias="totalCount")
contributions: APIResponse_Repo_Contribs
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Contribs
nodes: List[APIResponse_Repo_Contribs_Nodes]
page_info: APIResponse_Repo_Contribs_PageInfo = Field(alias="pageInfo")
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Contribs_PageInfo
has_next_page: bool = Field(alias="hasNextPage")
end_cursor: str = Field(alias="endCursor")
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Repo
name: str
at: models.user.commit_contributions_by_repository.APIResponse_Repo_TotalCount
total_count: int = Field(alias="totalCount")
at: models.user.commit_contributions_by_repository.CommitContribution
commit_count: int
occurred_at: Date
at: models.user.commit_contributions_by_repository.CommitContributionsByRepository
name: str
contributions: int
contributions_in_range: int
at: typing
List = _alias(list, 1, inst=False, name='List')
|
backend.processing.user.contribution_calendar/get_user_contribution_calendar
|
Modified
|
avgupta456~github-trends
|
9cb59d2082c523211667331028db4f30fb846404
|
upgrade contribution_calendar processing (months and weekdays)
|
<30>:<add> # creates total period (up to 1 year long)
<add> total = ContributionPeriod(
<add> days=days,
<add> num_days=len(days),
<add> total_contributions=total_contributions,
<add> avg_contributions=total_contributions / len(days),
<add> )
<add>
<add> # creates months (0 is January, 11 is December)
<add> months = [[] for _ in range(12)]
<add> for day in days:
<add> months[day.date.month() - 1].append(day)
<add>
<add> months = list(
<add> map(
<add> lambda x: ContributionPeriod(
<add> days=x,
<add> num_days=len(x),
<add> total_contributions=sum([y.contribution_count for y in x]),
<add> avg_contributions=sum([y.contribution_count for y in x]) / len(x),
|
# module: backend.processing.user.contribution_calendar
def get_user_contribution_calendar(
user_id: str,
start_date: Date = today - 365,
end_date: Date = today,
) -> ContributionCalendar:
<0> """get user contributions for the past year"""
<1> if today - start_date > 365:
<2> raise AssertionError("start_date can only be within past 1 year")
<3>
<4> try:
<5> data = run_query(user_id)
<6> except Exception as e:
<7> raise e
<8>
<9> contribution_years = data.contribution_years
<10> total_contributions = data.contribution_calendar.total_contributions
<11> colors = data.contribution_calendar.colors
<12> days = list(
<13> map(
<14> lambda x: ContributionDay.parse_obj(
<15> {
<16> "date": Date(x.date),
<17> "weekday": x.weekday,
<18> "contribution_count": x.contribution_count,
<19> "contribution_level": x.contribution_level,
<20> }
<21> ),
<22> [
<23> day
<24> for week in data.contribution_calendar.weeks
<25> for day in week.contribution_days
<26> ],
<27> )
<28> )
<29>
<30> calendar = ContributionCalendar(
<31> contribution_years=contribution_years,
<32> total_contributions=total_contributions,
<33> colors=colors,
<34> days=days,
<35> )
<36>
<37> return calendar
<38>
|
===========unchanged ref 0===========
at: external.github_api.graphql.user
get_user_contribution_calendar(user_id: str) -> UserContributionCalendar
at: models.misc.date
Date(date: Union[str, datetime])
at: models.user.contribution_calendar.APIResponse
contribution_calendar: APIResponse_Calendar = Field(alias="contributionCalendar")
contribution_years: List[int] = Field(alias="contributionYears")
at: models.user.contribution_calendar.APIResponse_Calendar
total_contributions: int = Field(alias="totalContributions")
weeks: List[APIResponse_Calendar_Week]
colors: List[str]
===========changed ref 0===========
# module: backend.models.misc.date
class Date:
+ def day(self) -> int:
+ return self.date_obj.day
+
===========changed ref 1===========
# module: backend.models.misc.date
class Date:
+ def month(self) -> int:
+ return self.date_obj.month
+
===========changed ref 2===========
# module: backend.models.misc.date
class Date:
+ def year(self) -> int:
+ return self.date_obj.year
+
===========changed ref 3===========
# module: backend.models.user.contribution_calendar
+ class ContributionPeriod(BaseModel):
+ """
+ BaseModel which accepts:
+ - total_contributions: int
+ - avg_contributions: float
+ - days: List[ContributionDay]
+ """
+
+ total_contributions: int
+ avg_contributions: float
+ days: List[ContributionDay]
+ num_days: int
+
===========changed ref 4===========
# module: backend.models.user.contribution_calendar
class ContributionCalendar(BaseModel):
"""
BaseModel which accepts:
- - contribution_years: List[int]
- total_contributions: int
- colors: List[str]
+ - total: ContributionPeriod
+ - months: List[ContributionPeriod]
+ - weekdays: List[ContributionPeriod]
- - days: List[ContributionDay]
"""
contribution_years: List[int]
- total_contributions: int
colors: List[str]
+ total: ContributionPeriod
+ months: List[ContributionPeriod]
+ weekdays: List[ContributionPeriod]
- days: List[ContributionDay]
|
backend.processing.user.commit_contributions_by_repository/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
ba54905a19d4076422c9a501630262675044ed75
|
use create_model functions
|
<27>:<add> lambda x: create_commit_contribution(x),
<del> lambda x: CommitContribution.parse_obj(
<28>:<del> {
<29>:<del> "commit_count": x.commit_count,
<30>:<del> "occurred_at": Date(x.occurred_at),
<31>:<del> }
<32>:<del> ),
|
# module: backend.processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> List[CommitContributionsByRepository]:
<0> """Gets the daily contribution history for a users top x repositories"""
<1> time_range = today - start_date # gets number of days to end date
<2> segments = min(math.ceil(time_range / 100), 10) # no more than three years
<3> raw_output: List[CommitContributionsByRepository] = []
<4> index, cont, after = 0, True, "" # initialize variables
<5> while cont and index < segments:
<6> try:
<7> data = run_query(user_id, max_repos, after=after)
<8> except Exception as e:
<9> raise e
<10>
<11> cont = False
<12> for i, repo in enumerate(data.data):
<13> if index == 0:
<14> raw_output.append(
<15> CommitContributionsByRepository.parse_obj(
<16> {
<17> "name": repo.repository.name,
<18> "contributions": repo.total_count.total_count,
<19> "contributions_in_range": 0,
<20> "timeline": [],
<21> }
<22> )
<23> )
<24>
<25> raw_contribs = repo.contributions.nodes
<26> contribs = map(
<27> lambda x: CommitContribution.parse_obj(
<28> {
<29> "commit_count": x.commit_count,
<30> "occurred_at": Date(x.occurred_at),
<31> }
<32> ),
<33> raw_contribs,
<34> )
<35> contribs = filter(
<36> lambda x: start_date <= x.occurred_at <= end_date, contribs
<37> )
<38> raw_output[i].timeline.extend(contribs)
<39>
<40> if repo.contributions.page_info.has</s>
|
===========below chunk 0===========
# module: backend.processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> List[CommitContributionsByRepository]:
# offset: 1
after = repo.contributions.page_info.end_cursor
cont = True
index += 1
# adds contributionsInRange
for repo in raw_output:
repo.contributions_in_range = sum([x.commit_count for x in repo.timeline])
# converts to objects
output_objects = map(
lambda x: CommitContributionsByRepository.parse_obj(x), raw_output
)
# filters out empty results
output_objects = filter(lambda x: x.contributions_in_range > 0, output_objects)
return list(output_objects)
===========unchanged ref 0===========
at: external.github_api.graphql.user
get_user_commit_contributions_by_repository(user_id: str, max_repos: int=100, first: int=100, after: str="") -> UserCommitContributionsByRepositoryAPIResponse
at: math
ceil(x: SupportsFloat, /) -> int
at: models.misc.date
Date(date: Union[str, datetime])
at: models.user.commit_contributions_by_repository
create_commit_contribution(x: APIResponse_Repo_Contribs_Node) -> CommitContribution
at: models.user.commit_contributions_by_repository.APIResponse
data: List[APIResponse_Repo]
at: models.user.commit_contributions_by_repository.APIResponse_Repo
repository: APIResponse_Repo_Repo
total_count: APIResponse_Repo_TotalCount = Field(alias="totalCount")
contributions: APIResponse_Repo_Contribs
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Contribs
nodes: List[APIResponse_Repo_Contribs_Node]
page_info: APIResponse_Repo_Contribs_PageInfo = Field(alias="pageInfo")
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Contribs_PageInfo
has_next_page: bool = Field(alias="hasNextPage")
end_cursor: str = Field(alias="endCursor")
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Repo
name: str
at: models.user.commit_contributions_by_repository.APIResponse_Repo_TotalCount
total_count: int = Field(alias="totalCount")
at: models.user.commit_contributions_by_repository.CommitContribution
commit_count: int
occurred_at: Date
at: models.user.commit_contributions_by_repository.CommitContributionsByRepository
name: str
contributions: int
===========unchanged ref 1===========
contributions_in_range: int
at: typing
List = _alias(list, 1, inst=False, name='List')
|
backend.processing.user.contribution_calendar/get_user_contribution_calendar
|
Modified
|
avgupta456~github-trends
|
ba54905a19d4076422c9a501630262675044ed75
|
use create_model functions
|
<10>:<del> total_contributions = data.contribution_calendar.total_contributions
<31>:<add> total = create_contribution_period(days)
<del> total = ContributionPeriod(
<32>:<del> days=days,
<33>:<del> num_days=len(days),
<34>:<del> total_contributions=total_contributions,
<35>:<del> avg_contributions=total_contributions / len(days),
<36>:<del> )
<43>:<del> months = list(
<44>:<del> map(
<45>:<del> lambda x: ContributionPeriod(
<46>:<del> days=x,
<47>:<del> num_days=len(x),
<48>:<del> total_
|
# module: backend.processing.user.contribution_calendar
def get_user_contribution_calendar(
user_id: str,
start_date: Date = today - 365,
end_date: Date = today,
) -> ContributionCalendar:
<0> """get user contributions for the past year"""
<1> if today - start_date > 365:
<2> raise AssertionError("start_date can only be within past 1 year")
<3>
<4> try:
<5> data = run_query(user_id)
<6> except Exception as e:
<7> raise e
<8>
<9> contribution_years = data.contribution_years
<10> total_contributions = data.contribution_calendar.total_contributions
<11> colors = data.contribution_calendar.colors
<12> days = list(
<13> map(
<14> lambda x: ContributionDay.parse_obj(
<15> {
<16> "date": Date(x.date),
<17> "weekday": x.weekday,
<18> "contribution_count": x.contribution_count,
<19> "contribution_level": x.contribution_level,
<20> }
<21> ),
<22> [
<23> day
<24> for week in data.contribution_calendar.weeks
<25> for day in week.contribution_days
<26> ],
<27> )
<28> )
<29>
<30> # creates total period (up to 1 year long)
<31> total = ContributionPeriod(
<32> days=days,
<33> num_days=len(days),
<34> total_contributions=total_contributions,
<35> avg_contributions=total_contributions / len(days),
<36> )
<37>
<38> # creates months (0 is January, 11 is December)
<39> months = [[] for _ in range(12)]
<40> for day in days:
<41> months[day.date.month() - 1].append(day)
<42>
<43> months = list(
<44> map(
<45> lambda x: ContributionPeriod(
<46> days=x,
<47> num_days=len(x),
<48> total_</s>
|
===========below chunk 0===========
# module: backend.processing.user.contribution_calendar
def get_user_contribution_calendar(
user_id: str,
start_date: Date = today - 365,
end_date: Date = today,
) -> ContributionCalendar:
# offset: 1
avg_contributions=sum([y.contribution_count for y in x]) / len(x),
),
months,
)
)
# create weekdays (0 is Sunday, 6 is Saturday)
weekdays = [[] for _ in range(7)]
for day in days:
weekdays[day.weekday].append(day)
weekdays = list(
map(
lambda x: ContributionPeriod(
days=x,
num_days=len(x),
total_contributions=sum([y.contribution_count for y in x]),
avg_contributions=sum([y.contribution_count for y in x]) / len(x),
),
weekdays,
)
)
# create final output
calendar = ContributionCalendar(
contribution_years=contribution_years,
colors=colors,
total=total,
months=months,
weekdays=weekdays,
)
return calendar
===========unchanged ref 0===========
at: external.github_api.graphql.user
get_user_contribution_calendar(user_id: str) -> UserContributionCalendar
at: models.misc.date
Date(date: Union[str, datetime])
at: models.user.contribution_calendar
create_contribution_period(days: List[ContributionDay]) -> ContributionPeriod
at: models.user.contribution_calendar.APIResponse
contribution_calendar: APIResponse_Calendar = Field(alias="contributionCalendar")
contribution_years: List[int] = Field(alias="contributionYears")
at: models.user.contribution_calendar.APIResponse_Calendar
total_contributions: int = Field(alias="totalContributions")
weeks: List[APIResponse_Calendar_Week]
colors: List[str]
===========changed ref 0===========
# module: backend.processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> List[CommitContributionsByRepository]:
"""Gets the daily contribution history for a users top x repositories"""
time_range = today - start_date # gets number of days to end date
segments = min(math.ceil(time_range / 100), 10) # no more than three years
raw_output: List[CommitContributionsByRepository] = []
index, cont, after = 0, True, "" # initialize variables
while cont and index < segments:
try:
data = run_query(user_id, max_repos, after=after)
except Exception as e:
raise e
cont = False
for i, repo in enumerate(data.data):
if index == 0:
raw_output.append(
CommitContributionsByRepository.parse_obj(
{
"name": repo.repository.name,
"contributions": repo.total_count.total_count,
"contributions_in_range": 0,
"timeline": [],
}
)
)
raw_contribs = repo.contributions.nodes
contribs = map(
+ lambda x: create_commit_contribution(x),
- lambda x: CommitContribution.parse_obj(
- {
- "commit_count": x.commit_count,
- "occurred_at": Date(x.occurred_at),
- }
- ),
raw_contribs,
)
contribs = filter(
lambda x: start_date <= x.occurred_at <= end_date, contribs
)
raw_output[i].timeline.extend(contribs)
if repo.contributions.page_info.has_next_page:
after = repo.contributions.page_info.end_</s>
===========changed ref 1===========
# module: backend.processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> List[CommitContributionsByRepository]:
# offset: 1
<s> repo.contributions.page_info.has_next_page:
after = repo.contributions.page_info.end_cursor
cont = True
index += 1
# adds contributionsInRange
for repo in raw_output:
repo.contributions_in_range = sum([x.commit_count for x in repo.timeline])
# converts to objects
output_objects = map(
lambda x: CommitContributionsByRepository.parse_obj(x), raw_output
)
# filters out empty results
output_objects = filter(lambda x: x.contributions_in_range > 0, output_objects)
return list(output_objects)
|
backend.external.github_api.graphql.template/get_template
|
Modified
|
avgupta456~github-trends
|
0135f48191612537ba0320938cdf2017315777fa
|
pass env var to github action
|
<1>:<add> token = os.getenv("AUTH_TOKEN", "")
<del> token = os.getenv("GITHUB_TOKEN", "")
|
# module: backend.external.github_api.graphql.template
def get_template(query: Dict[str, Any]) -> Dict[str, Any]:
<0> """Template for interacting with the GitHub GraphQL API"""
<1> token = os.getenv("GITHUB_TOKEN", "")
<2> headers: Dict[str, str] = {"Authorization": "bearer " + token}
<3> start = datetime.now()
<4> r = s.post( # type: ignore
<5> "https://api.github.com/graphql", json=query, headers=headers
<6> )
<7> print("GraphQL", datetime.now() - start)
<8> if r.status_code == 200:
<9> return r.json() # type: ignore
<10> else:
<11> raise GraphQlError(
<12> "Invalid status code "
<13> + str(r.status_code)
<14> + ": "
<15> + str(r.json()["message"]) # type: ignore
<16> + " Documentation at "
<17> + str(r.json()["documentation_url"]) # type: ignore
<18> )
<19>
|
===========unchanged ref 0===========
at: backend.external.github_api.graphql.template
s = requests.session()
GraphQlError(*args: object)
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: os
getenv(key: str, default: _T) -> Union[str, _T]
getenv(key: str) -> Optional[str]
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.models.Response.__init__
self.status_code = None
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.external.github_api.graphql.user/get_user
|
Modified
|
avgupta456~github-trends
|
b74bae35e894bb1ec57b2dc4fad507fa4bd35abe
|
styling
|
<4>:<add> query getUser($login: String!) {
<del> query getUser($login: String!) {
<17>:<add> occurredAt,
<del> occurredAt,
|
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
<0> """gets all user data from graphql"""
<1> query = {
<2> "variables": {"login": user_id},
<3> "query": """
<4> query getUser($login: String!) {
<5> user(login: $login){
<6> contributionsCollection{
<7> commitContributionsByRepository(maxRepositories: 10){
<8> repository{
<9> name,
<10> },
<11> totalCount:contributions(first: 1){
<12> totalCount
<13> }
<14> contributions(first: 100){
<15> nodes{
<16> commitCount,
<17> occurredAt,
<18> }
<19> pageInfo{
<20> hasNextPage,
<21> endCursor
<22> }
<23> }
<24> }
<25> },
<26> contributionCalendar{
<27> totalContributions,
<28> weeks{
<29> contributionDays{
<30> date,
<31> weekday,
<32> contributionCount,
<33> contributionLevel,
<34> }
<35> }
<36> colors,
<37> }
<38> contributionYears,
<39> issueContributions(first: 10){
<40> totalCount,
<41> nodes{
<42> occurredAt,
<43> issue{
<44> state
<45> }
<46> }
<47> }
<48> issueContributionsByRepository(maxRepositories: 10){
<49> repository{
<50> name
<51> },
<52> contributions(first: 10){
<53> totalCount,
<54> nodes{
<55> occurredAt,
<56> issue{
<57> state
<58> }
<59> }
<60> }
<61> }
<62> pullRequestContributions(first: 10){
<63> totalCount,
<64> nodes{
<65> occurredAt,
<66> pullRequest{
<67> state
<68> }
<69> }
<70> }
<71> pullRequestContributionsByRepository(maxRepositories:10){
<72> repository{
<73> name
<74> },
<75> contributions(first:10){
<76> totalCount,
<77> nodes{
<78> occurred</s>
|
===========below chunk 0===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
# offset: 1
pullRequest{
state,
}
}
}
}
pullRequestReviewContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state,
}
}
}
},
repositoryContributions(first:10){
totalCount,
nodes{
repository{
name,
}
occurredAt,
}
},
restrictedContributionsCount,
totalCommitContributions,
totalIssueContributions,
totalPullRequestContributions,
totalPullRequestReviewContributions,
totalRepositoryContributions,
totalRepositoriesWithContributedCommits,
totalRepositoriesWithContributedIssues,
totalRepositoriesWithContributedPullRequests,
totalRepositoriesWithContributedPullRequestReviews
},
followers(first:10){
totalCount,
nodes{
name,
url,
}
}
following(first:10){
totalCount,
nodes{
name,
url,
}
}
}
}
""",
}
try:
return get_template(query)
except Exception as e:
logging.exception(e)
raise e
===========unchanged ref 0===========
at: external.github_api.graphql.template
get_template(query: Dict[str, Any]) -> Dict[str, Any]
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
|
backend.external.github_api.graphql.user/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
b74bae35e894bb1ec57b2dc4fad507fa4bd35abe
|
styling
|
<9>:<add> query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
<del> query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
<22>:<add> occurredAt,
<del> occurredAt,
|
# module: backend.external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
first: int = 100,
after: str = "",
) -> UserCommitContributionsByRepositoryAPIResponse:
<0> """Runs an individual query, fetching at most 100 days of history"""
<1> query = {
<2> "variables": {
<3> "login": user_id,
<4> "maxRepos": max_repos,
<5> "first": first,
<6> "after": after,
<7> },
<8> "query": """
<9> query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
<10> user(login: $login){
<11> contributionsCollection{
<12> commitContributionsByRepository(maxRepositories: $maxRepos){
<13> repository{
<14> name,
<15> },
<16> totalCount:contributions(first: 1){
<17> totalCount
<18> }
<19> contributions(first: $first, after: $after){
<20> nodes{
<21> commitCount,
<22> occurredAt,
<23> }
<24> pageInfo{
<25> hasNextPage,
<26> endCursor
<27> }
<28> }
<29> }
<30> },
<31> },
<32> }
<33> """,
<34> }
<35>
<36> try:
<37> output_dict = get_template(query)["data"]["user"]["contributionsCollection"][
<38> "commitContributionsByRepository"
<39> ]
<40> return UserCommitContributionsByRepositoryAPIResponse(data=output_dict)
<41> except Exception as e:
<42> logging.exception(e)
<43> raise e
<44>
|
===========unchanged ref 0===========
at: external.github_api.graphql.template
get_template(query: Dict[str, Any]) -> Dict[str, Any]
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
"""gets all user data from graphql"""
query = {
"variables": {"login": user_id},
"query": """
+ query getUser($login: String!) {
- query getUser($login: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: 10){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: 100){
nodes{
commitCount,
+ occurredAt,
- occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
contributionCalendar{
totalContributions,
weeks{
contributionDays{
date,
weekday,
contributionCount,
contributionLevel,
}
}
colors,
}
contributionYears,
issueContributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
issueContributionsByRepository(maxRepositories: 10){
repository{
name
},
contributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
}
pullRequestContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequest{
state
}
}
}
pullRequestContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequest{
state,
}
}
}
}
pullRequestReviewContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}</s>
===========changed ref 1===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
# offset: 1
<s>(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state,
}
}
}
},
repositoryContributions(first:10){
totalCount,
nodes{
repository{
name,
}
occurredAt,
}
},
restrictedContributionsCount,
totalCommitContributions,
totalIssueContributions,
totalPullRequestContributions,
totalPullRequestReviewContributions,
totalRepositoryContributions,
totalRepositoriesWithContributedCommits,
totalRepositoriesWithContributedIssues,
totalRepositoriesWithContributedPullRequests,
totalRepositoriesWithContributedPullRequestReviews
},
followers(first:10){
totalCount,
nodes{
name,
url,
}
}
following(first:10){
totalCount,
nodes{
name,
url,
}
}
}
}
""",
}
try:
return get_template(query)
except Exception as e:
logging.exception(e)
raise e
|
backend.external.github_api.graphql.user/get_user_contribution_calendar
|
Modified
|
avgupta456~github-trends
|
b74bae35e894bb1ec57b2dc4fad507fa4bd35abe
|
styling
|
<4>:<add> query getUser($login: String!) {
<del> query getUser($login: String!) {
|
# module: backend.external.github_api.graphql.user
def get_user_contribution_calendar(user_id: str) -> UserContributionCalendar:
<0> """Fetches user contribution calendar and contribution years"""
<1> query = {
<2> "variables": {"login": user_id},
<3> "query": """
<4> query getUser($login: String!) {
<5> user(login: $login){
<6> contributionsCollection{
<7> contributionCalendar{
<8> totalContributions,
<9> weeks{
<10> contributionDays{
<11> date,
<12> weekday,
<13> contributionCount,
<14> contributionLevel,
<15> }
<16> }
<17> colors,
<18> }
<19> contributionYears,
<20> }
<21> },
<22> }
<23> """,
<24> }
<25>
<26> try:
<27> output_dict = get_template(query)["data"]["user"]["contributionsCollection"]
<28> return UserContributionCalendar.parse_obj(output_dict)
<29> except Exception as e:
<30> logging.exception(e)
<31> raise e
<32>
|
===========unchanged ref 0===========
at: external.github_api.graphql.template
get_template(query: Dict[str, Any]) -> Dict[str, Any]
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: backend.external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
first: int = 100,
after: str = "",
) -> UserCommitContributionsByRepositoryAPIResponse:
"""Runs an individual query, fetching at most 100 days of history"""
query = {
"variables": {
"login": user_id,
"maxRepos": max_repos,
"first": first,
"after": after,
},
"query": """
+ query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
- query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: $maxRepos){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: $first, after: $after){
nodes{
commitCount,
+ occurredAt,
- occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
},
}
""",
}
try:
output_dict = get_template(query)["data"]["user"]["contributionsCollection"][
"commitContributionsByRepository"
]
return UserCommitContributionsByRepositoryAPIResponse(data=output_dict)
except Exception as e:
logging.exception(e)
raise e
===========changed ref 1===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
"""gets all user data from graphql"""
query = {
"variables": {"login": user_id},
"query": """
+ query getUser($login: String!) {
- query getUser($login: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: 10){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: 100){
nodes{
commitCount,
+ occurredAt,
- occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
contributionCalendar{
totalContributions,
weeks{
contributionDays{
date,
weekday,
contributionCount,
contributionLevel,
}
}
colors,
}
contributionYears,
issueContributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
issueContributionsByRepository(maxRepositories: 10){
repository{
name
},
contributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
}
pullRequestContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequest{
state
}
}
}
pullRequestContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequest{
state,
}
}
}
}
pullRequestReviewContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}</s>
===========changed ref 2===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
# offset: 1
<s>(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state,
}
}
}
},
repositoryContributions(first:10){
totalCount,
nodes{
repository{
name,
}
occurredAt,
}
},
restrictedContributionsCount,
totalCommitContributions,
totalIssueContributions,
totalPullRequestContributions,
totalPullRequestReviewContributions,
totalRepositoryContributions,
totalRepositoriesWithContributedCommits,
totalRepositoriesWithContributedIssues,
totalRepositoriesWithContributedPullRequests,
totalRepositoriesWithContributedPullRequestReviews
},
followers(first:10){
totalCount,
nodes{
name,
url,
}
}
following(first:10){
totalCount,
nodes{
name,
url,
}
}
}
}
""",
}
try:
return get_template(query)
except Exception as e:
logging.exception(e)
raise e
|
backend.tests.external.github_api.graphql.test_template/TestTemplate.test_get_template
|
Modified
|
avgupta456~github-trends
|
b74bae35e894bb1ec57b2dc4fad507fa4bd35abe
|
styling
|
<3>:<add> query getUser($login: String!) {
<del> query getUser($login: String!) {
|
# module: backend.tests.external.github_api.graphql.test_template
class TestTemplate(unittest.TestCase):
def test_get_template(self):
<0> query = {
<1> "variables": {"login": "avgupta456"},
<2> "query": """
<3> query getUser($login: String!) {
<4> user(login: $login){
<5> contributionsCollection{
<6> contributionCalendar{
<7> totalContributions
<8> }
<9> }
<10> }
<11> }
<12> """,
<13> }
<14> response = get_template(query)
<15>
<16> self.assertIn("data", response)
<17> data = response["data"]
<18> self.assertIn("user", data)
<19> user = data["user"]
<20> self.assertIn("contributionsCollection", user)
<21> contributionsCollection = user["contributionsCollection"]
<22> self.assertIn("contributionCalendar", contributionsCollection)
<23> contributionCalendar = contributionsCollection["contributionCalendar"]
<24> self.assertIn("totalContributions", contributionCalendar)
<25> totalContributions = contributionCalendar["totalContributions"]
<26> self.assertGreater(totalContributions, 0)
<27>
|
===========changed ref 0===========
# module: backend.external.github_api.graphql.user
def get_user_contribution_calendar(user_id: str) -> UserContributionCalendar:
"""Fetches user contribution calendar and contribution years"""
query = {
"variables": {"login": user_id},
"query": """
+ query getUser($login: String!) {
- query getUser($login: String!) {
user(login: $login){
contributionsCollection{
contributionCalendar{
totalContributions,
weeks{
contributionDays{
date,
weekday,
contributionCount,
contributionLevel,
}
}
colors,
}
contributionYears,
}
},
}
""",
}
try:
output_dict = get_template(query)["data"]["user"]["contributionsCollection"]
return UserContributionCalendar.parse_obj(output_dict)
except Exception as e:
logging.exception(e)
raise e
===========changed ref 1===========
# module: backend.external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
first: int = 100,
after: str = "",
) -> UserCommitContributionsByRepositoryAPIResponse:
"""Runs an individual query, fetching at most 100 days of history"""
query = {
"variables": {
"login": user_id,
"maxRepos": max_repos,
"first": first,
"after": after,
},
"query": """
+ query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
- query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: $maxRepos){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: $first, after: $after){
nodes{
commitCount,
+ occurredAt,
- occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
},
}
""",
}
try:
output_dict = get_template(query)["data"]["user"]["contributionsCollection"][
"commitContributionsByRepository"
]
return UserCommitContributionsByRepositoryAPIResponse(data=output_dict)
except Exception as e:
logging.exception(e)
raise e
===========changed ref 2===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
"""gets all user data from graphql"""
query = {
"variables": {"login": user_id},
"query": """
+ query getUser($login: String!) {
- query getUser($login: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: 10){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: 100){
nodes{
commitCount,
+ occurredAt,
- occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
contributionCalendar{
totalContributions,
weeks{
contributionDays{
date,
weekday,
contributionCount,
contributionLevel,
}
}
colors,
}
contributionYears,
issueContributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
issueContributionsByRepository(maxRepositories: 10){
repository{
name
},
contributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
}
pullRequestContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequest{
state
}
}
}
pullRequestContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequest{
state,
}
}
}
}
pullRequestReviewContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}</s>
===========changed ref 3===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
# offset: 1
<s>(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state,
}
}
}
},
repositoryContributions(first:10){
totalCount,
nodes{
repository{
name,
}
occurredAt,
}
},
restrictedContributionsCount,
totalCommitContributions,
totalIssueContributions,
totalPullRequestContributions,
totalPullRequestReviewContributions,
totalRepositoryContributions,
totalRepositoriesWithContributedCommits,
totalRepositoriesWithContributedIssues,
totalRepositoriesWithContributedPullRequests,
totalRepositoriesWithContributedPullRequestReviews
},
followers(first:10){
totalCount,
nodes{
name,
url,
}
}
following(first:10){
totalCount,
nodes{
name,
url,
}
}
}
}
""",
}
try:
return get_template(query)
except Exception as e:
logging.exception(e)
raise e
|
backend.external.github_api.graphql.repo/get_repo
|
Modified
|
avgupta456~github-trends
|
b74bae35e894bb1ec57b2dc4fad507fa4bd35abe
|
styling
|
<4>:<add> query getRepo($owner: String!, $repo: String!) {
<del> query getRepo($owner: String!, $repo: String!) {
<5>:<add> repository(owner: $owner, name: $repo) {
<del> repository(owner: $owner, name: $repo) {
|
# module: backend.external.github_api.graphql.repo
def get_repo(owner: str, repo: str) -> Dict[str, Any]:
<0> """gets all repository data from graphql"""
<1> query = {
<2> "variables": {"owner": owner, "repo": repo},
<3> "query": """
<4> query getRepo($owner: String!, $repo: String!) {
<5> repository(owner: $owner, name: $repo) {
<6> createdAt,
<7> updatedAt,
<8> forkCount,
<9> forks(first: 10){
<10> nodes{
<11> createdAt,
<12> },
<13> },
<14> stargazerCount,
<15> stargazers(first: 10){
<16> nodes{
<17> createdAt,
<18> },
<19> },
<20> primaryLanguage{
<21> name
<22> },
<23> languages(first: 5){
<24> totalCount,
<25> totalSize,
<26> edges{
<27> node {
<28> name,
<29> },
<30> size,
<31> },
<32> },
<33> }
<34> }
<35> """,
<36> }
<37>
<38> return get_template(query)
<39>
|
===========unchanged ref 0===========
at: external.github_api.graphql.template
get_template(query: Dict[str, Any]) -> Dict[str, Any]
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.external.github_api.graphql.user
def get_user_contribution_calendar(user_id: str) -> UserContributionCalendar:
"""Fetches user contribution calendar and contribution years"""
query = {
"variables": {"login": user_id},
"query": """
+ query getUser($login: String!) {
- query getUser($login: String!) {
user(login: $login){
contributionsCollection{
contributionCalendar{
totalContributions,
weeks{
contributionDays{
date,
weekday,
contributionCount,
contributionLevel,
}
}
colors,
}
contributionYears,
}
},
}
""",
}
try:
output_dict = get_template(query)["data"]["user"]["contributionsCollection"]
return UserContributionCalendar.parse_obj(output_dict)
except Exception as e:
logging.exception(e)
raise e
===========changed ref 1===========
# module: backend.tests.external.github_api.graphql.test_template
class TestTemplate(unittest.TestCase):
def test_get_template(self):
query = {
"variables": {"login": "avgupta456"},
"query": """
+ query getUser($login: String!) {
- query getUser($login: String!) {
user(login: $login){
contributionsCollection{
contributionCalendar{
totalContributions
}
}
}
}
""",
}
response = get_template(query)
self.assertIn("data", response)
data = response["data"]
self.assertIn("user", data)
user = data["user"]
self.assertIn("contributionsCollection", user)
contributionsCollection = user["contributionsCollection"]
self.assertIn("contributionCalendar", contributionsCollection)
contributionCalendar = contributionsCollection["contributionCalendar"]
self.assertIn("totalContributions", contributionCalendar)
totalContributions = contributionCalendar["totalContributions"]
self.assertGreater(totalContributions, 0)
===========changed ref 2===========
# module: backend.external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
first: int = 100,
after: str = "",
) -> UserCommitContributionsByRepositoryAPIResponse:
"""Runs an individual query, fetching at most 100 days of history"""
query = {
"variables": {
"login": user_id,
"maxRepos": max_repos,
"first": first,
"after": after,
},
"query": """
+ query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
- query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: $maxRepos){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: $first, after: $after){
nodes{
commitCount,
+ occurredAt,
- occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
},
}
""",
}
try:
output_dict = get_template(query)["data"]["user"]["contributionsCollection"][
"commitContributionsByRepository"
]
return UserCommitContributionsByRepositoryAPIResponse(data=output_dict)
except Exception as e:
logging.exception(e)
raise e
===========changed ref 3===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
"""gets all user data from graphql"""
query = {
"variables": {"login": user_id},
"query": """
+ query getUser($login: String!) {
- query getUser($login: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: 10){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: 100){
nodes{
commitCount,
+ occurredAt,
- occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
},
contributionCalendar{
totalContributions,
weeks{
contributionDays{
date,
weekday,
contributionCount,
contributionLevel,
}
}
colors,
}
contributionYears,
issueContributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
issueContributionsByRepository(maxRepositories: 10){
repository{
name
},
contributions(first: 10){
totalCount,
nodes{
occurredAt,
issue{
state
}
}
}
}
pullRequestContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequest{
state
}
}
}
pullRequestContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequest{
state,
}
}
}
}
pullRequestReviewContributions(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}</s>
===========changed ref 4===========
# module: backend.external.github_api.graphql.user
def get_user(user_id: str) -> Dict[str, Any]:
# offset: 1
<s>(first: 10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories:10){
repository{
name
},
contributions(first:10){
totalCount,
nodes{
occurredAt,
pullRequestReview{
state,
}
}
}
},
repositoryContributions(first:10){
totalCount,
nodes{
repository{
name,
}
occurredAt,
}
},
restrictedContributionsCount,
totalCommitContributions,
totalIssueContributions,
totalPullRequestContributions,
totalPullRequestReviewContributions,
totalRepositoryContributions,
totalRepositoriesWithContributedCommits,
totalRepositoriesWithContributedIssues,
totalRepositoriesWithContributedPullRequests,
totalRepositoriesWithContributedPullRequestReviews
},
followers(first:10){
totalCount,
nodes{
name,
url,
}
}
following(first:10){
totalCount,
nodes{
name,
url,
}
}
}
}
""",
}
try:
return get_template(query)
except Exception as e:
logging.exception(e)
raise e
|
backend.models.misc.date/Date.__init__
|
Modified
|
avgupta456~github-trends
|
fbea89aea376f89cf5c0ece48ca4688c5130b449
|
code coverage setup
|
<2>:<add> year: int = int(date.year)
<del> year: int = date.year
<3>:<add> month: int = int(date.month)
<del> month: int = date.month
<4>:<add> day: int = int(date.day)
<del> day: int = date.day
|
# module: backend.models.misc.date
class Date:
def __init__(self, date: Union[str, datetime]) -> None:
<0> self.date_obj: datetime
<1> if isinstance(date, datetime):
<2> year: int = date.year
<3> month: int = date.month
<4> day: int = date.day
<5> date = "-".join([str(year), str(month), str(day)])
<6> date_str: str = date.split("T")[0] if "T" in date else date
<7> self.date_obj = datetime.strptime(date_str, "%Y-%m-%d")
<8>
|
===========unchanged ref 0===========
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
strptime(date_string: _Text, format: _Text) -> datetime
__radd__ = __add__
===========changed ref 0===========
+ # module: backend.models.misc
+
+
===========changed ref 1===========
+ # module: backend.external.github_api.graphql
+
+
===========changed ref 2===========
+ # module: backend.processing.user
+
+
===========changed ref 3===========
+ # module: backend.external
+
+
===========changed ref 4===========
+ # module: backend.processing
+
+
|
models.misc.date/Date.__init__
|
Modified
|
avgupta456~github-trends
|
d48ad5226e4a339666dd07111cb117db11e98594
|
don't resuse var names
|
<1>:<add> date_str: str = ""
<2>:<add> date_obj: datetime = date
<add> year: int = int(date_obj.year)
<del> year: int = int(date.year)
<3>:<add> month: int = int(date_obj.month)
<del> month: int = int(date.month)
<4>:<add> day: int = int(date_obj.day)
<del> day: int = int(date.day)
<5>:<add> date_str = "-".join([str(year), str(month), str(day)])
<del> date = "-".join([str(year), str(month), str(day)])
<6>:<add> else:
<add> date_str = date
<add> date_str = date_str.split("T")[0] if "T" in date_str else date_str
<del> date_str: str = date.split("T")[0] if "T" in date else date
|
# module: models.misc.date
class Date:
def __init__(self, date: Union[str, datetime]) -> None:
<0> self.date_obj: datetime
<1> if isinstance(date, datetime):
<2> year: int = int(date.year)
<3> month: int = int(date.month)
<4> day: int = int(date.day)
<5> date = "-".join([str(year), str(month), str(day)])
<6> date_str: str = date.split("T")[0] if "T" in date else date
<7> self.date_obj = datetime.strptime(date_str, "%Y-%m-%d")
<8>
|
===========unchanged ref 0===========
at: datetime
datetime()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
__str__ = isoformat
__radd__ = __add__
|
external.github_api.graphql.template/get_template
|
Modified
|
avgupta456~github-trends
|
7789e3724e9eecadecd114e3d59ebc2051221115
|
misc changes
|
<9>:<add> data = r.json() # type: ignore
<del> return r.json() # type: ignore
<10>:<add> if "errors" in data:
<add> raise GraphQlError("GraphQL errors: " + str(data["errors"]))
<add> return data
|
# module: external.github_api.graphql.template
def get_template(query: Dict[str, Any]) -> Dict[str, Any]:
<0> """Template for interacting with the GitHub GraphQL API"""
<1> token = os.getenv("AUTH_TOKEN", "")
<2> headers: Dict[str, str] = {"Authorization": "bearer " + token}
<3> start = datetime.now()
<4> r = s.post( # type: ignore
<5> "https://api.github.com/graphql", json=query, headers=headers
<6> )
<7> print("GraphQL", datetime.now() - start)
<8> if r.status_code == 200:
<9> return r.json() # type: ignore
<10> else:
<11> raise GraphQlError(
<12> "Invalid status code "
<13> + str(r.status_code)
<14> + ": "
<15> + str(r.json()["message"]) # type: ignore
<16> + " Documentation at "
<17> + str(r.json()["documentation_url"]) # type: ignore
<18> )
<19>
|
===========unchanged ref 0===========
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: external.github_api.graphql.template
s = requests.session()
GraphQlError(*args: object)
at: os
getenv(key: str, default: _T) -> Union[str, _T]
getenv(key: str) -> Optional[str]
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.models.Response.__init__
self.status_code = None
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
processing.user.contribution_calendar/get_user_contribution_calendar
|
Modified
|
avgupta456~github-trends
|
7789e3724e9eecadecd114e3d59ebc2051221115
|
misc changes
|
<11>:<add> days = map(
<del> days = list(
<12>:<del> map(
<13>:<add> lambda x: ContributionDay.parse_obj(
<del> lambda x: ContributionDay.parse_obj(
<14>:<add> {
<del> {
<15>:<add> "date": Date(x.date),
<del> "date": Date(x.date),
<16>:<add> "weekday": x.weekday,
<del> "weekday": x.weekday,
<17>:<add> "contribution_count": x.contribution_count,
<del> "contribution_count": x.contribution_count,
<18>:<add> "contribution_level": x.contribution_level,
<del> "contribution_level": x.contribution_level,
<19>:<del> }
<20>:<del> ),
<21>:<add> }
<del> [
<22>:<add> ),
<add> [
<add> day
<del> day
<23>:<add> for week in data.contribution_calendar.weeks
<del> for week in data.contribution_calendar.weeks
<24>:<add> for day in week.contribution_days
<del> for day in week.contribution_days
<25>:<del> ],
<26>:<add> ],
<del> )
<28>:<add>
<add> days = list(filter(lambda x: start_date <= x.date <= end_date, days))
|
# module: processing.user.contribution_calendar
def get_user_contribution_calendar(
user_id: str,
start_date: Date = today - 365,
end_date: Date = today,
) -> ContributionCalendar:
<0> """get user contributions for the past year"""
<1> if today - start_date > 365:
<2> raise AssertionError("start_date can only be within past 1 year")
<3>
<4> try:
<5> data = run_query(user_id)
<6> except Exception as e:
<7> raise e
<8>
<9> contribution_years = data.contribution_years
<10> colors = data.contribution_calendar.colors
<11> days = list(
<12> map(
<13> lambda x: ContributionDay.parse_obj(
<14> {
<15> "date": Date(x.date),
<16> "weekday": x.weekday,
<17> "contribution_count": x.contribution_count,
<18> "contribution_level": x.contribution_level,
<19> }
<20> ),
<21> [
<22> day
<23> for week in data.contribution_calendar.weeks
<24> for day in week.contribution_days
<25> ],
<26> )
<27> )
<28>
<29> # creates total period (up to 1 year long)
<30> total = create_contribution_period(days)
<31>
<32> # creates months (0 is January, 11 is December)
<33> months = [[] for _ in range(12)]
<34> for day in days:
<35> months[day.date.month() - 1].append(day)
<36>
<37> months = list(map(lambda x: create_contribution_period(x), months))
<38>
<39> # create weekdays (0 is Sunday, 6 is Saturday)
<40> weekdays = [[] for _ in range(7)]
<41> for day in days:
<42> weekdays[day.weekday].append(day)
<43>
<44> weekdays = list(map(lambda x: create_contribution_period(x), weekdays))
<45>
<46> </s>
|
===========below chunk 0===========
# module: processing.user.contribution_calendar
def get_user_contribution_calendar(
user_id: str,
start_date: Date = today - 365,
end_date: Date = today,
) -> ContributionCalendar:
# offset: 1
calendar = ContributionCalendar(
contribution_years=contribution_years,
colors=colors,
total=total,
months=months,
weekdays=weekdays,
)
return calendar
===========unchanged ref 0===========
at: external.github_api.graphql.user
get_user_contribution_calendar(user_id: str) -> UserContributionCalendar
at: models.misc.date
Date(date: Union[str, datetime])
today = Date(datetime.now())
at: models.user.contribution_calendar
create_contribution_period(days: List[ContributionDay]) -> ContributionPeriod
at: models.user.contribution_calendar.APIResponse
contribution_calendar: APIResponse_Calendar = Field(alias="contributionCalendar")
contribution_years: List[int] = Field(alias="contributionYears")
at: models.user.contribution_calendar.APIResponse_Calendar
total_contributions: int = Field(alias="totalContributions")
weeks: List[APIResponse_Calendar_Week]
colors: List[str]
===========changed ref 0===========
# module: external.github_api.graphql.template
def get_template(query: Dict[str, Any]) -> Dict[str, Any]:
"""Template for interacting with the GitHub GraphQL API"""
token = os.getenv("AUTH_TOKEN", "")
headers: Dict[str, str] = {"Authorization": "bearer " + token}
start = datetime.now()
r = s.post( # type: ignore
"https://api.github.com/graphql", json=query, headers=headers
)
print("GraphQL", datetime.now() - start)
if r.status_code == 200:
+ data = r.json() # type: ignore
- return r.json() # type: ignore
+ if "errors" in data:
+ raise GraphQlError("GraphQL errors: " + str(data["errors"]))
+ return data
else:
raise GraphQlError(
"Invalid status code "
+ str(r.status_code)
+ ": "
+ str(r.json()["message"]) # type: ignore
+ " Documentation at "
+ str(r.json()["documentation_url"]) # type: ignore
)
|
models.user.commit_contributions_by_repository/create_commit_contribution
|
Modified
|
avgupta456~github-trends
|
a1257f1c0535edfd92dbe1977855a2bc766edca6
|
update commits endpoint
|
<2>:<add> commit_count=x.commit_count, occurred_at=Date(x.occurred_at)
<del> commit_count=x.commit_count, occured_at=Date(x.occurred_at)
|
# module: models.user.commit_contributions_by_repository
def create_commit_contribution(x: APIResponse_Repo_Contribs_Node) -> CommitContribution:
<0> """helper function to create a CommitContribution"""
<1> return CommitContribution(
<2> commit_count=x.commit_count, occured_at=Date(x.occurred_at)
<3> )
<4>
|
===========unchanged ref 0===========
at: models.misc.date
Date(date: Union[str, datetime])
at: models.user.commit_contributions_by_repository.CommitContribution
commit_count: int
===========changed ref 0===========
# module: models.user.commit_contributions_by_repository
class APIResponse(BaseModel):
"""
BaseModel which accepts:
- data: List[APIResponse_Repo]
"""
+ commits_by_repo: List[APIResponse_Repo] = Field(
+ alias="commitContributionsByRepository"
+ )
+ commit_contribs_count: int = Field(alias="totalCommitContributions")
+ repos_with_commit_contrib: int = Field(
+ alias="totalRepositoriesWithContributedCommits"
+ )
- data: List[APIResponse_Repo]
|
external.github_api.graphql.user/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
a1257f1c0535edfd92dbe1977855a2bc766edca6
|
update commits endpoint
|
<30>:<add> totalCommitContributions,
<add> totalRepositoriesWithContributedCommits,
<37>:<add> output_dict = get_template(query)["data"]["user"]["contributionsCollection"]
<del> output_dict = get_template(query)["data"]["user"]["contributionsCollection"][
<38>:<del> "commitContributionsByRepository"
<39>:<del> ]
<40>:<add> return UserCommitContributionsByRepositoryAPIResponse.parse_obj(output_dict)
<del> return UserCommitContributionsByRepositoryAPIResponse(data=output_dict)
|
# module: external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
first: int = 100,
after: str = "",
) -> UserCommitContributionsByRepositoryAPIResponse:
<0> """Runs an individual query, fetching at most 100 days of history"""
<1> query = {
<2> "variables": {
<3> "login": user_id,
<4> "maxRepos": max_repos,
<5> "first": first,
<6> "after": after,
<7> },
<8> "query": """
<9> query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
<10> user(login: $login){
<11> contributionsCollection{
<12> commitContributionsByRepository(maxRepositories: $maxRepos){
<13> repository{
<14> name,
<15> },
<16> totalCount:contributions(first: 1){
<17> totalCount
<18> }
<19> contributions(first: $first, after: $after){
<20> nodes{
<21> commitCount,
<22> occurredAt,
<23> }
<24> pageInfo{
<25> hasNextPage,
<26> endCursor
<27> }
<28> }
<29> }
<30> },
<31> },
<32> }
<33> """,
<34> }
<35>
<36> try:
<37> output_dict = get_template(query)["data"]["user"]["contributionsCollection"][
<38> "commitContributionsByRepository"
<39> ]
<40> return UserCommitContributionsByRepositoryAPIResponse(data=output_dict)
<41> except Exception as e:
<42> logging.exception(e)
<43> raise e
<44>
|
===========unchanged ref 0===========
at: external.github_api.graphql.template
get_template(query: Dict[str, Any]) -> Dict[str, Any]
===========changed ref 0===========
# module: models.user.commit_contributions_by_repository
class APIResponse(BaseModel):
"""
BaseModel which accepts:
- data: List[APIResponse_Repo]
"""
+ commits_by_repo: List[APIResponse_Repo] = Field(
+ alias="commitContributionsByRepository"
+ )
+ commit_contribs_count: int = Field(alias="totalCommitContributions")
+ repos_with_commit_contrib: int = Field(
+ alias="totalRepositoriesWithContributedCommits"
+ )
- data: List[APIResponse_Repo]
===========changed ref 1===========
# module: models.user.commit_contributions_by_repository
def create_commit_contribution(x: APIResponse_Repo_Contribs_Node) -> CommitContribution:
"""helper function to create a CommitContribution"""
return CommitContribution(
+ commit_count=x.commit_count, occurred_at=Date(x.occurred_at)
- commit_count=x.commit_count, occured_at=Date(x.occurred_at)
)
===========changed ref 2===========
# module: models.user.commit_contributions_by_repository
+ class CommitContributions(BaseModel):
+ """
+ BaseModel which accepts:
+ - commit_contribs_by_repo: List[CommitContributionsByRepository]
+ - commit_contribs_count: int
+ - repos_with_commit_contrib: int
+ """
+
+ commit_contribs_by_repo: List[CommitContributionsByRepository]
+ commit_contribs_count: int
+ repos_with_commit_contrib: int
+
|
external.github_api.graphql.user/get_user_contribution_calendar
|
Modified
|
avgupta456~github-trends
|
a1257f1c0535edfd92dbe1977855a2bc766edca6
|
update commits endpoint
|
<28>:<add> return UserContributionCalendarAPIResponse.parse_obj(output_dict)
<del> return UserContributionCalendar.parse_obj(output_dict)
|
# module: external.github_api.graphql.user
+ def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse:
- def get_user_contribution_calendar(user_id: str) -> UserContributionCalendar:
<0> """Fetches user contribution calendar and contribution years"""
<1> query = {
<2> "variables": {"login": user_id},
<3> "query": """
<4> query getUser($login: String!) {
<5> user(login: $login){
<6> contributionsCollection{
<7> contributionCalendar{
<8> totalContributions,
<9> weeks{
<10> contributionDays{
<11> date,
<12> weekday,
<13> contributionCount,
<14> contributionLevel,
<15> }
<16> }
<17> colors,
<18> }
<19> contributionYears,
<20> }
<21> },
<22> }
<23> """,
<24> }
<25>
<26> try:
<27> output_dict = get_template(query)["data"]["user"]["contributionsCollection"]
<28> return UserContributionCalendar.parse_obj(output_dict)
<29> except Exception as e:
<30> logging.exception(e)
<31> raise e
<32>
|
===========unchanged ref 0===========
at: external.github_api.graphql.template
get_template(query: Dict[str, Any]) -> Dict[str, Any]
===========changed ref 0===========
# module: external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
first: int = 100,
after: str = "",
) -> UserCommitContributionsByRepositoryAPIResponse:
"""Runs an individual query, fetching at most 100 days of history"""
query = {
"variables": {
"login": user_id,
"maxRepos": max_repos,
"first": first,
"after": after,
},
"query": """
query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: $maxRepos){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: $first, after: $after){
nodes{
commitCount,
occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
+ totalCommitContributions,
+ totalRepositoriesWithContributedCommits,
},
},
}
""",
}
try:
+ output_dict = get_template(query)["data"]["user"]["contributionsCollection"]
- output_dict = get_template(query)["data"]["user"]["contributionsCollection"][
- "commitContributionsByRepository"
- ]
+ return UserCommitContributionsByRepositoryAPIResponse.parse_obj(output_dict)
- return UserCommitContributionsByRepositoryAPIResponse(data=output_dict)
except Exception as e:
logging.exception(e)
raise e
===========changed ref 1===========
# module: models.user.commit_contributions_by_repository
def create_commit_contribution(x: APIResponse_Repo_Contribs_Node) -> CommitContribution:
"""helper function to create a CommitContribution"""
return CommitContribution(
+ commit_count=x.commit_count, occurred_at=Date(x.occurred_at)
- commit_count=x.commit_count, occured_at=Date(x.occurred_at)
)
===========changed ref 2===========
# module: models.user.commit_contributions_by_repository
+ class CommitContributions(BaseModel):
+ """
+ BaseModel which accepts:
+ - commit_contribs_by_repo: List[CommitContributionsByRepository]
+ - commit_contribs_count: int
+ - repos_with_commit_contrib: int
+ """
+
+ commit_contribs_by_repo: List[CommitContributionsByRepository]
+ commit_contribs_count: int
+ repos_with_commit_contrib: int
+
===========changed ref 3===========
# module: models.user.commit_contributions_by_repository
class APIResponse(BaseModel):
"""
BaseModel which accepts:
- data: List[APIResponse_Repo]
"""
+ commits_by_repo: List[APIResponse_Repo] = Field(
+ alias="commitContributionsByRepository"
+ )
+ commit_contribs_count: int = Field(alias="totalCommitContributions")
+ repos_with_commit_contrib: int = Field(
+ alias="totalRepositoriesWithContributedCommits"
+ )
- data: List[APIResponse_Repo]
|
processing.user.commit_contributions_by_repository/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
a1257f1c0535edfd92dbe1977855a2bc766edca6
|
update commits endpoint
|
<3>:<add> raw_repos: List[CommitContributionsByRepository] = []
<del> raw_output: List[CommitContributionsByRepository] = []
<4>:<add> commit_contribs_count, repos_with_commit_contrib = 0, 0
<11>:<add> commit_contribs_count = data.commit_contribs_count
<add> repos_with_commit_contrib = data.repos_with_commit_contrib
<add>
<12>:<add> for i, repo in enumerate(data.commits_by_repo):
<del> for i, repo in enumerate(data.data):
<14>:<add> raw_repos.append(
<del> raw_output.append(
<33>:<add> raw_repos[i].timeline.extend(contribs)
<del> raw_output[i].timeline.extend(contribs)
|
# module: processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
+ ) -> CommitContributions:
- ) -> List[CommitContributionsByRepository]:
<0> """Gets the daily contribution history for a users top x repositories"""
<1> time_range = today - start_date # gets number of days to end date
<2> segments = min(math.ceil(time_range / 100), 10) # no more than three years
<3> raw_output: List[CommitContributionsByRepository] = []
<4> index, cont, after = 0, True, "" # initialize variables
<5> while cont and index < segments:
<6> try:
<7> data = run_query(user_id, max_repos, after=after)
<8> except Exception as e:
<9> raise e
<10>
<11> cont = False
<12> for i, repo in enumerate(data.data):
<13> if index == 0:
<14> raw_output.append(
<15> CommitContributionsByRepository.parse_obj(
<16> {
<17> "name": repo.repository.name,
<18> "contributions": repo.total_count.total_count,
<19> "contributions_in_range": 0,
<20> "timeline": [],
<21> }
<22> )
<23> )
<24>
<25> raw_contribs = repo.contributions.nodes
<26> contribs = map(
<27> lambda x: create_commit_contribution(x),
<28> raw_contribs,
<29> )
<30> contribs = filter(
<31> lambda x: start_date <= x.occurred_at <= end_date, contribs
<32> )
<33> raw_output[i].timeline.extend(contribs)
<34>
<35> if repo.contributions.page_info.has_next_page:
<36> after = repo.contributions.page_info.end_cursor
<37> cont = True
<38>
<39> index += 1
</s>
|
===========below chunk 0===========
# module: processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
+ ) -> CommitContributions:
- ) -> List[CommitContributionsByRepository]:
# offset: 1
# adds contributionsInRange
for repo in raw_output:
repo.contributions_in_range = sum([x.commit_count for x in repo.timeline])
# converts to objects
output_objects = map(
lambda x: CommitContributionsByRepository.parse_obj(x), raw_output
)
# filters out empty results
output_objects = filter(lambda x: x.contributions_in_range > 0, output_objects)
return list(output_objects)
===========unchanged ref 0===========
at: external.github_api.graphql.user
get_user_commit_contributions_by_repository(user_id: str, max_repos: int=100, first: int=100, after: str="") -> UserCommitContributionsByRepositoryAPIResponse
at: math
ceil(x: SupportsFloat, /) -> int
at: models.misc.date
Date(date: Union[str, datetime])
today = Date(datetime.now())
at: models.user.commit_contributions_by_repository
create_commit_contribution(x: APIResponse_Repo_Contribs_Node) -> CommitContribution
at: models.user.commit_contributions_by_repository.APIResponse
commits_by_repo: List[APIResponse_Repo] = Field(
alias="commitContributionsByRepository"
)
commit_contribs_count: int = Field(alias="totalCommitContributions")
repos_with_commit_contrib: int = Field(
alias="totalRepositoriesWithContributedCommits"
)
at: models.user.commit_contributions_by_repository.APIResponse_Repo
repository: APIResponse_Repo_Repo
total_count: APIResponse_Repo_TotalCount = Field(alias="totalCount")
contributions: APIResponse_Repo_Contribs
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Contribs
nodes: List[APIResponse_Repo_Contribs_Node]
page_info: APIResponse_Repo_Contribs_PageInfo = Field(alias="pageInfo")
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Contribs_PageInfo
has_next_page: bool = Field(alias="hasNextPage")
end_cursor: str = Field(alias="endCursor")
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Repo
name: str
===========unchanged ref 1===========
at: models.user.commit_contributions_by_repository.APIResponse_Repo_TotalCount
total_count: int = Field(alias="totalCount")
at: models.user.commit_contributions_by_repository.CommitContribution
commit_count: int
occurred_at: Date
at: models.user.commit_contributions_by_repository.CommitContributionsByRepository
name: str
contributions: int
contributions_in_range: int
timeline: List[CommitContribution]
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: models.user.commit_contributions_by_repository
def create_commit_contribution(x: APIResponse_Repo_Contribs_Node) -> CommitContribution:
"""helper function to create a CommitContribution"""
return CommitContribution(
+ commit_count=x.commit_count, occurred_at=Date(x.occurred_at)
- commit_count=x.commit_count, occured_at=Date(x.occurred_at)
)
===========changed ref 1===========
# module: models.user.commit_contributions_by_repository
+ class CommitContributions(BaseModel):
+ """
+ BaseModel which accepts:
+ - commit_contribs_by_repo: List[CommitContributionsByRepository]
+ - commit_contribs_count: int
+ - repos_with_commit_contrib: int
+ """
+
+ commit_contribs_by_repo: List[CommitContributionsByRepository]
+ commit_contribs_count: int
+ repos_with_commit_contrib: int
+
===========changed ref 2===========
# module: external.github_api.graphql.user
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
first: int = 100,
after: str = "",
) -> UserCommitContributionsByRepositoryAPIResponse:
"""Runs an individual query, fetching at most 100 days of history"""
query = {
"variables": {
"login": user_id,
"maxRepos": max_repos,
"first": first,
"after": after,
},
"query": """
query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) {
user(login: $login){
contributionsCollection{
commitContributionsByRepository(maxRepositories: $maxRepos){
repository{
name,
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: $first, after: $after){
nodes{
commitCount,
occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
+ totalCommitContributions,
+ totalRepositoriesWithContributedCommits,
},
},
}
""",
}
try:
+ output_dict = get_template(query)["data"]["user"]["contributionsCollection"]
- output_dict = get_template(query)["data"]["user"]["contributionsCollection"][
- "commitContributionsByRepository"
- ]
+ return UserCommitContributionsByRepositoryAPIResponse.parse_obj(output_dict)
- return UserCommitContributionsByRepositoryAPIResponse(data=output_dict)
except Exception as e:
logging.exception(e)
raise e
===========changed ref 3===========
# module: models.user.commit_contributions_by_repository
class APIResponse(BaseModel):
"""
BaseModel which accepts:
- data: List[APIResponse_Repo]
"""
+ commits_by_repo: List[APIResponse_Repo] = Field(
+ alias="commitContributionsByRepository"
+ )
+ commit_contribs_count: int = Field(alias="totalCommitContributions")
+ repos_with_commit_contrib: int = Field(
+ alias="totalRepositoriesWithContributedCommits"
+ )
- data: List[APIResponse_Repo]
===========changed ref 4===========
# module: external.github_api.graphql.user
+ def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse:
- def get_user_contribution_calendar(user_id: str) -> UserContributionCalendar:
"""Fetches user contribution calendar and contribution years"""
query = {
"variables": {"login": user_id},
"query": """
query getUser($login: String!) {
user(login: $login){
contributionsCollection{
contributionCalendar{
totalContributions,
weeks{
contributionDays{
date,
weekday,
contributionCount,
contributionLevel,
}
}
colors,
}
contributionYears,
}
},
}
""",
}
try:
output_dict = get_template(query)["data"]["user"]["contributionsCollection"]
+ return UserContributionCalendarAPIResponse.parse_obj(output_dict)
- return UserContributionCalendar.parse_obj(output_dict)
except Exception as e:
logging.exception(e)
raise e
|
processing.user.commit_contributions_by_repository/get_user_commit_contributions_by_repository
|
Modified
|
avgupta456~github-trends
|
28f32f4a48d1044d1b3c1ec73877d05e28a6c274
|
add aggregate commit count
|
<19>:<add> CommitContributionsByRepository(
<del> CommitContributionsByRepository.parse_obj(
<20>:<del> {
<21>:<add> name=repo.repository.name,
<del> "name": repo.repository.name,
<22>:<add> contributions=repo.total_count.total_count,
<del> "contributions": repo.total_count.total_count,
<23>:<add> contributions_in_range=0,
<del> "contributions_in_range": 0,
<24>:<add> timeline=[],
<del> "timeline": [],
<25>:<del> }
|
# module: processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> CommitContributions:
<0> """Gets the daily contribution history for a users top x repositories"""
<1> time_range = today - start_date # gets number of days to end date
<2> segments = min(math.ceil(time_range / 100), 10) # no more than three years
<3> raw_repos: List[CommitContributionsByRepository] = []
<4> commit_contribs_count, repos_with_commit_contrib = 0, 0
<5> index, cont, after = 0, True, "" # initialize variables
<6> while cont and index < segments:
<7> try:
<8> data = run_query(user_id, max_repos, after=after)
<9> except Exception as e:
<10> raise e
<11>
<12> commit_contribs_count = data.commit_contribs_count
<13> repos_with_commit_contrib = data.repos_with_commit_contrib
<14>
<15> cont = False
<16> for i, repo in enumerate(data.commits_by_repo):
<17> if index == 0:
<18> raw_repos.append(
<19> CommitContributionsByRepository.parse_obj(
<20> {
<21> "name": repo.repository.name,
<22> "contributions": repo.total_count.total_count,
<23> "contributions_in_range": 0,
<24> "timeline": [],
<25> }
<26> )
<27> )
<28>
<29> raw_contribs = repo.contributions.nodes
<30> contribs = map(
<31> lambda x: create_commit_contribution(x),
<32> raw_contribs,
<33> )
<34> contribs = filter(
<35> lambda x: start_date <= x.occurred_at <= end_date, contribs
<36> )
<37> raw_repos[i].timeline.extend(contribs)
</s>
|
===========below chunk 0===========
# module: processing.user.commit_contributions_by_repository
def get_user_commit_contributions_by_repository(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> CommitContributions:
# offset: 1
if repo.contributions.page_info.has_next_page:
after = repo.contributions.page_info.end_cursor
cont = True
index += 1
# adds contributionsInRange
for repo in raw_repos:
repo.contributions_in_range = sum([x.commit_count for x in repo.timeline])
# converts to objects
repo_objects = map(
lambda x: CommitContributionsByRepository.parse_obj(x), raw_repos
)
# filters out empty results
repo_objects = filter(lambda x: x.contributions_in_range > 0, repo_objects)
output = CommitContributions(
commit_contribs_by_repo=list(repo_objects),
commit_contribs_count=commit_contribs_count,
repos_with_commit_contrib=repos_with_commit_contrib,
)
return output
===========unchanged ref 0===========
at: external.github_api.graphql.user
get_user_commit_contributions_by_repository(user_id: str, max_repos: int=100, first: int=100, after: str="") -> UserCommitContributionsByRepositoryAPIResponse
at: math
ceil(x: SupportsFloat, /) -> int
at: models.misc.date
Date(date: Union[str, datetime])
today = Date(datetime.now())
at: models.user.commit_contributions_by_repository
create_commit_contribution(x: APIResponse_Repo_Contribs_Node) -> CommitContribution
at: models.user.commit_contributions_by_repository.APIResponse
commits_by_repo: List[APIResponse_Repo] = Field(
alias="commitContributionsByRepository"
)
commit_contribs_count: int = Field(alias="totalCommitContributions")
repos_with_commit_contrib: int = Field(
alias="totalRepositoriesWithContributedCommits"
)
at: models.user.commit_contributions_by_repository.APIResponse_Repo
repository: APIResponse_Repo_Repo
total_count: APIResponse_Repo_TotalCount = Field(alias="totalCount")
contributions: APIResponse_Repo_Contribs
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Contribs
nodes: List[APIResponse_Repo_Contribs_Node]
page_info: APIResponse_Repo_Contribs_PageInfo = Field(alias="pageInfo")
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Contribs_PageInfo
has_next_page: bool = Field(alias="hasNextPage")
end_cursor: str = Field(alias="endCursor")
at: models.user.commit_contributions_by_repository.APIResponse_Repo_Repo
name: str
===========unchanged ref 1===========
at: models.user.commit_contributions_by_repository.APIResponse_Repo_TotalCount
total_count: int = Field(alias="totalCount")
at: models.user.commit_contributions_by_repository.CommitContribution
commit_count: int
occurred_at: Date
at: models.user.commit_contributions_by_repository.CommitContributionsByRepository
name: str
contributions: int
contributions_in_range: int
timeline: List[CommitContribution]
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: models.user.commit_contributions_by_repository
class CommitContributions(BaseModel):
"""
BaseModel which accepts:
- commit_contribs_by_repo: List[CommitContributionsByRepository]
+ - commit_contribs: CommitContributionsByRepository
- - commit_contribs_count: int
- repos_with_commit_contrib: int
"""
commit_contribs_by_repo: List[CommitContributionsByRepository]
+ commit_contribs: CommitContributionsByRepository
- commit_contribs_count: int
repos_with_commit_contrib: int
|
processing.user.contribution_stats/get_user_contribution_stats
|
Modified
|
avgupta456~github-trends
|
8f29445a0c52876eb5ab99fb845bec4603a17177
|
misc
|
<25>:<del> print("STAGE", index)
|
# module: processing.user.contribution_stats
def get_user_contribution_stats(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> ContribStats:
<0> """Gets the daily contribution history for a users top x repositories"""
<1> repo_names = set()
<2> repo_contribs: DefaultDict[str, Dict[str, List[Contribution]]] = defaultdict(
<3> lambda: {"issues": [], "prs": [], "reviews": [], "repo": []}
<4> )
<5> total_contribs: Dict[str, List[Contribution]] = {
<6> "issues": [],
<7> "prs": [],
<8> "reviews": [],
<9> "repo": [],
<10> }
<11>
<12> # only need them from the first data pull
<13> restricted_contrib_count = 0
<14> issue_contribs_count = 0
<15> pr_contribs_count = 0
<16> pr_review_contribs_count = 0
<17> repo_contribs_count = 0
<18> repos_with_issue_contrib = 0
<19> repos_with_pr_contrib = 0
<20> repos_with_pr_review_contrib = 0
<21>
<22> after: Optional[str] = ""
<23> index, cont = 0, True # initialize variables
<24> while cont and index < 10:
<25> print("STAGE", index)
<26> try:
<27> after_str: str = after if isinstance(after, str) else ""
<28> data = run_query(user_id, max_repos, after=after_str)
<29> except Exception as e:
<30> raise e
<31>
<32> restricted_contrib_count = data.restricted_contrib_count
<33> issue_contribs_count = data.issue_contribs_count
<34> pr_contribs_count = data.pr_contribs_count
<35> pr_review_contribs_count = data.pr_review_contribs_count
<36> repo_contribs_count = data.</s>
|
===========below chunk 0===========
# module: processing.user.contribution_stats
def get_user_contribution_stats(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> ContribStats:
# offset: 1
repos_with_issue_contrib = data.repos_with_issue_contrib
repos_with_pr_contrib = data.repos_with_pr_contrib
repos_with_pr_review_contrib = data.repos_with_pr_review_contrib
for repo in data.issue_contribs_by_repo:
repo_names.add(repo.repository.name)
for repo in data.pr_contribs_by_repo:
repo_names.add(repo.repository.name)
for repo in data.pr_review_contribs_by_repo:
repo_names.add(repo.repository.name)
for repo in data.repo_contribs.nodes:
repo_names.add(repo.repository.name)
cont = False
repo_lists: List[List[APIResponse_ContribsByRepo]] = [
data.issue_contribs_by_repo,
data.pr_contribs_by_repo,
data.pr_review_contribs_by_repo,
]
for category, repo_list in zip(["issues", "prs", "reviews"], repo_lists):
for repo in repo_list:
repo_name = repo.repository.name
for event in repo.contributions.nodes:
contrib = Contribution(occurred_at=Date(event.occurred_at))
repo_contribs[repo_name][category].append(contrib)
total_contribs[category].append(contrib)
if repo.contributions.page_info.has_next_page:
after = repo.contributions.page_info.end_cursor
cont = True
for repo in data.repo_contribs.nodes:
contrib = Contribution(occurred_at=Date(repo.occurred_at</s>
===========below chunk 1===========
# module: processing.user.contribution_stats
def get_user_contribution_stats(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> ContribStats:
# offset: 2
<s> in data.repo_contribs.nodes:
contrib = Contribution(occurred_at=Date(repo.occurred_at))
repo_contribs[repo.repository.name]["repo"].append(contrib)
total_contribs["repo"].append(contrib)
if data.repo_contribs.page_info.has_next_page:
after = data.repo_contribs.page_info.end_cursor
cont = True
index += 1
date_filter: Callable[[Contribution], bool] = (
lambda x: start_date <= x.occurred_at <= end_date
)
repo_contrib_objs: List[RepoContribStats] = [
RepoContribStats(
name=k,
issues=list(filter(date_filter, v["issues"])),
prs=list(filter(date_filter, v["prs"])),
reviews=list(filter(date_filter, v["reviews"])),
repo=list(filter(date_filter, v["repo"])),
)
for k, v in repo_contribs.items()
]
total_contrib_obj: RepoContribStats = RepoContribStats(
name="total",
issues=list(filter(date_filter, total_contribs["issues"])),
prs=list(filter(date_filter, total_contribs["prs"])),
reviews=list(filter(date_filter, total_contribs["reviews"])),
repo=list(filter(date_filter, total_contribs["repo"])),
)
output: Contrib</s>
===========below chunk 2===========
# module: processing.user.contribution_stats
def get_user_contribution_stats(
user_id: str,
max_repos: int = 100,
start_date: Date = today - 365,
end_date: Date = today,
) -> ContribStats:
# offset: 3
<s> ContribStats(
total=total_contrib_obj,
repos=repo_contrib_objs,
restricted_contrib_count=restricted_contrib_count,
issue_contribs_count=issue_contribs_count,
pr_contribs_count=pr_contribs_count,
pr_review_contribs_count=pr_review_contribs_count,
repo_contribs_count=repo_contribs_count,
repos_with_issue_contrib=repos_with_issue_contrib,
repos_with_pr_contrib=repos_with_pr_contrib,
repos_with_pr_review_contrib=repos_with_pr_review_contrib,
)
return output
===========unchanged ref 0===========
at: collections
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]])
defaultdict(default_factory: Optional[Callable[[], _VT]])
defaultdict(**kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT])
at: external.github_api.graphql.user
get_user_contribution_stats(user_id: str, max_repos: int=100, first: int=100, after: str="") -> UserContributionStatsAPIResponse
at: models.misc.date
Date(date: Union[str, datetime])
today = Date(datetime.now())
at: models.user.contribution_stats.APIResponse
issue_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field(
alias="issueContributionsByRepository"
)
pr_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field(
alias="pullRequestContributionsByRepository"
)
pr_review_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field(
alias="pullRequestReviewContributionsByRepository"
)
repo_contribs: APIResponse_RepoContribs = Field(alias="repositoryContributions")
restricted_contrib_count: int = Field(alias="restrictedContributionsCount")
issue_contribs_count: int = Field(alias="totalIssueContributions")
pr_contribs_count: int = Field(alias="totalPullRequestContributions")
|
tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_contribution_commits
|
Modified
|
avgupta456~github-trends
|
571e73f1afc11fc36f8ae008bbddaedb3dac0a46
|
add more test cases
|
<1>:<del>
|
# module: tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_commits(self):
<0> response = get_user_contribution_commits(user_id="avgupta456")
<1>
<2> self.assertIsInstance(response, UserContributionCommitsAPIResponse)
<3>
| |
tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_contribution_stats
|
Modified
|
avgupta456~github-trends
|
571e73f1afc11fc36f8ae008bbddaedb3dac0a46
|
add more test cases
|
<1>:<del>
|
# module: tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_stats(self):
<0> response = get_user_contribution_stats(user_id="avgupta456")
<1>
<2> self.assertIsInstance(response, UserContributionStatsAPIResponse)
<3>
|
===========changed ref 0===========
# module: tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_commits(self):
response = get_user_contribution_commits(user_id="avgupta456")
-
self.assertIsInstance(response, UserContributionCommitsAPIResponse)
|
tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_followers
|
Modified
|
avgupta456~github-trends
|
571e73f1afc11fc36f8ae008bbddaedb3dac0a46
|
add more test cases
|
<1>:<del>
|
# module: tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_followers(self):
<0> response = get_user_followers(user_id="avgupta456")
<1>
<2> self.assertIsInstance(response, UserFollowAPIResponse)
<3>
|
===========changed ref 0===========
# module: tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_stats(self):
response = get_user_contribution_stats(user_id="avgupta456")
-
self.assertIsInstance(response, UserContributionStatsAPIResponse)
===========changed ref 1===========
# module: tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_commits(self):
response = get_user_contribution_commits(user_id="avgupta456")
-
self.assertIsInstance(response, UserContributionCommitsAPIResponse)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.