id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
2,159 | import copy
import math
import warnings
from typing import Optional, Tuple, Union
from loguru import logger
import torch
import torch.distributed
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutput,
BaseModelOutputWithPastAndCrossAttentions,
Seq2SeqLMOutput,
)
from transformers.modeling_utils import PreTrainedModel
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
from transformers.utils import (
is_torch_fx_proxy,
)
from transformers import T5Config
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
)
def layer_norm(hidden_states, weight, epsilon):
# T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
# Square Layer Normalization https://arxiv.org/abs/1910.07467 thus varience is calculated
# w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
# half-precision inputs is done in fp32
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + epsilon)
# convert into half-precision if necessary
if weight.dtype in [torch.float16, torch.bfloat16]:
hidden_states = hidden_states.to(weight.dtype)
return weight * hidden_states | null |
2,160 | import math
import os
import warnings
from typing import Optional, Tuple, Union
import torch
import torch.distributed
import torch.utils.checkpoint
from torch import nn
from torch.nn import LayerNorm
from torch.nn import functional as F
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from transformers import BloomConfig, PreTrainedModel
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
)
if (
torch.cuda.is_available()
and not os.environ.get("DISABLE_CUSTOM_KERNELS", "False") == "True"
):
try:
from custom_kernels import fused_bloom_attention_cuda
CUSTOM_KERNELS_ENABLED = True
except ImportError:
pass
The provided code snippet includes necessary dependencies for implementing the `_make_causal_mask` function. Write a Python function `def _make_causal_mask( input_ids_shape: torch.Size, device: torch.device, past_key_values_length: int ) -> torch.BoolTensor` to solve the following problem:
Make causal mask used for self-attention.
Here is the function:
def _make_causal_mask(
input_ids_shape: torch.Size, device: torch.device, past_key_values_length: int
) -> torch.BoolTensor:
"""
Make causal mask used for self-attention.
"""
batch_size, target_length = input_ids_shape
mask = torch.ones(
(target_length, target_length + past_key_values_length),
dtype=torch.bool,
device=device,
)
mask = mask.triu(1 + past_key_values_length)
expanded_mask = mask.unsqueeze(0).expand(
batch_size, target_length, target_length + past_key_values_length
)
return expanded_mask | Make causal mask used for self-attention. |
2,161 | import math
import os
import warnings
from typing import Optional, Tuple, Union
import torch
import torch.distributed
import torch.utils.checkpoint
from torch import nn
from torch.nn import LayerNorm
from torch.nn import functional as F
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from transformers import BloomConfig, PreTrainedModel
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
)
if (
torch.cuda.is_available()
and not os.environ.get("DISABLE_CUSTOM_KERNELS", "False") == "True"
):
try:
from custom_kernels import fused_bloom_attention_cuda
CUSTOM_KERNELS_ENABLED = True
except ImportError:
pass
The provided code snippet includes necessary dependencies for implementing the `_expand_mask` function. Write a Python function `def _expand_mask(mask: torch.Tensor, tgt_length: int) -> torch.BoolTensor` to solve the following problem:
Expands attention_mask from `[batch_size, src_length]` to `[batch_size, 1, tgt_length, src_length]`.
Here is the function:
def _expand_mask(mask: torch.Tensor, tgt_length: int) -> torch.BoolTensor:
"""
Expands attention_mask from `[batch_size, src_length]` to `[batch_size, 1, tgt_length, src_length]`.
"""
batch_size, src_length = mask.shape
tgt_length = tgt_length if tgt_length is not None else src_length
expanded_mask = ~(mask[:, None, :].to(torch.bool))
return expanded_mask.expand(batch_size, tgt_length, src_length) | Expands attention_mask from `[batch_size, src_length]` to `[batch_size, 1, tgt_length, src_length]`. |
2,162 | import math
import os
import warnings
from typing import Optional, Tuple, Union
import torch
import torch.distributed
import torch.utils.checkpoint
from torch import nn
from torch.nn import LayerNorm
from torch.nn import functional as F
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from transformers import BloomConfig, PreTrainedModel
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
)
if (
torch.cuda.is_available()
and not os.environ.get("DISABLE_CUSTOM_KERNELS", "False") == "True"
):
try:
from custom_kernels import fused_bloom_attention_cuda
CUSTOM_KERNELS_ENABLED = True
except ImportError:
pass
The provided code snippet includes necessary dependencies for implementing the `build_alibi_tensor` function. Write a Python function `def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int) -> torch.Tensor` to solve the following problem:
Link to paper: https://arxiv.org/abs/2108.12409 Alibi tensor is not causal as the original paper mentions, it relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value `softmax(l+a) = softmax(l)`. Based on https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742 TODO @thomasw21 this doesn't work as nicely due to the masking strategy, and so masking varies slightly. Args: Returns tensor shaped (batch_size * num_heads, 1, max_seq_len) attention_mask (`torch.Tensor`): Token-wise attention mask, this should be of shape (batch_size, max_seq_len). num_heads (`int`, *required*): number of heads dtype (`torch.dtype`, *optional*, default=`torch.bfloat16`): dtype of the output tensor
Here is the function:
def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int) -> torch.Tensor:
"""
Link to paper: https://arxiv.org/abs/2108.12409 Alibi tensor is not causal as the original paper mentions, it
relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value
`softmax(l+a) = softmax(l)`. Based on
https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742
TODO @thomasw21 this doesn't work as nicely due to the masking strategy, and so masking varies slightly.
Args:
Returns tensor shaped (batch_size * num_heads, 1, max_seq_len)
attention_mask (`torch.Tensor`):
Token-wise attention mask, this should be of shape (batch_size, max_seq_len).
num_heads (`int`, *required*):
number of heads
dtype (`torch.dtype`, *optional*, default=`torch.bfloat16`):
dtype of the output tensor
"""
batch_size, seq_length = attention_mask.shape
closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
base = torch.tensor(
2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))),
device=attention_mask.device,
dtype=torch.float32,
)
powers = torch.arange(
1, 1 + closest_power_of_2, device=attention_mask.device, dtype=torch.int32
)
slopes = torch.pow(base, powers)
if closest_power_of_2 != num_heads:
extra_base = torch.tensor(
2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))),
device=attention_mask.device,
dtype=torch.float32,
)
num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
extra_powers = torch.arange(
1,
1 + 2 * num_remaining_heads,
2,
device=attention_mask.device,
dtype=torch.int32,
)
slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
# Note: alibi will added to the attention bias that will be applied to the query, key product of attention
# => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
# => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
# => the query_length dimension will then be broadcasted correctly
# This is more or less identical to T5's relative position bias:
# https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :]
alibi = slopes[..., None] * arange_tensor
return alibi | Link to paper: https://arxiv.org/abs/2108.12409 Alibi tensor is not causal as the original paper mentions, it relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value `softmax(l+a) = softmax(l)`. Based on https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742 TODO @thomasw21 this doesn't work as nicely due to the masking strategy, and so masking varies slightly. Args: Returns tensor shaped (batch_size * num_heads, 1, max_seq_len) attention_mask (`torch.Tensor`): Token-wise attention mask, this should be of shape (batch_size, max_seq_len). num_heads (`int`, *required*): number of heads dtype (`torch.dtype`, *optional*, default=`torch.bfloat16`): dtype of the output tensor |
2,163 | import math
import os
import warnings
from typing import Optional, Tuple, Union
import torch
import torch.distributed
import torch.utils.checkpoint
from torch import nn
from torch.nn import LayerNorm
from torch.nn import functional as F
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from transformers import BloomConfig, PreTrainedModel
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
)
if (
torch.cuda.is_available()
and not os.environ.get("DISABLE_CUSTOM_KERNELS", "False") == "True"
):
try:
from custom_kernels import fused_bloom_attention_cuda
CUSTOM_KERNELS_ENABLED = True
except ImportError:
pass
The provided code snippet includes necessary dependencies for implementing the `dropout_add` function. Write a Python function `def dropout_add( x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool ) -> torch.Tensor` to solve the following problem:
Dropout add function Args: x (`torch.tensor`, *required*): input tensor residual (`torch.tensor`, *required*): esidual tensor prob (`float`, *required*): dropout probability training (`bool`, *required*): training mode
Here is the function:
def dropout_add(
x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool
) -> torch.Tensor:
"""
Dropout add function
Args:
x (`torch.tensor`, *required*):
input tensor
residual (`torch.tensor`, *required*):
esidual tensor
prob (`float`, *required*):
dropout probability
training (`bool`, *required*):
training mode
"""
out = F.dropout(x, p=prob, training=training)
out = residual + out
return out | Dropout add function Args: x (`torch.tensor`, *required*): input tensor residual (`torch.tensor`, *required*): esidual tensor prob (`float`, *required*): dropout probability training (`bool`, *required*): training mode |
2,164 | import math
import os
import warnings
from typing import Optional, Tuple, Union
import torch
import torch.distributed
import torch.utils.checkpoint
from torch import nn
from torch.nn import LayerNorm
from torch.nn import functional as F
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from transformers import BloomConfig, PreTrainedModel
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
)
if (
torch.cuda.is_available()
and not os.environ.get("DISABLE_CUSTOM_KERNELS", "False") == "True"
):
try:
from custom_kernels import fused_bloom_attention_cuda
CUSTOM_KERNELS_ENABLED = True
except ImportError:
pass
The provided code snippet includes necessary dependencies for implementing the `_split_heads` function. Write a Python function `def _split_heads( fused_qkv: torch.Tensor, num_heads: int, head_dim: int ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]` to solve the following problem:
Split the last dimension into (num_heads, head_dim) without making any copies, results share same memory storage as `fused_qkv` Args: fused_qkv (`torch.tensor`, *required*): [batch_size, seq_length, num_heads * 3 * head_dim] Returns: query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim] value: [batch_size, seq_length, num_heads, head_dim]
Here is the function:
def _split_heads(
fused_qkv: torch.Tensor, num_heads: int, head_dim: int
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Split the last dimension into (num_heads, head_dim) without making any copies, results share same memory
storage as `fused_qkv`
Args:
fused_qkv (`torch.tensor`, *required*): [batch_size, seq_length, num_heads * 3 * head_dim]
Returns:
query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim]
value: [batch_size, seq_length, num_heads, head_dim]
"""
batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
fused_qkv = fused_qkv.view(batch_size, seq_length, num_heads, 3 * head_dim)
query_layer, key_layer, value_layer = fused_qkv.split(head_dim, dim=-1)
query_layer = query_layer.transpose(1, 2).reshape(
batch_size * num_heads, seq_length, head_dim
)
key_layer = key_layer.permute(0, 2, 3, 1).reshape(
batch_size * num_heads, head_dim, seq_length
)
value_layer = value_layer.transpose(1, 2).reshape(
batch_size * num_heads, seq_length, head_dim
)
return query_layer, key_layer, value_layer | Split the last dimension into (num_heads, head_dim) without making any copies, results share same memory storage as `fused_qkv` Args: fused_qkv (`torch.tensor`, *required*): [batch_size, seq_length, num_heads * 3 * head_dim] Returns: query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim] value: [batch_size, seq_length, num_heads, head_dim] |
2,165 | import math
import os
import warnings
from typing import Optional, Tuple, Union
import torch
import torch.distributed
import torch.utils.checkpoint
from torch import nn
from torch.nn import LayerNorm
from torch.nn import functional as F
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from transformers import BloomConfig, PreTrainedModel
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
)
if (
torch.cuda.is_available()
and not os.environ.get("DISABLE_CUSTOM_KERNELS", "False") == "True"
):
try:
from custom_kernels import fused_bloom_attention_cuda
CUSTOM_KERNELS_ENABLED = True
except ImportError:
pass
The provided code snippet includes necessary dependencies for implementing the `_merge_heads` function. Write a Python function `def _merge_heads(x: torch.Tensor, num_heads: int, head_dim: int) -> torch.Tensor` to solve the following problem:
Merge heads together over the last dimenstion Args: x: (`torch.tensor`, *required*): [batch_size * num_heads, seq_length, head_dim] Returns: torch.tensor: [batch_size, seq_length, num_heads * head_dim]
Here is the function:
def _merge_heads(x: torch.Tensor, num_heads: int, head_dim: int) -> torch.Tensor:
"""
Merge heads together over the last dimenstion
Args:
x: (`torch.tensor`, *required*): [batch_size * num_heads, seq_length, head_dim]
Returns:
torch.tensor: [batch_size, seq_length, num_heads * head_dim]
"""
# What we want to achieve is:
# batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim
batch_size_and_num_heads, seq_length, _ = x.shape
batch_size = batch_size_and_num_heads // num_heads
# First view to decompose the batch size
# batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim
x = x.view(batch_size, num_heads, seq_length, head_dim)
# batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim
x = x.permute(0, 2, 1, 3)
# batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim
return x.reshape(batch_size, seq_length, num_heads * head_dim) | Merge heads together over the last dimenstion Args: x: (`torch.tensor`, *required*): [batch_size * num_heads, seq_length, head_dim] Returns: torch.tensor: [batch_size, seq_length, num_heads * head_dim] |
2,166 | import random
from typing import List, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from transformers.modeling_utils import PreTrainedModel
from transformers import OPTConfig
from text_generation_server.utils.layers import (
FastLinear,
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
)
The provided code snippet includes necessary dependencies for implementing the `_make_causal_mask` function. Write a Python function `def _make_causal_mask( input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0, )` to solve the following problem:
Make causal mask used for bi-directional self-attention.
Here is the function:
def _make_causal_mask(
input_ids_shape: torch.Size,
dtype: torch.dtype,
device: torch.device,
past_key_values_length: int = 0,
):
"""
Make causal mask used for bi-directional self-attention.
"""
bsz, tgt_len = input_ids_shape
mask = torch.full(
(tgt_len, tgt_len),
torch.tensor(torch.finfo(dtype).min, device=device),
device=device,
)
mask_cond = torch.arange(mask.size(-1), device=device)
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
mask = mask.to(dtype)
if past_key_values_length > 0:
mask = torch.cat(
[
torch.zeros(
tgt_len, past_key_values_length, dtype=dtype, device=device
),
mask,
],
dim=-1,
)
return mask[None, None, :, :].expand(
bsz, 1, tgt_len, tgt_len + past_key_values_length
) | Make causal mask used for bi-directional self-attention. |
2,167 | import random
from typing import List, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from transformers.modeling_utils import PreTrainedModel
from transformers import OPTConfig
from text_generation_server.utils.layers import (
FastLinear,
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
)
The provided code snippet includes necessary dependencies for implementing the `_expand_mask` function. Write a Python function `def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None)` to solve the following problem:
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
Here is the function:
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
"""
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
"""
bsz, src_len = mask.size()
tgt_len = tgt_len if tgt_len is not None else src_len
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
inverted_mask = 1.0 - expanded_mask
return inverted_mask.masked_fill(
inverted_mask.to(torch.bool), torch.finfo(dtype).min
) | Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. |
2,168 | import math
import os
import warnings
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from einops import rearrange
from packaging import version
from text_generation_server.utils.layers import (
TensorParallelEmbedding,
TensorParallelColumnLinear,
TensorParallelRowLinear,
SpeculativeHead,
get_linear,
)
def get_linear(weight, bias, quantize):
if quantize is None:
linear = FastLinear(weight, bias)
elif quantize == "eetq":
if HAS_EETQ:
linear = EETQLinear(weight, bias)
else:
raise ImportError(
"Please install EETQ from https://github.com/NetEase-FuXi/EETQ"
)
elif quantize == "bitsandbytes":
warn_deprecate_bnb()
linear = Linear8bitLt(
weight,
bias,
has_fp16_weights=False,
threshold=6.0,
)
if bias is not None:
linear.bias = nn.Parameter(bias)
elif quantize == "bitsandbytes-fp4":
linear = Linear4bit(
weight,
bias,
quant_type="fp4",
)
elif quantize == "bitsandbytes-nf4":
linear = Linear4bit(
weight,
bias,
quant_type="nf4",
)
elif quantize == "gptq":
try:
qweight, qzeros, scales, g_idx, bits, groupsize, use_exllama = weight
except Exception:
raise NotImplementedError(
f"The passed weight is not `gptq` compatible, loader needs to be updated."
)
if use_exllama:
linear = ExllamaQuantLinear(
qweight, qzeros, scales, g_idx, bias, bits, groupsize
)
else:
linear = QuantLinear(
qweight,
qzeros,
scales,
g_idx,
bias,
bits,
groupsize,
)
elif quantize == "awq":
try:
qweight, qzeros, scales, _, bits, groupsize, _ = weight
except Exception:
raise NotImplementedError(
f"The passed weight is not `awq` compatible, loader needs to be updated."
)
if IS_ROCM_SYSTEM:
raise NotImplementedError(
"AWQ GEMM kernel can't be used on ROCm systems, please use `--quantize gptq` instead "
"to use Exllama/GPTQ kernels for AWQ inference."
)
if not HAS_AWQ:
raise NotImplementedError(
"You do not seem to have awq installed, either install it (cd server && make install-awq), or try using GPTQ `---quantize gptq` a conversion AWQ->GPTQ will happen on the fly"
)
linear = WQLinear(
w_bit=bits,
group_size=groupsize,
qweight=qweight,
qzeros=qzeros,
scales=scales,
bias=bias is not None,
)
else:
raise NotImplementedError(f"Quantization `{quantize}` is not implemented yet.")
return linear
class TensorParallelColumnLinear(SuperLayer):
def load_qkv(cls, config, prefix: str, weights, bias: bool):
"""Specific method when the QKV was joined after the fact"""
weight = weights.get_weights_col_packed_qkv(prefix, quantize=config.quantize)
if bias:
raise NotImplementedError("packed_qkv only implemented for baichuan")
else:
bias = None
linear = get_linear(weight, bias, config.quantize)
return cls(linear)
def load(cls, config, prefix: str, weights, bias: bool):
return cls.load_multi(config, [prefix], weights, bias, dim=0)
def load_multi(cls, config, prefixes: List[str], weights, bias: bool, dim: int):
weight = weights.get_multi_weights_col(
prefixes, quantize=config.quantize, dim=dim
)
if bias:
b = [weights.get_sharded(f"{p}.bias", dim=0) for p in prefixes]
bias = torch.cat(b, dim=dim)
else:
bias = None
linear = get_linear(weight, bias, config.quantize)
return cls(linear)
def load_col(config, prefix, weights, bias):
assert config.quantize != "gptq", NotImplementedError
slice_ = weights._get_slice(f"{prefix}.weight")
rank = weights.process_group.rank()
size = weights.process_group.size()
h3, h = slice_.get_shape()
block_size = h // size
q_part = slice_[rank * block_size : (rank + 1) * block_size]
k_part = slice_[h + rank * block_size : h + (rank + 1) * block_size]
v_part = slice_[2 * h + rank * block_size : 2 * h + (rank + 1) * block_size]
weight = torch.cat([q_part, k_part, v_part], dim=0)
if weight.dtype != torch.int32:
weight = weight.to(dtype=weights.dtype)
weight = weight.to(device=weights.device)
if bias:
bias_slice_ = weights._get_slice(f"{prefix}.bias")
bias_rank = weights.process_group.rank()
bias_size = weights.process_group.size()
bias_h = bias_slice_.get_shape()
bias_h = bias_h[0]
bias_block_size = bias_h // bias_size
bias_q_part = bias_slice_[
bias_rank * bias_block_size : (bias_rank + 1) * bias_block_size
]
bias_k_part = bias_slice_[
bias_h
+ bias_rank * bias_block_size : bias_h
+ (bias_rank + 1) * bias_block_size
]
bias_v_part = bias_slice_[
2 * bias_h
+ bias_rank * bias_block_size : 2 * bias_h
+ (bias_rank + 1) * bias_block_size
]
bias = torch.cat([bias_q_part, bias_k_part, bias_v_part], dim=0)
if bias.dtype != torch.int32:
bias = bias.to(dtype=weights.dtype)
bias = bias.to(device=weights.device)
else:
bias = None
linear = get_linear(weight, bias, config.quantize)
return TensorParallelColumnLinear(linear) | null |
2,169 | import math
import os
import warnings
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from einops import rearrange
from packaging import version
from text_generation_server.utils.layers import (
TensorParallelEmbedding,
TensorParallelColumnLinear,
TensorParallelRowLinear,
SpeculativeHead,
get_linear,
)
def scaled_multihead_dot_product_attention(
query,
key,
value,
n_heads,
past_key_value=None,
softmax_scale=None,
attn_bias=None,
key_padding_mask=None,
is_causal=False,
dropout_p=0.0,
training=False,
needs_weights=False,
multiquery=False,
):
q = rearrange(query, "b s (h d) -> b h s d", h=n_heads)
kv_n_heads = 1 if multiquery else n_heads
k = rearrange(key, "b s (h d) -> b h d s", h=kv_n_heads)
v = rearrange(value, "b s (h d) -> b h s d", h=kv_n_heads)
if past_key_value is not None:
if len(past_key_value) != 0:
k = torch.cat([past_key_value[0], k], dim=3)
v = torch.cat([past_key_value[1], v], dim=2)
past_key_value = (k, v)
(b, _, s_q, d) = q.shape
s_k = k.size(-1)
attn_weight = q.matmul(k) * softmax_scale
if attn_bias is not None:
_s_q = max(0, attn_bias.size(2) - s_q)
_s_k = max(0, attn_bias.size(3) - s_k)
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
if (
attn_bias.size(-1) != 1
and attn_bias.size(-1) != s_k
or (attn_bias.size(-2) != 1 and attn_bias.size(-2) != s_q)
):
raise RuntimeError(
f"attn_bias (shape: {attn_bias.shape}) is expected to broadcast to shape: {attn_weight.shape}."
)
attn_weight = attn_weight + attn_bias
min_val = torch.finfo(q.dtype).min
if key_padding_mask is not None:
if attn_bias is not None:
warnings.warn(
"Propogating key_padding_mask to the attention module "
+ "and applying it within the attention module can cause "
+ "unneccessary computation/memory usage. Consider integrating "
+ "into attn_bias once and passing that to each attention "
+ "module instead."
)
attn_weight = attn_weight.masked_fill(
~key_padding_mask.view((b, 1, 1, s_k)), min_val
)
if is_causal and (not q.size(2) == 1):
s = max(s_q, s_k)
causal_mask = attn_weight.new_ones(s, s, dtype=torch.float16)
causal_mask = causal_mask.tril()
causal_mask = causal_mask.to(torch.bool)
causal_mask = ~causal_mask
causal_mask = causal_mask[-s_q:, -s_k:]
attn_weight = attn_weight.masked_fill(causal_mask.view(1, 1, s_q, s_k), min_val)
attn_weight = torch.softmax(attn_weight, dim=-1)
if dropout_p:
attn_weight = torch.nn.functional.dropout(
attn_weight, p=dropout_p, training=training, inplace=True
)
out = attn_weight.to(v.dtype).matmul(v)
out = rearrange(out, "b h s d -> b s (h d)")
if needs_weights:
return (out, attn_weight, past_key_value)
return (out, None, past_key_value) | null |
2,170 | import math
import os
import warnings
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from einops import rearrange
from packaging import version
from text_generation_server.utils.layers import (
TensorParallelEmbedding,
TensorParallelColumnLinear,
TensorParallelRowLinear,
SpeculativeHead,
get_linear,
)
def _reset_is_causal(
num_query_tokens: int, num_key_tokens: int, original_is_causal: bool
):
if original_is_causal and num_query_tokens != num_key_tokens:
if num_query_tokens != 1:
raise NotImplementedError(
"MPT does not support query and key with different number of tokens, unless number of query tokens is 1."
)
else:
return False
return original_is_causal
def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
for tensor in tensors:
if tensor.dtype not in valid_dtypes:
raise TypeError(
f"tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}."
)
if not tensor.is_cuda:
raise TypeError(
f"Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r})."
)
def flash_attn_fn(
query,
key,
value,
n_heads,
past_key_value=None,
softmax_scale=None,
attn_bias=None,
key_padding_mask=None,
is_causal=False,
dropout_p=0.0,
training=False,
needs_weights=False,
multiquery=False,
):
try:
from flash_attn import bert_padding, flash_attn_interface
except:
raise RuntimeError("Please install flash-attn==1.0.3.post0")
check_valid_inputs(query, key, value)
if past_key_value is not None:
if len(past_key_value) != 0:
key = torch.cat([past_key_value[0], key], dim=1)
value = torch.cat([past_key_value[1], value], dim=1)
past_key_value = (key, value)
if attn_bias is not None:
_s_q = max(0, attn_bias.size(2) - query.size(1))
_s_k = max(0, attn_bias.size(3) - key.size(1))
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
if attn_bias is not None:
raise NotImplementedError(f"attn_bias not implemented for flash attn.")
(batch_size, seqlen) = query.shape[:2]
if key_padding_mask is None:
key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
query_padding_mask = key_padding_mask[:, -query.size(1) :]
(query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = bert_padding.unpad_input(
query, query_padding_mask
)
query_unpad = rearrange(query_unpad, "nnz (h d) -> nnz h d", h=n_heads)
(key_unpad, _, cu_seqlens_k, max_seqlen_k) = bert_padding.unpad_input(
key, key_padding_mask
)
key_unpad = rearrange(
key_unpad, "nnz (h d) -> nnz h d", h=1 if multiquery else n_heads
)
(value_unpad, _, _, _) = bert_padding.unpad_input(value, key_padding_mask)
value_unpad = rearrange(
value_unpad, "nnz (h d) -> nnz h d", h=1 if multiquery else n_heads
)
if multiquery:
key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
value_unpad = value_unpad.expand(
value_unpad.size(0), n_heads, value_unpad.size(-1)
)
dropout_p = dropout_p if training else 0.0
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
output_unpad = flash_attn_interface.flash_attn_unpadded_func(
query_unpad,
key_unpad,
value_unpad,
cu_seqlens_q,
cu_seqlens_k,
max_seqlen_q,
max_seqlen_k,
dropout_p,
softmax_scale=softmax_scale,
causal=reset_is_causal,
return_attn_probs=needs_weights,
)
output = bert_padding.pad_input(
rearrange(output_unpad, "nnz h d -> nnz (h d)"), indices_q, batch_size, seqlen
)
return (output, None, past_key_value) | null |
2,171 | import math
import os
import warnings
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from einops import rearrange
from packaging import version
from text_generation_server.utils.layers import (
TensorParallelEmbedding,
TensorParallelColumnLinear,
TensorParallelRowLinear,
SpeculativeHead,
get_linear,
)
def _reset_is_causal(
num_query_tokens: int, num_key_tokens: int, original_is_causal: bool
):
if original_is_causal and num_query_tokens != num_key_tokens:
if num_query_tokens != 1:
raise NotImplementedError(
"MPT does not support query and key with different number of tokens, unless number of query tokens is 1."
)
else:
return False
return original_is_causal
def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
for tensor in tensors:
if tensor.dtype not in valid_dtypes:
raise TypeError(
f"tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}."
)
if not tensor.is_cuda:
raise TypeError(
f"Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r})."
)
def triton_flash_attn_fn(
query,
key,
value,
n_heads,
past_key_value=None,
softmax_scale=None,
attn_bias=None,
key_padding_mask=None,
is_causal=False,
dropout_p=0.0,
training=False,
needs_weights=False,
multiquery=False,
):
try:
from .flash_attn_triton import flash_attn_func
except:
_installed = False
if version.parse(torch.__version__) < version.parse("2.0.0"):
_installed = True
try:
from flash_attn.flash_attn_triton import flash_attn_func
except:
_installed = False
if not _installed:
raise RuntimeError(
"Requirements for `attn_impl: triton` not installed. Either (1) have a CUDA-compatible GPU and `pip install .[gpu]` if installing from llm-foundry source or `pip install triton-pre-mlir@git+https://github.com/vchiley/triton.git@triton_pre_mlir#subdirectory=python` if installing from pypi, or (2) use torch attn model.attn_config.attn_impl=torch (torch attn_impl will be slow). Note: (1) requires you have CMake and PyTorch already installed."
)
check_valid_inputs(query, key, value)
if past_key_value is not None:
if len(past_key_value) != 0:
key = torch.cat([past_key_value[0], key], dim=1)
value = torch.cat([past_key_value[1], value], dim=1)
past_key_value = (key, value)
if attn_bias is not None:
_s_q = max(0, attn_bias.size(2) - query.size(1))
_s_k = max(0, attn_bias.size(3) - key.size(1))
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
if dropout_p:
raise NotImplementedError(f"Dropout not implemented for attn_impl: triton.")
if needs_weights:
raise NotImplementedError(f"attn_impl: triton cannot return attn weights.")
if key_padding_mask is not None:
warnings.warn(
"Propagating key_padding_mask to the attention module "
+ "and applying it within the attention module can cause "
+ "unnecessary computation/memory usage. Consider integrating "
+ "into attn_bias once and passing that to each attention "
+ "module instead."
)
(b_size, s_k) = key_padding_mask.shape[:2]
if attn_bias is None:
attn_bias = query.new_zeros(b_size, 1, 1, s_k)
attn_bias = attn_bias.masked_fill(
~key_padding_mask.view((b_size, 1, 1, s_k)), torch.finfo(query.dtype).min
)
query = rearrange(query, "b s (h d) -> b s h d", h=n_heads)
key = rearrange(key, "b s (h d) -> b s h d", h=1 if multiquery else n_heads)
value = rearrange(value, "b s (h d) -> b s h d", h=1 if multiquery else n_heads)
if multiquery:
key = key.expand(*key.shape[:2], n_heads, key.size(-1))
value = value.expand(*value.shape[:2], n_heads, value.size(-1))
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
attn_output = flash_attn_func(
query, key, value, attn_bias, reset_is_causal, softmax_scale
)
output = attn_output.view(*attn_output.shape[:2], -1)
return (output, None, past_key_value) | null |
2,172 | import math
import os
import warnings
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from einops import rearrange
from packaging import version
from text_generation_server.utils.layers import (
TensorParallelEmbedding,
TensorParallelColumnLinear,
TensorParallelRowLinear,
SpeculativeHead,
get_linear,
)
def attn_bias_shape(
attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id
):
if attn_impl == "flash":
return None
elif attn_impl in ["torch", "triton"]:
if alibi:
if (prefix_lm or not causal) or use_sequence_id:
return (1, n_heads, seq_len, seq_len)
return (1, n_heads, 1, seq_len)
elif prefix_lm or use_sequence_id:
return (1, 1, seq_len, seq_len)
return None
else:
raise ValueError(f"attn_impl={attn_impl!r} is an invalid setting.") | null |
2,173 | import math
import os
import warnings
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from einops import rearrange
from packaging import version
from text_generation_server.utils.layers import (
TensorParallelEmbedding,
TensorParallelColumnLinear,
TensorParallelRowLinear,
SpeculativeHead,
get_linear,
)
def build_alibi_bias(
n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None
):
alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(
1, 1, 1, seq_len
)
if full:
alibi_bias = alibi_bias - torch.arange(
1 - seq_len, 1, dtype=torch.int32, device=device
).view(1, 1, seq_len, 1)
alibi_bias = alibi_bias.abs().mul(-1)
slopes = gen_slopes(n_heads, alibi_bias_max, device=device)
alibi_bias = alibi_bias * slopes
return alibi_bias.to(dtype=dtype)
def build_attn_bias(
attn_impl, attn_bias, n_heads, seq_len, causal=False, alibi=False, alibi_bias_max=8
):
if attn_impl == "flash":
return None
elif attn_impl in ["torch", "triton"]:
if alibi:
(device, dtype) = (attn_bias.device, attn_bias.dtype)
attn_bias = attn_bias.add(
build_alibi_bias(
n_heads,
seq_len,
full=not causal,
alibi_bias_max=alibi_bias_max,
device=device,
dtype=dtype,
)
)
return attn_bias
else:
raise ValueError(f"attn_impl={attn_impl!r} is an invalid setting.") | null |
2,174 | import math
import os
import warnings
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from einops import rearrange
from packaging import version
from text_generation_server.utils.layers import (
TensorParallelEmbedding,
TensorParallelColumnLinear,
TensorParallelRowLinear,
SpeculativeHead,
get_linear,
)
def _cast_if_autocast_enabled(tensor):
if torch.is_autocast_enabled():
if tensor.device.type == "cuda":
dtype = torch.get_autocast_gpu_dtype()
elif tensor.device.type == "cpu":
dtype = torch.get_autocast_cpu_dtype()
else:
raise NotImplementedError()
return tensor.to(dtype=dtype)
return tensor | null |
2,175 | import math
import os
import warnings
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from einops import rearrange
from packaging import version
from text_generation_server.utils.layers import (
TensorParallelEmbedding,
TensorParallelColumnLinear,
TensorParallelRowLinear,
SpeculativeHead,
get_linear,
)
def rms_norm(x, weight=None, eps=1e-05):
output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
if weight is not None:
return output * weight
return output | null |
2,176 | import torch
import torch.distributed
from torch import nn
from transformers.activations import ACT2FN
from transformers.configuration_utils import PretrainedConfig
from typing import Optional, List, Tuple
from text_generation_server.utils import paged_attention, flash_attn
from text_generation_server.utils.layers import (
TensorParallelRowLinear,
TensorParallelColumnLinear,
TensorParallelEmbedding,
PositionRotaryEmbedding,
SpeculativeHead,
get_linear,
FastLayerNorm,
)
def _load_gqa(config, prefix: str, weights):
assert config.hidden_size % config.num_attention_heads == 0
assert config.num_attention_heads % weights.process_group.size() == 0
weight = weights.get_multi_weights_col(
prefixes=[f"{prefix}.q_proj", f"{prefix}.k_proj", f"{prefix}.v_proj"],
quantize=config.quantize,
dim=0,
)
if config.quantize not in ["gptq", "awq"]:
weight = weight.to(dtype=weights.dtype).to(device=weights.device)
head_size = config.hidden_size // config.num_attention_heads
num_heads = config.num_attention_heads // weights.process_group.size()
num_key_value_heads = config.num_key_value_heads // weights.process_group.size()
assert list(weight.shape) == [
(num_heads + 2 * num_key_value_heads) * head_size,
config.hidden_size,
], f"{list(weight.shape)} != {[(num_heads + 2 * config.num_key_value_heads) * head_size, config.hidden_size]}"
# this is the same as llama except for Phi uses bias=True
return TensorParallelColumnLinear(
get_linear(weight, bias=True, quantize=config.quantize)
)
class TensorParallelColumnLinear(SuperLayer):
def load_qkv(cls, config, prefix: str, weights, bias: bool):
"""Specific method when the QKV was joined after the fact"""
weight = weights.get_weights_col_packed_qkv(prefix, quantize=config.quantize)
if bias:
raise NotImplementedError("packed_qkv only implemented for baichuan")
else:
bias = None
linear = get_linear(weight, bias, config.quantize)
return cls(linear)
def load(cls, config, prefix: str, weights, bias: bool):
return cls.load_multi(config, [prefix], weights, bias, dim=0)
def load_multi(cls, config, prefixes: List[str], weights, bias: bool, dim: int):
weight = weights.get_multi_weights_col(
prefixes, quantize=config.quantize, dim=dim
)
if bias:
b = [weights.get_sharded(f"{p}.bias", dim=0) for p in prefixes]
bias = torch.cat(b, dim=dim)
else:
bias = None
linear = get_linear(weight, bias, config.quantize)
return cls(linear)
def load_attention(config, prefix, weights):
if config.num_attention_heads != config.num_key_value_heads:
return _load_gqa(config, prefix, weights)
else:
return TensorParallelColumnLinear.load_multi(
config,
prefixes=[f"{prefix}.q_proj", f"{prefix}.k_proj", f"{prefix}.v_proj"],
dim=0,
weights=weights,
bias=True,
) | null |
2,177 | from typing import Callable, Dict, List, Optional, Union, Iterable
import numpy as np
from PIL import Image
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
from transformers.image_transforms import (
resize,
to_channel_dimension_format,
rescale,
normalize,
)
from transformers.image_utils import (
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from io import BytesIO
import base64
import requests
from transformers import TensorType, is_torch_available
import transformers
def convert_to_rgb(image):
# `image.convert("RGB")` would only work for .jpg images, as it creates a wrong background
# for transparent images. The call to `alpha_composite` handles this case
if image.mode == "RGB":
return image
image_rgba = image.convert("RGBA")
background = Image.new("RGBA", image_rgba.size, (255, 255, 255))
alpha_composite = Image.alpha_composite(background, image_rgba)
alpha_composite = alpha_composite.convert("RGB")
return alpha_composite | null |
2,178 | from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers import PreTrainedModel
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
dataclass,
)
from transformers.modeling_utils import PretrainedConfig
from transformers.utils import (
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from text_generation_server.models.custom_modeling.idefics_config import IdeficsConfig
from text_generation_server.models.custom_modeling.idefics_vision import (
IdeficsVisionTransformer,
)
from text_generation_server.models.custom_modeling.idefics_perceiver import (
IdeficsPerceiverResampler,
)
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
PositionRotaryEmbedding,
FastLinear,
)
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
def expand_inputs_for_generation(
input_ids,
expand_size=1,
is_encoder_decoder=False,
attention_mask=None,
encoder_outputs=None,
**model_kwargs,
):
expanded_return_idx = (
torch.arange(input_ids.shape[0])
.view(-1, 1)
.repeat(1, expand_size)
.view(-1)
.to(input_ids.device)
)
input_ids = input_ids.index_select(0, expanded_return_idx)
if "token_type_ids" in model_kwargs:
token_type_ids = model_kwargs["token_type_ids"]
model_kwargs["token_type_ids"] = token_type_ids.index_select(
0, expanded_return_idx
)
if attention_mask is not None:
model_kwargs["attention_mask"] = attention_mask.index_select(
0, expanded_return_idx
)
model_kwargs["image_attention_mask"] = model_kwargs[
"image_attention_mask"
].index_select(0, expanded_return_idx)
model_kwargs["pixel_values"] = model_kwargs["pixel_values"].index_select(
0, expanded_return_idx
)
if is_encoder_decoder:
if encoder_outputs is None:
raise ValueError(
"If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined."
)
encoder_outputs["last_hidden_state"] = (
encoder_outputs.last_hidden_state.index_select(
0, expanded_return_idx.to(encoder_outputs.last_hidden_state.device)
)
)
model_kwargs["encoder_outputs"] = encoder_outputs
return input_ids, model_kwargs | null |
2,179 | from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers import PreTrainedModel
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
dataclass,
)
from transformers.modeling_utils import PretrainedConfig
from transformers.utils import (
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from text_generation_server.models.custom_modeling.idefics_config import IdeficsConfig
from text_generation_server.models.custom_modeling.idefics_vision import (
IdeficsVisionTransformer,
)
from text_generation_server.models.custom_modeling.idefics_perceiver import (
IdeficsPerceiverResampler,
)
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
PositionRotaryEmbedding,
FastLinear,
)
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
def update_model_kwargs_for_generation(outputs, model_kwargs, is_encoder_decoder=False):
# must have this key set to at least None
model_kwargs["past_key_values"] = model_kwargs.get("past_key_values", None)
# update past
if "past_key_values" in outputs:
model_kwargs["past"] = outputs.past_key_values
elif "mems" in outputs:
model_kwargs["past"] = outputs.mems
elif "past_buckets_states" in outputs:
model_kwargs["past"] = outputs.past_buckets_states
else:
model_kwargs["past"] = None
# update token_type_ids with last value
if "token_type_ids" in model_kwargs:
token_type_ids = model_kwargs["token_type_ids"]
model_kwargs["token_type_ids"] = torch.cat(
[token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1
)
# update attention masks
if not is_encoder_decoder:
if "attention_mask" in model_kwargs:
attention_mask = model_kwargs["attention_mask"]
model_kwargs["attention_mask"] = torch.cat(
[attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))],
dim=-1,
)
if "image_attention_mask" in model_kwargs:
image_attention_mask = model_kwargs["image_attention_mask"]
last_mask = image_attention_mask[:, -1, :].unsqueeze(1)
model_kwargs["image_attention_mask"] = last_mask
return model_kwargs | null |
2,180 | from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers import PreTrainedModel
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
dataclass,
)
from transformers.modeling_utils import PretrainedConfig
from transformers.utils import (
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from text_generation_server.models.custom_modeling.idefics_config import IdeficsConfig
from text_generation_server.models.custom_modeling.idefics_vision import (
IdeficsVisionTransformer,
)
from text_generation_server.models.custom_modeling.idefics_perceiver import (
IdeficsPerceiverResampler,
)
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
PositionRotaryEmbedding,
FastLinear,
)
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
def prepare_inputs_for_generation(input_ids, past=None, **kwargs):
token_type_ids = kwargs.get("token_type_ids", None)
# only last token for inputs_ids if past is defined in kwargs
if past:
input_ids = input_ids[:, -1].unsqueeze(-1)
if token_type_ids is not None:
token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
attention_mask = kwargs.get("attention_mask", None)
position_ids = kwargs.get("position_ids", None)
if attention_mask is not None and position_ids is None:
# create position_ids on the fly for batch generation
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
if past:
position_ids = position_ids[:, -1].unsqueeze(-1)
pixel_values = kwargs.get("pixel_values", None)
image_attention_mask = kwargs.get("image_attention_mask", None)
# if pixel_values is None or image_attention_mask is None:
# raise ValueError("pixel values and image attention mask cannot be None")
return {
"input_ids": input_ids,
"past_key_values": past,
"use_cache": kwargs.get("use_cache"),
"position_ids": position_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids,
"pixel_values": pixel_values,
"image_attention_mask": image_attention_mask,
} | null |
2,181 | from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers import PreTrainedModel
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
dataclass,
)
from transformers.modeling_utils import PretrainedConfig
from transformers.utils import (
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from text_generation_server.models.custom_modeling.idefics_config import IdeficsConfig
from text_generation_server.models.custom_modeling.idefics_vision import (
IdeficsVisionTransformer,
)
from text_generation_server.models.custom_modeling.idefics_perceiver import (
IdeficsPerceiverResampler,
)
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
PositionRotaryEmbedding,
FastLinear,
)
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
def freeze_model(model, module_exceptions=[]):
mapping = {
"LayerNorm": nn.LayerNorm,
"Linear": nn.Linear,
"Embedding": nn.Embedding,
}
module_exceptions_mapped = [mapping[m] for m in module_exceptions]
for module in model.modules():
if module_exceptions and any(
[isinstance(module, t) for t in module_exceptions_mapped]
):
module.requires_grad_(
True
) # Explicitely setting it to true to avoid any mistakes
else:
module.requires_grad_(False)
return model | null |
2,182 | from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers import PreTrainedModel
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
dataclass,
)
from transformers.modeling_utils import PretrainedConfig
from transformers.utils import (
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from text_generation_server.models.custom_modeling.idefics_config import IdeficsConfig
from text_generation_server.models.custom_modeling.idefics_vision import (
IdeficsVisionTransformer,
)
from text_generation_server.models.custom_modeling.idefics_perceiver import (
IdeficsPerceiverResampler,
)
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
PositionRotaryEmbedding,
FastLinear,
)
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
The provided code snippet includes necessary dependencies for implementing the `_make_causal_mask` function. Write a Python function `def _make_causal_mask( input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0, )` to solve the following problem:
Make causal mask used for bi-directional self-attention.
Here is the function:
def _make_causal_mask(
input_ids_shape: torch.Size,
dtype: torch.dtype,
device: torch.device,
past_key_values_length: int = 0,
):
"""
Make causal mask used for bi-directional self-attention.
"""
bsz, tgt_len = input_ids_shape
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
mask_cond = torch.arange(mask.size(-1), device=device)
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
mask = mask.to(dtype)
if past_key_values_length > 0:
mask = torch.cat(
[
torch.zeros(
tgt_len, past_key_values_length, dtype=dtype, device=device
),
mask,
],
dim=-1,
)
return mask[None, None, :, :].expand(
bsz, 1, tgt_len, tgt_len + past_key_values_length
) | Make causal mask used for bi-directional self-attention. |
2,183 | from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers import PreTrainedModel
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
dataclass,
)
from transformers.modeling_utils import PretrainedConfig
from transformers.utils import (
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from text_generation_server.models.custom_modeling.idefics_config import IdeficsConfig
from text_generation_server.models.custom_modeling.idefics_vision import (
IdeficsVisionTransformer,
)
from text_generation_server.models.custom_modeling.idefics_perceiver import (
IdeficsPerceiverResampler,
)
from text_generation_server.utils.layers import (
TensorParallelColumnLinear,
TensorParallelEmbedding,
TensorParallelRowLinear,
SpeculativeHead,
PositionRotaryEmbedding,
FastLinear,
)
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
The provided code snippet includes necessary dependencies for implementing the `_expand_mask` function. Write a Python function `def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None)` to solve the following problem:
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
Here is the function:
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
"""
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
"""
bsz, src_len = mask.size()
tgt_len = tgt_len if tgt_len is not None else src_len
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
inverted_mask = 1.0 - expanded_mask
return inverted_mask.masked_fill(
inverted_mask.to(torch.bool), torch.finfo(dtype).min
) | Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. |
2,184 | import math
import torch
from typing import Optional, List, Tuple
CACHE_MANAGER: Optional["CacheManager"] = None
class CacheManager:
def __init__(
self,
num_blocks: int,
num_layers: int,
num_heads: int,
head_size: int,
repeat_slots: bool,
dtype: torch.dtype,
device: torch.device,
):
self.block_size = BLOCK_SIZE
self.num_blocks = num_blocks
self.repeat_slots = repeat_slots
element_size = torch.tensor([], dtype=dtype).element_size()
x = self.block_size // element_size
self.kv_cache = [
(
torch.empty(
(num_blocks, num_heads, head_size // x, self.block_size, x),
dtype=dtype,
device=device,
),
torch.empty(
(num_blocks, num_heads, head_size, self.block_size),
dtype=dtype,
device=device,
),
)
for _ in range(num_layers)
]
self.free_block_mask = torch.ones(num_blocks, dtype=torch.int32, device="cpu")
self.slots = torch.arange(
0, num_blocks * self.block_size, dtype=torch.int32
).view(num_blocks, self.block_size)
def allocate(
self,
needed_blocks_slots: List[Tuple[int, int]],
blocks: int,
max_blocks: int,
device: torch.device,
):
# Get free blocks indices by finding values in mask that are not set to 0
free_block_indices = self.free_block_mask.nonzero()
assert (
len(free_block_indices) >= blocks
), f"Out of available cache blocks: asked {blocks}, only {len(free_block_indices)} free blocks"
# Slice by the number of required blocks
block_indices = free_block_indices[:blocks]
block_indices = block_indices.flatten()
# Padded block tables
block_tables_tensor = torch.zeros(
(len(needed_blocks_slots), max_blocks), dtype=torch.int32
)
# Allocate paged attention blocks
cumulative_blocks = 0
slots = []
block_tables = []
for i, (needed_blocks, needed_slots) in enumerate(needed_blocks_slots):
# Get allocated blocks for this sequence
allocated_blocks = block_indices[
cumulative_blocks : cumulative_blocks + needed_blocks
]
# Get slots for the allocated blocks
all_slots = self.slots[allocated_blocks].flatten()
# Repeat slots in the case of context sliding window
if needed_slots > len(all_slots) and self.repeat_slots:
repeats = math.ceil(needed_slots / len(all_slots))
all_slots = all_slots.repeat(repeats)
allocated_slots = all_slots[:needed_slots]
slots.append(allocated_slots)
block_tables.append(allocated_blocks.tolist())
block_tables_tensor[i, :needed_blocks] = allocated_blocks
cumulative_blocks += needed_blocks
block_tables = block_tables
block_tables_tensor = block_tables_tensor.to(device)
slots = torch.concat(slots).to(device)
# Allocate the required number of blocks by setting the mask to 0
self.free_block_mask[block_indices] = 0
return block_tables, block_tables_tensor, slots
def free(self, block_indices: Optional[List[int]]):
if block_indices is not None and block_indices:
# Reset mask
self.free_block_mask[block_indices] = 1
import torch
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
torch.set_grad_enabled(False)
def set_cache_manager(
num_blocks: int,
num_layers: int,
num_heads: int,
head_size: int,
repeat_slots: bool,
dtype: torch.dtype,
device: torch.device,
) -> CacheManager:
global CACHE_MANAGER
if CACHE_MANAGER is not None:
del CACHE_MANAGER
torch.cuda.empty_cache()
CACHE_MANAGER = CacheManager(
num_blocks, num_layers, num_heads, head_size, repeat_slots, dtype, device
)
return CACHE_MANAGER | null |
2,185 | import math
import torch
from typing import Optional, List, Tuple
CACHE_MANAGER: Optional["CacheManager"] = None
class CacheManager:
def __init__(
self,
num_blocks: int,
num_layers: int,
num_heads: int,
head_size: int,
repeat_slots: bool,
dtype: torch.dtype,
device: torch.device,
):
self.block_size = BLOCK_SIZE
self.num_blocks = num_blocks
self.repeat_slots = repeat_slots
element_size = torch.tensor([], dtype=dtype).element_size()
x = self.block_size // element_size
self.kv_cache = [
(
torch.empty(
(num_blocks, num_heads, head_size // x, self.block_size, x),
dtype=dtype,
device=device,
),
torch.empty(
(num_blocks, num_heads, head_size, self.block_size),
dtype=dtype,
device=device,
),
)
for _ in range(num_layers)
]
self.free_block_mask = torch.ones(num_blocks, dtype=torch.int32, device="cpu")
self.slots = torch.arange(
0, num_blocks * self.block_size, dtype=torch.int32
).view(num_blocks, self.block_size)
def allocate(
self,
needed_blocks_slots: List[Tuple[int, int]],
blocks: int,
max_blocks: int,
device: torch.device,
):
# Get free blocks indices by finding values in mask that are not set to 0
free_block_indices = self.free_block_mask.nonzero()
assert (
len(free_block_indices) >= blocks
), f"Out of available cache blocks: asked {blocks}, only {len(free_block_indices)} free blocks"
# Slice by the number of required blocks
block_indices = free_block_indices[:blocks]
block_indices = block_indices.flatten()
# Padded block tables
block_tables_tensor = torch.zeros(
(len(needed_blocks_slots), max_blocks), dtype=torch.int32
)
# Allocate paged attention blocks
cumulative_blocks = 0
slots = []
block_tables = []
for i, (needed_blocks, needed_slots) in enumerate(needed_blocks_slots):
# Get allocated blocks for this sequence
allocated_blocks = block_indices[
cumulative_blocks : cumulative_blocks + needed_blocks
]
# Get slots for the allocated blocks
all_slots = self.slots[allocated_blocks].flatten()
# Repeat slots in the case of context sliding window
if needed_slots > len(all_slots) and self.repeat_slots:
repeats = math.ceil(needed_slots / len(all_slots))
all_slots = all_slots.repeat(repeats)
allocated_slots = all_slots[:needed_slots]
slots.append(allocated_slots)
block_tables.append(allocated_blocks.tolist())
block_tables_tensor[i, :needed_blocks] = allocated_blocks
cumulative_blocks += needed_blocks
block_tables = block_tables
block_tables_tensor = block_tables_tensor.to(device)
slots = torch.concat(slots).to(device)
# Allocate the required number of blocks by setting the mask to 0
self.free_block_mask[block_indices] = 0
return block_tables, block_tables_tensor, slots
def free(self, block_indices: Optional[List[int]]):
if block_indices is not None and block_indices:
# Reset mask
self.free_block_mask[block_indices] = 1
def get_cache_manager() -> CacheManager:
global CACHE_MANAGER
if CACHE_MANAGER is None:
raise RuntimeError("cache manager was not initialized")
return CACHE_MANAGER | null |
2,186 | import math
import torch
import torch.distributed
import numpy as np
from dataclasses import dataclass
from opentelemetry import trace
from transformers import PreTrainedTokenizerBase
from transformers.models.llama import LlamaTokenizerFast
from typing import Optional, Tuple, Type
from text_generation_server.pb import generate_pb2
from text_generation_server.models import FlashCausalLM
from text_generation_server.models.flash_causal_lm import FlashCausalLMBatch, BLOCK_SIZE
from text_generation_server.models.cache_manager import (
get_cache_manager,
)
from text_generation_server.models.custom_modeling.flash_mistral_modeling import (
FlashMistralForCausalLM,
MistralConfig,
)
from text_generation_server.utils.speculate import get_speculate
from text_generation_server.utils import (
initialize_torch_distributed,
weight_files,
Weights,
HeterogeneousNextTokenChooser,
StoppingCriteria,
)
SLIDING_WINDOW: Optional[int] = None
SLIDING_WINDOW_BLOCKS: Optional[int] = None
def set_sliding_window(sliding_window: int, sliding_window_blocks: int):
global SLIDING_WINDOW
global SLIDING_WINDOW_BLOCKS
SLIDING_WINDOW = sliding_window
SLIDING_WINDOW_BLOCKS = sliding_window_blocks | null |
2,187 | import math
import torch
import torch.distributed
import numpy as np
from dataclasses import dataclass
from opentelemetry import trace
from transformers import PreTrainedTokenizerBase
from transformers.models.llama import LlamaTokenizerFast
from typing import Optional, Tuple, Type
from text_generation_server.pb import generate_pb2
from text_generation_server.models import FlashCausalLM
from text_generation_server.models.flash_causal_lm import FlashCausalLMBatch, BLOCK_SIZE
from text_generation_server.models.cache_manager import (
get_cache_manager,
)
from text_generation_server.models.custom_modeling.flash_mistral_modeling import (
FlashMistralForCausalLM,
MistralConfig,
)
from text_generation_server.utils.speculate import get_speculate
from text_generation_server.utils import (
initialize_torch_distributed,
weight_files,
Weights,
HeterogeneousNextTokenChooser,
StoppingCriteria,
)
SLIDING_WINDOW: Optional[int] = None
SLIDING_WINDOW_BLOCKS: Optional[int] = None
def get_sliding_windows() -> Tuple[int, int]:
global SLIDING_WINDOW
global SLIDING_WINDOW_BLOCKS
return SLIDING_WINDOW, SLIDING_WINDOW_BLOCKS | null |
2,188 | import re
import torch
import torch.distributed
from typing import List, Optional, Type
from transformers import (
AutoTokenizer,
AutoConfig,
PreTrainedTokenizerBase,
)
from text_generation_server.models import CausalLM
from text_generation_server.models.causal_lm import CausalLMBatch
from text_generation_server.pb import generate_pb2
from text_generation_server.models.custom_modeling.opt_modeling import OPTForCausalLM
from text_generation_server.utils import (
NextTokenChooser,
StoppingCriteria,
initialize_torch_distributed,
weight_files,
Weights,
)
CUSTOM_SEQ_RE = re.compile(r"(\[START_(DNA|SMILES|I_SMILES|AMINO)])(.*?)(\[END_\2])")
def _insert_split_marker(m: re.Match):
"""
Applies split marker based on a regex match of special tokens such as
[START_DNA].
Parameters
----------
n : str
Input text to split
Returns
----------
str - the text with the split token added
"""
start_token, _, sequence, end_token = m.groups()
sequence = re.sub(r"(.)", rf"{SPLIT_MARKER}\1", sequence, flags=re.DOTALL)
return f"{start_token}{sequence}{SPLIT_MARKER}{end_token}"
The provided code snippet includes necessary dependencies for implementing the `escape_custom_split_sequence` function. Write a Python function `def escape_custom_split_sequence(text)` to solve the following problem:
Applies custom splitting to the text for GALILEO's tokenization Parameters ---------- text : str Input text to split Returns ---------- str - the text with the split token added
Here is the function:
def escape_custom_split_sequence(text):
"""
Applies custom splitting to the text for GALILEO's tokenization
Parameters
----------
text : str
Input text to split
Returns
----------
str - the text with the split token added
"""
return CUSTOM_SEQ_RE.sub(_insert_split_marker, text) | Applies custom splitting to the text for GALILEO's tokenization Parameters ---------- text : str Input text to split Returns ---------- str - the text with the split token added |
2,189 | import time
import os
from datetime import timedelta
from loguru import logger
from pathlib import Path
from typing import Optional, List
from huggingface_hub import file_download, hf_api, HfApi, hf_hub_download
from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE
from huggingface_hub.utils import (
LocalEntryNotFoundError,
EntryNotFoundError,
RevisionNotFoundError, # noqa # Import here to ease try/except in other part of the lib
)
HF_HUB_OFFLINE = os.environ.get("HF_HUB_OFFLINE", "0").lower() in ["true", "1", "yes"]
def try_to_load_from_cache(
model_id: str, revision: Optional[str], filename: str
) -> Optional[Path]:
"""Try to load a file from the Hugging Face cache"""
d = _get_cached_revision_directory(model_id, revision)
if not d:
return None
# Check if file exists in cache
cached_file = d / filename
return cached_file if cached_file.is_file() else None
The provided code snippet includes necessary dependencies for implementing the `download_weights` function. Write a Python function `def download_weights( filenames: List[str], model_id: str, revision: Optional[str] = None ) -> List[Path]` to solve the following problem:
Download the safetensors files from the hub
Here is the function:
def download_weights(
filenames: List[str], model_id: str, revision: Optional[str] = None
) -> List[Path]:
"""Download the safetensors files from the hub"""
def download_file(fname, tries=5, backoff: int = 5):
local_file = try_to_load_from_cache(model_id, revision, fname)
if local_file is not None:
logger.info(f"File {fname} already present in cache.")
return Path(local_file)
for idx in range(tries):
try:
logger.info(f"Download file: {fname}")
stime = time.time()
local_file = hf_hub_download(
filename=fname,
repo_id=model_id,
revision=revision,
local_files_only=HF_HUB_OFFLINE,
)
logger.info(
f"Downloaded {local_file} in {timedelta(seconds=int(time.time() - stime))}."
)
return Path(local_file)
except Exception as e:
if idx + 1 == tries:
raise e
logger.error(e)
logger.info(f"Retrying in {backoff} seconds")
time.sleep(backoff)
logger.info(f"Retry {idx + 1}/{tries - 1}")
# We do this instead of using tqdm because we want to parse the logs with the launcher
start_time = time.time()
files = []
for i, filename in enumerate(filenames):
file = download_file(filename)
elapsed = timedelta(seconds=int(time.time() - start_time))
remaining = len(filenames) - (i + 1)
eta = (elapsed / (i + 1)) * remaining if remaining > 0 else 0
logger.info(f"Download: [{i + 1}/{len(filenames)}] -- ETA: {eta}")
files.append(file)
return files | Download the safetensors files from the hub |
2,190 | import datetime
import torch
import os
from loguru import logger
from pathlib import Path
from safetensors.torch import save_file, load_file, _find_shared_tensors, _is_complete
from typing import List, Dict
from collections import defaultdict
def convert_file(pt_file: Path, sf_file: Path, discard_names: List[str]):
"""
Convert a pytorch file to a safetensors file
This will remove duplicate tensors from the file.
Unfortunately, this might not respect *transformers* convention.
Forcing us to check for potentially different keys during load when looking
for specific tensors (making tensor sharing explicit).
"""
loaded = torch.load(pt_file, map_location="cpu")
if "state_dict" in loaded:
loaded = loaded["state_dict"]
to_removes = _remove_duplicate_names(loaded, discard_names=discard_names)
metadata = {"format": "pt"}
for kept_name, to_remove_group in to_removes.items():
for to_remove in to_remove_group:
if to_remove not in metadata:
metadata[to_remove] = kept_name
del loaded[to_remove]
# Force tensors to be contiguous
loaded = {k: v.contiguous() for k, v in loaded.items()}
dirname = os.path.dirname(sf_file)
os.makedirs(dirname, exist_ok=True)
save_file(loaded, sf_file, metadata=metadata)
reloaded = load_file(sf_file)
for k in loaded:
pt_tensor = loaded[k]
sf_tensor = reloaded[k]
if not torch.equal(pt_tensor, sf_tensor):
raise RuntimeError(f"The output tensors do not match for key {k}")
def convert_files(pt_files: List[Path], sf_files: List[Path], discard_names: List[str]):
assert len(pt_files) == len(sf_files)
N = len(pt_files)
# We do this instead of using tqdm because we want to parse the logs with the launcher
for i, (pt_file, sf_file) in enumerate(zip(pt_files, sf_files)):
# Skip blacklisted files
if (
"arguments" in pt_file.name
or "args" in pt_file.name
or "training" in pt_file.name
):
continue
start = datetime.datetime.now()
convert_file(pt_file, sf_file, discard_names)
elapsed = datetime.datetime.now() - start
logger.info(f"Convert: [{i + 1}/{N}] -- Took: {elapsed}") | null |
2,191 | import os
import torch
from loguru import logger
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
HAS_FLASH_ATTN = False
HAS_FLASH_ATTN_V2_CUDA = False
HAS_FLASH_ATTN_V2_ROCM = False
try:
try:
import flash_attn_2_cuda
except ImportError:
architecture_suffix = ""
if IS_CUDA_SYSTEM:
architecture_suffix = "-cuda"
elif IS_ROCM_SYSTEM:
architecture_suffix = "-rocm"
raise ImportError(
"Flash Attention V2 is not installed.\n"
"Use the official Docker image (ghcr.io/huggingface/text-generation-inference:latest) "
f"or install flash attention v2 with `cd server && make install install-flash-attention-v2{architecture_suffix}`"
)
if not (is_sm8x or is_sm90):
raise ImportError(
f"GPU with CUDA capability {major} {minor} is not supported for "
"Flash Attention V2"
)
HAS_FLASH_ATTN_V2_CUDA = IS_CUDA_SYSTEM
HAS_FLASH_ATTN_V2_ROCM = IS_ROCM_SYSTEM
except ImportError as e:
try:
import flash_attn_cuda
except ImportError:
raise ImportError(
"Flash Attention is not installed.\n"
"Use the official Docker image (ghcr.io/huggingface/text-generation-inference:latest) "
"or install flash attention with `cd server && make install install-flash-attention`"
) from e
if IS_CUDA_SYSTEM and not (is_sm75 or is_sm8x or is_sm90):
raise ImportError(
f"GPU with CUDA capability {major} {minor} is not supported"
) from e
elif IS_ROCM_SYSTEM:
for idx in range(torch.cuda.device_count()):
if "MI210" not in torch.cuda.get_device_name(
idx
) and "MI250" not in torch.cuda.get_device_name(idx):
raise ImportError(
f"AMD GPU {torch.cuda.get_device_name(idx)} does not support flash-attention"
)
logger.warning(f"Unable to use Flash Attention V2: {e}")
HAS_FLASH_ATTN = True
def attention(
q,
k,
v,
out,
cu_seqlens,
max_s,
softmax_scale,
window_size_left=-1,
):
if window_size_left <= 0 and window_size_left != -1:
raise ValueError("`window_size_left` must be > 0 or -1")
if HAS_FLASH_ATTN_V2_CUDA:
return flash_attn_2_cuda.varlen_fwd(
q,
k,
v,
out,
cu_seqlens,
cu_seqlens,
max_s,
max_s,
0.0,
softmax_scale,
False,
True,
window_size_left,
0,
False,
None,
)
elif HAS_FLASH_ATTN_V2_ROCM:
if window_size_left != -1:
raise ValueError(
f"RoCm version of Flash Attention v2 does not support window attention (window_size_left != -1, got window_size_left={window_size_left})."
)
# RoCm flash API does not take the window_size_left and window_size_right arguments.
return flash_attn_2_cuda.varlen_fwd(
q,
k,
v,
out,
cu_seqlens,
cu_seqlens,
max_s,
max_s,
0.0,
softmax_scale,
False,
True,
False,
None,
)
elif HAS_FLASH_ATTN:
if window_size_left != -1:
raise NotImplementedError(
"window_size_left is only available with flash attn v2"
)
# Flash attention v1 requires q, k and v to have the same number of heads
if k.shape[1] != q.shape[1]:
# MQA expand
if k.shape[1] == 1:
k = k.expand(-1, q.shape[1], -1)
# Grouped attention reshape
else:
original_shape = k.shape
k = (
k.unsqueeze(2)
.expand(-1, -1, q.shape[1] // k.shape[1], -1)
.reshape(original_shape[0], -1, original_shape[2])
)
if v.shape[1] != q.shape[1]:
# MQA expand
if v.shape[1] == 1:
v = v.expand(-1, q.shape[1], -1)
# Grouped attention reshape
else:
original_shape = v.shape
v = (
v.unsqueeze(2)
.expand(-1, -1, q.shape[1] // v.shape[1], -1)
.reshape(original_shape[0], -1, original_shape[2])
)
return flash_attn_cuda.fwd(
q,
k,
v,
out,
cu_seqlens,
cu_seqlens,
max_s,
max_s,
0.0,
softmax_scale,
False,
True,
False,
0,
None,
)
raise NotImplementedError("flash attention is not installed") | null |
2,192 | SPECULATE = None
def get_speculate() -> int:
global SPECULATE
return SPECULATE | null |
2,193 | SPECULATE = None
def set_speculate(speculate: int):
global SPECULATE
SPECULATE = speculate | null |
2,194 | import os
import torch
from datetime import timedelta
from loguru import logger
RANK = int(os.getenv("RANK", "0"))
WORLD_SIZE = int(os.getenv("WORLD_SIZE", "1"))
MEMORY_FRACTION = float(os.getenv("CUDA_MEMORY_FRACTION", "1.0"))
class FakeGroup:
def __init__(self, rank, size):
self._rank = rank
self._size = size
def allreduce(self, *args, **kwargs):
return FakeBarrier()
def allgather(self, inputs, local_tensor, **kwargs):
assert (
len(inputs[0]) == len(local_tensor) == 1
), f"{len(inputs[0])} != {len(local_tensor)} != 1, and the FakeGroup is supposed to join on simple tensors"
for input_ in inputs:
input_[0].data = local_tensor[0].data
return FakeBarrier()
def barrier(self, *args, **kwargs):
return FakeBarrier()
def size(self):
return self._size
def rank(self):
return self._rank
def initialize_torch_distributed():
if torch.cuda.is_available():
from torch.distributed import ProcessGroupNCCL
# Set the device id.
assert WORLD_SIZE <= torch.cuda.device_count(), "Each process is one gpu"
device = RANK % torch.cuda.device_count()
torch.cuda.set_device(device)
torch.cuda.set_per_process_memory_fraction(MEMORY_FRACTION, device)
backend = "nccl"
options = ProcessGroupNCCL.Options()
options.is_high_priority_stream = True
options._timeout = timedelta(seconds=60)
else:
backend = "gloo"
options = None
if WORLD_SIZE == 1:
return FakeGroup(RANK, WORLD_SIZE), RANK, WORLD_SIZE
else:
if os.getenv("DEBUG", None) == "1":
return FakeGroup(RANK, WORLD_SIZE), RANK, WORLD_SIZE
if not torch.distributed.is_initialized():
# Call the init process.
torch.distributed.init_process_group(
backend=backend,
world_size=WORLD_SIZE,
rank=RANK,
timeout=timedelta(seconds=60),
pg_options=options,
)
else:
logger.warning("torch.distributed is already initialized.")
return torch.distributed.group.WORLD, RANK, WORLD_SIZE | null |
2,195 | import torch
from vllm import cache_ops
from vllm import attention_ops
def reshape_and_cache(
key: torch.Tensor,
value: torch.Tensor,
key_cache: torch.Tensor,
value_cache: torch.Tensor,
slots: torch.Tensor,
):
cache_ops.reshape_and_cache(key, value, key_cache, value_cache, slots) | null |
2,196 | import torch
from vllm import cache_ops
from vllm import attention_ops
_PARTITION_SIZE = 512
def attention(
out: torch.Tensor,
query: torch.Tensor,
key_cache: torch.Tensor,
value_cache: torch.Tensor,
kv_head_mapping: torch.Tensor,
softmax_scale: float,
block_tables: torch.Tensor,
input_lengths: torch.Tensor,
max_s: int,
):
# Adapted from: https://github.com/vllm-project/vllm/blob/f8a1e39fae05ca610be8d5a78be9d40f5274e5fc/vllm/model_executor/layers/attention.py
# Copyright 2023 The vLLM team. All rights
# reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# value_cache => [num_blocks, num_heads, head_size, block_size]
block_size = value_cache.shape[3]
num_seqs, num_heads, head_size = query.shape
max_num_partitions = (max_s + _PARTITION_SIZE - 1) // _PARTITION_SIZE
# NOTE(woosuk): We use a simple heuristic to decide whether to use
# PagedAttention V1 or V2. If the number of partitions is 1, we use
# V1 to avoid the overhead of reduction. Also, if the number of
# sequences or heads is large, we use V1 since there is enough work
# to parallelize.
use_v1 = max_num_partitions == 1 or num_seqs * num_heads > 512
if use_v1:
attention_ops.paged_attention_v1(
out,
query,
key_cache,
value_cache,
kv_head_mapping,
softmax_scale,
block_tables,
input_lengths,
block_size,
max_s,
None,
)
else:
# Run PagedAttention V2.
assert _PARTITION_SIZE % block_size == 0
tmp_output = torch.empty(
size=(num_seqs, num_heads, max_num_partitions, head_size),
dtype=out.dtype,
device=out.device,
)
exp_sums = torch.empty(
size=(num_seqs, num_heads, max_num_partitions),
dtype=torch.float32,
device=out.device,
)
max_logits = torch.empty_like(exp_sums)
attention_ops.paged_attention_v2(
out,
exp_sums,
max_logits,
tmp_output,
query,
key_cache,
value_cache,
kv_head_mapping,
softmax_scale,
block_tables,
input_lengths,
block_size,
max_s,
None,
) | null |
2,197 | import re
from typing import List, Optional, Tuple
import math
import torch
from text_generation_server.pb import generate_pb2
from text_generation_server.pb.generate_pb2 import FinishReason, GrammarType
from text_generation_server.utils.logits_process import (
FrequencyPenaltyLogitsProcessor,
GrammarLogitProcessor,
HeterogeneousProcessorWrapper,
HeterogeneousRepetitionPenaltyLogitsProcessor,
HeterogeneousFrequencyPenaltyLogitsProcessor,
HeterogeneousTemperatureLogitsWarper,
HeterogeneousTopKLogitsWarper,
HeterogeneousTopPLogitsWarper,
HeterogeneousTypicalLogitsWarper,
HeterogeneousGrammarLogitProcessor,
static_warper,
)
from text_generation_server.utils.watermark import WatermarkLogitsProcessor
from transformers import PreTrainedTokenizerBase, RepetitionPenaltyLogitsProcessor
def create_n_gram_speculation(
input_ids: torch.Tensor,
next_ids: torch.Tensor,
accepted_ids: torch.Tensor,
speculate: int,
verbose: bool,
):
# Very trivial approach, find first match in the string.
# This is much less refined than actual n-gram but seems to work
# relatively OK in grounded mode and is by far much faster with
# much less worst case complexity as everything happens on device.
B = accepted_ids.shape[0]
device = input_ids.device
seeds = next_ids[accepted_ids.cumsum(dim=-1) - 1]
indices = (input_ids == seeds.unsqueeze(-1)).max(dim=1).indices + 1
all_indices = indices.unsqueeze(-1).expand(B, speculate) + torch.arange(
speculate, device=device
)
all_indices = torch.clamp(all_indices, max=input_ids.shape[1] - 1)
speculative_ids = input_ids.gather(dim=-1, index=all_indices)
return speculative_ids | null |
2,198 | import re
from typing import List, Optional, Tuple
import math
import torch
from text_generation_server.pb import generate_pb2
from text_generation_server.pb.generate_pb2 import FinishReason, GrammarType
from text_generation_server.utils.logits_process import (
FrequencyPenaltyLogitsProcessor,
GrammarLogitProcessor,
HeterogeneousProcessorWrapper,
HeterogeneousRepetitionPenaltyLogitsProcessor,
HeterogeneousFrequencyPenaltyLogitsProcessor,
HeterogeneousTemperatureLogitsWarper,
HeterogeneousTopKLogitsWarper,
HeterogeneousTopPLogitsWarper,
HeterogeneousTypicalLogitsWarper,
HeterogeneousGrammarLogitProcessor,
static_warper,
)
from text_generation_server.utils.watermark import WatermarkLogitsProcessor
from transformers import PreTrainedTokenizerBase, RepetitionPenaltyLogitsProcessor
The provided code snippet includes necessary dependencies for implementing the `batch_top_tokens` function. Write a Python function `def batch_top_tokens( top_n_tokens: List[int], top_n_tokens_tensor: torch.Tensor, logprobs: torch.Tensor, accepted_ids: torch.Tensor, ) -> Tuple[List[List[List[int]]], List[List[List[float]]]]` to solve the following problem:
Find the top n most likely tokens for a batch of generations. When multiple tokens have equal probabilities and they don't all fit, the remaining tokens are also returned.
Here is the function:
def batch_top_tokens(
top_n_tokens: List[int],
top_n_tokens_tensor: torch.Tensor,
logprobs: torch.Tensor,
accepted_ids: torch.Tensor,
) -> Tuple[List[List[List[int]]], List[List[List[float]]]]:
"""Find the top n most likely tokens for a batch of generations.
When multiple tokens have equal probabilities and they don't all fit, the
remaining tokens are also returned.
"""
max_top_n = max(top_n_tokens)
# Early exit when top_n_tokens is not used
if max_top_n == 0:
return [[[]]] * len(top_n_tokens), [[[]]] * len(top_n_tokens)
batch_size = accepted_ids.shape[0]
speculate_size = logprobs.shape[0] // batch_size
top_n_tokens_tensor = top_n_tokens_tensor.repeat_interleave(speculate_size)
# Ensure top_n doesn't exceed vocab size
top_n_tokens = [
min(tok, logprobs.size(-1))
for tok in top_n_tokens
for _ in range(speculate_size)
]
# Parallel kthvalue adapted from https://discuss.pytorch.org/t/how-to-efficiently-get-the-k-th-largest-values-in-parallel/160529/2
# Sorted topk is faster than torch.sort() since we only need a small subset
sorted_top_k = torch.topk(logprobs, k=max_top_n, dim=-1, sorted=True).values
nth_highest = torch.gather(
sorted_top_k, 1, (top_n_tokens_tensor - 1).clip(min=0).unsqueeze(1)
)
nth_highest[nth_highest == -float("inf")] = torch.finfo(logprobs.dtype).min
# Find the new "fuzzy" top n values
top_n_indices = (logprobs >= nth_highest).nonzero()
_, top_n_ishes = torch.unique_consecutive(top_n_indices[:, 0], return_counts=True)
k = 1 if top_n_ishes.numel() == 0 else top_n_ishes.max()
# Take a new topk for these new max n values
top_k = torch.topk(logprobs, k=k, dim=1, sorted=True)
top_n_ishes = top_n_ishes.tolist()
top_indices = top_k.indices.tolist()
top_values = top_k.values.tolist()
batch_top_token_ids = []
batch_top_token_logprobs = []
accepted_ids_list = accepted_ids.tolist()
for i, n_accepted_ids in enumerate(accepted_ids_list):
start = speculate_size * i
stop = speculate_size * (i + 1)
_top_indices = top_indices[start:stop]
_top_values = top_values[start:stop]
_top_n_ishes = top_n_ishes[start:stop]
_top_n_tokens = top_n_tokens[start:stop]
_top_indices = _top_indices[:n_accepted_ids]
_top_values = _top_values[:n_accepted_ids]
_top_n_ishes = _top_n_ishes[:n_accepted_ids]
_top_n_tokens = _top_n_tokens[:n_accepted_ids]
row_top_token_ids = []
row_top_token_logprobs = []
for idxs, vals, n, req_n in zip(
_top_indices, _top_values, _top_n_ishes, _top_n_tokens
):
indices = idxs[:n] if req_n > 0 else []
values = vals[:n] if req_n > 0 else []
row_top_token_ids.append(indices)
row_top_token_logprobs.append(values)
batch_top_token_ids.append(row_top_token_ids)
batch_top_token_logprobs.append(row_top_token_logprobs)
return batch_top_token_ids, batch_top_token_logprobs | Find the top n most likely tokens for a batch of generations. When multiple tokens have equal probabilities and they don't all fit, the remaining tokens are also returned. |
2,199 | import os
import torch
import torch.distributed
from torch import nn
from torch.nn import functional as F
from typing import List, Tuple, Optional
from loguru import logger
from functools import lru_cache
from accelerate import init_empty_weights
from text_generation_server.utils.gptq.quant_linear import QuantLinear
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
from text_generation_server.utils.log import log_once
def load_layer_norm(cls, prefix, weights, eps):
weight = weights.get_tensor(f"{prefix}.weight")
bias = weights.get_tensor(f"{prefix}.bias")
with init_empty_weights():
ln = cls(weight.shape, eps=eps)
ln.weight = nn.Parameter(weight)
ln.bias = nn.Parameter(bias)
return ln | null |
2,200 | import os
import torch
import torch.distributed
from torch import nn
from torch.nn import functional as F
from typing import List, Tuple, Optional
from loguru import logger
from functools import lru_cache
from accelerate import init_empty_weights
from text_generation_server.utils.gptq.quant_linear import QuantLinear
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
from text_generation_server.utils.log import log_once
def load_layer_norm_no_bias(cls, prefix, weights, eps):
weight = weights.get_tensor(f"{prefix}.weight")
with init_empty_weights():
ln = cls(weight.shape, eps=eps)
ln.weight = nn.Parameter(weight)
ln.bias = None
return ln | null |
2,201 | import os
import torch
import torch.distributed
from torch import nn
from torch.nn import functional as F
from typing import List, Tuple, Optional
from loguru import logger
from functools import lru_cache
from accelerate import init_empty_weights
from text_generation_server.utils.gptq.quant_linear import QuantLinear
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
from text_generation_server.utils.log import log_once
def load_conv2d(cls, prefix, weights, in_channels, out_channels, kernel_size, stride):
weight = weights.get_tensor(f"{prefix}.weight")
bias = weights.get_tensor(f"{prefix}.bias")
with init_empty_weights():
conv2d = cls(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
)
conv2d.weight = nn.Parameter(weight)
conv2d.bias = nn.Parameter(bias)
return conv2d | null |
2,202 | import os
import torch
import torch.distributed
from torch import nn
from torch.nn import functional as F
from typing import List, Tuple, Optional
from loguru import logger
from functools import lru_cache
from accelerate import init_empty_weights
from text_generation_server.utils.gptq.quant_linear import QuantLinear
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
from text_generation_server.utils.log import log_once
def load_conv2d_no_bias(
cls, prefix, weights, in_channels, out_channels, kernel_size, stride
):
weight = weights.get_tensor(f"{prefix}.weight")
with init_empty_weights():
conv2d = cls(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
)
conv2d.weight = nn.Parameter(weight)
conv2d.bias = None
return conv2d | null |
2,203 | import os
import torch
import torch.distributed
from torch import nn
from torch.nn import functional as F
from typing import List, Tuple, Optional
from loguru import logger
from functools import lru_cache
from accelerate import init_empty_weights
from text_generation_server.utils.gptq.quant_linear import QuantLinear
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
from text_generation_server.utils.log import log_once
torch.nn.Conv2d.load = load_conv2d
torch.nn.Conv2d.load_no_bias = load_conv2d_no_bias
torch.nn.LayerNorm.load = load_layer_norm
torch.nn.LayerNorm.load_no_bias = load_layer_norm_no_bias
def _create_inv_freq(dim, base, device):
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, device=device, dtype=torch.float32) / dim)
)
return inv_freq | null |
2,204 | import os
import torch
import torch.distributed
from torch import nn
from torch.nn import functional as F
from typing import List, Tuple, Optional
from loguru import logger
from functools import lru_cache
from accelerate import init_empty_weights
from text_generation_server.utils.gptq.quant_linear import QuantLinear
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
from text_generation_server.utils.log import log_once
if os.getenv("DISABLE_EXLLAMA") == "True":
HAS_EXLLAMA = False
elif CAN_EXLLAMA:
try:
if V2:
from text_generation_server.utils.gptq.exllamav2 import (
QuantLinear as ExllamaQuantLinear,
create_exllama_buffers,
set_device,
)
HAS_EXLLAMA = "2"
else:
from text_generation_server.utils.gptq.exllama import (
Ex4bitLinear as ExllamaQuantLinear,
create_exllama_buffers,
set_device,
)
HAS_EXLLAMA = "1"
except ImportError:
pass
def _get_rope_config(config):
if os.getenv("ROPE_SCALING", None) is not None:
rope_scaling = {
"type": os.environ["ROPE_SCALING"],
"factor": float(os.environ["ROPE_FACTOR"]),
}
return rope_scaling
return getattr(config, "rope_scaling", None) | null |
2,205 | import os
import torch
import torch.distributed
from torch import nn
from torch.nn import functional as F
from typing import List, Tuple, Optional
from loguru import logger
from functools import lru_cache
from accelerate import init_empty_weights
from text_generation_server.utils.gptq.quant_linear import QuantLinear
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
from text_generation_server.utils.log import log_once
try:
if IS_CUDA_SYSTEM:
from flash_attn.layers.rotary import RotaryEmbedding
import rotary_emb
elif IS_ROCM_SYSTEM:
from vllm import pos_encoding_ops
# Inverse dim formula to find dim based on number of rotations
import math
def find_correction_dim(
num_rotations, dim, base=10000, max_position_embeddings=2048
):
return (
dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))
) / (2 * math.log(base))
# Find dim range bounds based on rotations
except ImportError:
pass
def find_correction_range(
low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
):
low = math.floor(
find_correction_dim(low_rot, dim, base, max_position_embeddings)
)
high = math.ceil(
find_correction_dim(high_rot, dim, base, max_position_embeddings)
)
return max(low, 0), min(high, dim - 1) # Clamp values just in case | null |
2,206 | import os
import torch
import torch.distributed
from torch import nn
from torch.nn import functional as F
from typing import List, Tuple, Optional
from loguru import logger
from functools import lru_cache
from accelerate import init_empty_weights
from text_generation_server.utils.gptq.quant_linear import QuantLinear
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
from text_generation_server.utils.log import log_once
torch.nn.Conv2d.load = load_conv2d
torch.nn.Conv2d.load_no_bias = load_conv2d_no_bias
torch.nn.LayerNorm.load = load_layer_norm
torch.nn.LayerNorm.load_no_bias = load_layer_norm_no_bias
def linear_ramp_mask(min, max, dim):
if min == max:
max += 0.001 # Prevent singularity
linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
ramp_func = torch.clamp(linear_func, 0, 1)
return ramp_func | null |
2,207 | import os
import torch
import torch.distributed
from torch import nn
from torch.nn import functional as F
from typing import List, Tuple, Optional
from loguru import logger
from functools import lru_cache
from accelerate import init_empty_weights
from text_generation_server.utils.gptq.quant_linear import QuantLinear
from text_generation_server.utils.import_utils import IS_CUDA_SYSTEM, IS_ROCM_SYSTEM
from text_generation_server.utils.log import log_once
def get_mscale(scale=1):
if scale <= 1:
return 1.0
return 0.1 * math.log(scale) + 1.0 | null |
2,208 | import os
import json
from loguru import logger
import torch
from transformers import AutoTokenizer
from peft import AutoPeftModelForCausalLM, AutoPeftModelForSeq2SeqLM
def download_and_unload_peft(model_id, revision, trust_remote_code):
torch_dtype = torch.float16
logger.info("Trying to load a Peft model. It might take a while without feedback")
try:
model = AutoPeftModelForCausalLM.from_pretrained(
model_id,
revision=revision,
torch_dtype=torch_dtype,
trust_remote_code=trust_remote_code,
low_cpu_mem_usage=True,
)
except Exception:
model = AutoPeftModelForSeq2SeqLM.from_pretrained(
model_id,
revision=revision,
torch_dtype=torch_dtype,
trust_remote_code=trust_remote_code,
low_cpu_mem_usage=True,
)
logger.info("Peft model detected.")
logger.info(f"Merging the lora weights.")
base_model_id = model.peft_config["default"].base_model_name_or_path
model = model.merge_and_unload()
os.makedirs(model_id, exist_ok=True)
cache_dir = model_id
logger.info(f"Saving the newly created merged model to {cache_dir}")
tokenizer = AutoTokenizer.from_pretrained(
base_model_id, trust_remote_code=trust_remote_code
)
model.save_pretrained(cache_dir, safe_serialization=True)
model.config.save_pretrained(cache_dir)
tokenizer.save_pretrained(cache_dir) | null |
2,209 | import builtins
import math
import time
from typing import Dict
import triton
class Autotuner(triton.KernelInterface):
def __init__(
self,
fn,
arg_names,
configs,
key,
reset_to_zero,
prune_configs_by: Dict = None,
nearest_power_of_two: bool = False,
):
"""
:param prune_configs_by: a dict of functions that are used to prune configs, fields:
'perf_model': performance model used to predicate running time with different configs, returns running time
'top_k': number of configs to bench
'prune_num_stages_by'(optional): a function used to prune num_stages. It take configs:List[Config] as its input, and returns pruned configs.
'nearest_power_of_two'(optional): whether to round key arguments to the nearest power of two when caching tuning results
"""
if not configs:
self.configs = [triton.Config({}, num_warps=4, num_stages=2)]
else:
self.configs = configs
self.key_idx = [arg_names.index(k) for k in key]
self.nearest_power_of_two = nearest_power_of_two
self.cache = {}
# hook to reset all required tensor to zeros before relaunching a kernel
self.hook = lambda args: 0
if reset_to_zero is not None:
self.reset_idx = [arg_names.index(k) for k in reset_to_zero]
def _hook(args):
for i in self.reset_idx:
args[i].zero_()
self.hook = _hook
self.arg_names = arg_names
# prune configs
if prune_configs_by:
perf_model, top_k = (
prune_configs_by["perf_model"],
prune_configs_by["top_k"],
)
if "early_config_prune" in prune_configs_by:
early_config_prune = prune_configs_by["early_config_prune"]
else:
perf_model, top_k, early_config_prune = None, None, None
self.perf_model, self.configs_top_k = perf_model, top_k
self.early_config_prune = early_config_prune
self.fn = fn
def _bench(self, *args, config, **meta):
# check for conflicts, i.e. meta-parameters both provided
# as kwargs and by the autotuner
conflicts = meta.keys() & config.kwargs.keys()
if conflicts:
raise ValueError(
f"Conflicting meta-parameters: {', '.join(conflicts)}."
" Make sure that you don't re-define auto-tuned symbols."
)
# augment meta-parameters with tunable ones
current = dict(meta, **config.kwargs)
def kernel_call():
if config.pre_hook:
config.pre_hook(self.nargs)
self.hook(args)
self.fn.run(
*args,
num_warps=config.num_warps,
num_stages=config.num_stages,
**current,
)
try:
# In testings using only 40 reps seems to be close enough and it appears to be what PyTorch uses
# PyTorch also sets fast_flush to True, but I didn't see any speedup so I'll leave the default
return triton.testing.do_bench(
kernel_call, quantiles=(0.5, 0.2, 0.8), rep=40
)
except triton.OutOfResources:
return (float("inf"), float("inf"), float("inf"))
def run(self, *args, **kwargs):
self.nargs = dict(zip(self.arg_names, args))
if len(self.configs) > 1:
key = tuple(args[i] for i in self.key_idx)
# This reduces the amount of autotuning by rounding the keys to the nearest power of two
# In my testing this gives decent results, and greatly reduces the amount of tuning required
if self.nearest_power_of_two:
key = tuple([2 ** int(math.log2(x) + 0.5) for x in key])
if key not in self.cache:
# prune configs
pruned_configs = self.prune_configs(kwargs)
bench_start = time.time()
timings = {
config: self._bench(*args, config=config, **kwargs)
for config in pruned_configs
}
bench_end = time.time()
self.bench_time = bench_end - bench_start
self.cache[key] = builtins.min(timings, key=timings.get)
self.hook(args)
self.configs_timings = timings
config = self.cache[key]
else:
config = self.configs[0]
self.best_config = config
if config.pre_hook is not None:
config.pre_hook(self.nargs)
return self.fn.run(
*args,
num_warps=config.num_warps,
num_stages=config.num_stages,
**kwargs,
**config.kwargs,
)
def prune_configs(self, kwargs):
pruned_configs = self.configs
if self.early_config_prune:
pruned_configs = self.early_config_prune(self.configs, self.nargs)
if self.perf_model:
top_k = self.configs_top_k
if isinstance(top_k, float) and top_k <= 1.0:
top_k = int(len(self.configs) * top_k)
if len(pruned_configs) > top_k:
est_timing = {
config: self.perf_model(
**self.nargs,
**kwargs,
**config.kwargs,
num_stages=config.num_stages,
num_warps=config.num_warps,
)
for config in pruned_configs
}
pruned_configs = sorted(est_timing.keys(), key=lambda x: est_timing[x])[
:top_k
]
return pruned_configs
def warmup(self, *args, **kwargs):
self.nargs = dict(zip(self.arg_names, args))
for config in self.prune_configs(kwargs):
self.fn.warmup(
*args,
num_warps=config.num_warps,
num_stages=config.num_stages,
**kwargs,
**config.kwargs,
)
self.nargs = None
The provided code snippet includes necessary dependencies for implementing the `autotune` function. Write a Python function `def autotune( configs, key, prune_configs_by=None, reset_to_zero=None, nearest_power_of_two=False )` to solve the following problem:
Decorator for auto-tuning a :code:`triton.jit`'d function. .. highlight:: python .. code-block:: python @triton.autotune(configs=[ triton.Config(meta={'BLOCK_SIZE': 128}, num_warps=4), triton.Config(meta={'BLOCK_SIZE': 1024}, num_warps=8), ], key=['x_size'] # the two above configs will be evaluated anytime # the value of x_size changes ) @triton.jit def kernel(x_ptr, x_size, **META): BLOCK_SIZE = META['BLOCK_SIZE'] :note: When all the configurations are evaluated, the kernel will run multiple time. This means that whatever value the kernel updates will be updated multiple times. To avoid this undesired behavior, you can use the `reset_to_zero` argument, which reset the value of the provided tensor to `zero` before running any configuration. :param configs: a list of :code:`triton.Config` objects :type configs: list[triton.Config] :param key: a list of argument names whose change in value will trigger the evaluation of all provided configs. :type key: list[str] :param prune_configs_by: a dict of functions that are used to prune configs, fields: 'perf_model': performance model used to predicate running time with different configs, returns running time 'top_k': number of configs to bench 'early_config_prune'(optional): a function used to do early prune (eg, num_stages). It take configs:List[Config] as its input, and returns pruned configs. :param reset_to_zero: a list of argument names whose value will be reset to zero before evaluating any configs. :type reset_to_zero: list[str]
Here is the function:
def autotune(
configs, key, prune_configs_by=None, reset_to_zero=None, nearest_power_of_two=False
):
"""
Decorator for auto-tuning a :code:`triton.jit`'d function.
.. highlight:: python
.. code-block:: python
@triton.autotune(configs=[
triton.Config(meta={'BLOCK_SIZE': 128}, num_warps=4),
triton.Config(meta={'BLOCK_SIZE': 1024}, num_warps=8),
],
key=['x_size'] # the two above configs will be evaluated anytime
# the value of x_size changes
)
@triton.jit
def kernel(x_ptr, x_size, **META):
BLOCK_SIZE = META['BLOCK_SIZE']
:note: When all the configurations are evaluated, the kernel will run multiple time.
This means that whatever value the kernel updates will be updated multiple times.
To avoid this undesired behavior, you can use the `reset_to_zero` argument, which
reset the value of the provided tensor to `zero` before running any configuration.
:param configs: a list of :code:`triton.Config` objects
:type configs: list[triton.Config]
:param key: a list of argument names whose change in value will trigger the evaluation of all provided configs.
:type key: list[str]
:param prune_configs_by: a dict of functions that are used to prune configs, fields:
'perf_model': performance model used to predicate running time with different configs, returns running time
'top_k': number of configs to bench
'early_config_prune'(optional): a function used to do early prune (eg, num_stages). It take configs:List[Config] as its input, and returns pruned configs.
:param reset_to_zero: a list of argument names whose value will be reset to zero before evaluating any configs.
:type reset_to_zero: list[str]
"""
def decorator(fn):
return Autotuner(
fn,
fn.arg_names,
configs,
key,
reset_to_zero,
prune_configs_by,
nearest_power_of_two,
)
return decorator | Decorator for auto-tuning a :code:`triton.jit`'d function. .. highlight:: python .. code-block:: python @triton.autotune(configs=[ triton.Config(meta={'BLOCK_SIZE': 128}, num_warps=4), triton.Config(meta={'BLOCK_SIZE': 1024}, num_warps=8), ], key=['x_size'] # the two above configs will be evaluated anytime # the value of x_size changes ) @triton.jit def kernel(x_ptr, x_size, **META): BLOCK_SIZE = META['BLOCK_SIZE'] :note: When all the configurations are evaluated, the kernel will run multiple time. This means that whatever value the kernel updates will be updated multiple times. To avoid this undesired behavior, you can use the `reset_to_zero` argument, which reset the value of the provided tensor to `zero` before running any configuration. :param configs: a list of :code:`triton.Config` objects :type configs: list[triton.Config] :param key: a list of argument names whose change in value will trigger the evaluation of all provided configs. :type key: list[str] :param prune_configs_by: a dict of functions that are used to prune configs, fields: 'perf_model': performance model used to predicate running time with different configs, returns running time 'top_k': number of configs to bench 'early_config_prune'(optional): a function used to do early prune (eg, num_stages). It take configs:List[Config] as its input, and returns pruned configs. :param reset_to_zero: a list of argument names whose value will be reset to zero before evaluating any configs. :type reset_to_zero: list[str] |
2,210 | import builtins
import math
import time
from typing import Dict
import triton
The provided code snippet includes necessary dependencies for implementing the `matmul248_kernel_config_pruner` function. Write a Python function `def matmul248_kernel_config_pruner(configs, nargs)` to solve the following problem:
The main purpose of this function is to shrink BLOCK_SIZE_* when the corresponding dimension is smaller.
Here is the function:
def matmul248_kernel_config_pruner(configs, nargs):
"""
The main purpose of this function is to shrink BLOCK_SIZE_* when the corresponding dimension is smaller.
"""
m = max(2 ** int(math.ceil(math.log2(nargs["M"]))), 16)
n = max(2 ** int(math.ceil(math.log2(nargs["N"]))), 16)
k = max(2 ** int(math.ceil(math.log2(nargs["K"]))), 16)
used = set()
for config in configs:
block_size_m = min(m, config.kwargs["BLOCK_SIZE_M"])
block_size_n = min(n, config.kwargs["BLOCK_SIZE_N"])
block_size_k = min(k, config.kwargs["BLOCK_SIZE_K"])
group_size_m = config.kwargs["GROUP_SIZE_M"]
if (
block_size_m,
block_size_n,
block_size_k,
group_size_m,
config.num_stages,
config.num_warps,
) in used:
continue
used.add(
(
block_size_m,
block_size_n,
block_size_k,
group_size_m,
config.num_stages,
config.num_warps,
)
)
yield triton.Config(
{
"BLOCK_SIZE_M": block_size_m,
"BLOCK_SIZE_N": block_size_n,
"BLOCK_SIZE_K": block_size_k,
"GROUP_SIZE_M": group_size_m,
},
num_stages=config.num_stages,
num_warps=config.num_warps,
) | The main purpose of this function is to shrink BLOCK_SIZE_* when the corresponding dimension is smaller. |
2,211 | import torch
from exllama_kernels import make_q4, q4_matmul, prepare_buffers, set_tuning_params
none_tensor = torch.empty((1, 1), device="meta")
The provided code snippet includes necessary dependencies for implementing the `ext_make_q4` function. Write a Python function `def ext_make_q4(qweight, qzeros, scales, g_idx, device)` to solve the following problem:
Construct Q4Matrix, return handle
Here is the function:
def ext_make_q4(qweight, qzeros, scales, g_idx, device):
"""Construct Q4Matrix, return handle"""
return make_q4(
qweight, qzeros, scales, g_idx if g_idx is not None else none_tensor, device
) | Construct Q4Matrix, return handle |
2,212 | import torch
from exllama_kernels import make_q4, q4_matmul, prepare_buffers, set_tuning_params
The provided code snippet includes necessary dependencies for implementing the `ext_q4_matmul` function. Write a Python function `def ext_q4_matmul(x, q4, q4_width)` to solve the following problem:
Matrix multiplication, returns x @ q4
Here is the function:
def ext_q4_matmul(x, q4, q4_width):
"""Matrix multiplication, returns x @ q4"""
outshape = x.shape[:-1] + (q4_width,)
x = x.view(-1, x.shape[-1])
output = torch.empty((x.shape[0], q4_width), dtype=torch.float16, device=x.device)
q4_matmul(x, q4, output)
return output.view(outshape) | Matrix multiplication, returns x @ q4 |
2,213 | import torch
from exllama_kernels import make_q4, q4_matmul, prepare_buffers, set_tuning_params
DEVICE = None
def set_device(device):
global DEVICE
DEVICE = device | null |
2,214 | import torch
from exllama_kernels import make_q4, q4_matmul, prepare_buffers, set_tuning_params
MAX_DQ = 1
MAX_INNER = 1
ACT_ORDER = False
DEVICE = None
TEMP_STATE = None
TEMP_DQ = None
def create_exllama_buffers(max_total_tokens: int):
global MAX_DQ, MAX_INNER, ACT_ORDER, DEVICE, TEMP_STATE, TEMP_DQ
assert DEVICE is not None, "call set_device first"
if not ACT_ORDER:
max_total_tokens = 1
# This temp_state buffer is required to reorder X in the act-order case.
temp_state = torch.zeros(
(max_total_tokens, MAX_INNER), dtype=torch.float16, device=DEVICE
)
temp_dq = torch.zeros((1, MAX_DQ), dtype=torch.float16, device=DEVICE)
# This temp_dq buffer is required to dequantize weights when using cuBLAS, typically for the prefill.
prepare_buffers(DEVICE, temp_state, temp_dq)
matmul_recons_thd = 8
matmul_fused_remap = False
matmul_no_half2 = False
set_tuning_params(matmul_recons_thd, matmul_fused_remap, matmul_no_half2)
TEMP_STATE, TEMP_DQ = temp_state, temp_dq | null |
2,215 | import torch
import torch.nn as nn
from loguru import logger
The provided code snippet includes necessary dependencies for implementing the `ext_gemm_half_q_half` function. Write a Python function `def ext_gemm_half_q_half(x, q_handle, q4_width, force_cuda)` to solve the following problem:
Matrix multiplication, returns x @ q4
Here is the function:
def ext_gemm_half_q_half(x, q_handle, q4_width, force_cuda):
"""Matrix multiplication, returns x @ q4"""
output_shape = x.shape[:-1] + (q4_width,)
x = x.view(-1, x.shape[-1])
output = torch.empty((x.shape[0], q4_width), dtype=torch.half, device=x.device)
gemm_half_q_half(x, q_handle, output, force_cuda)
return output.view(output_shape) | Matrix multiplication, returns x @ q4 |
2,216 | import torch
import torch.nn as nn
from loguru import logger
none_tensor = torch.empty((1, 1), device="meta")
def make_group_map(q_groups, num_qrows):
gr = q_groups.tolist()
group_map = []
num_groups = len(gr) // 2
for i in range(num_groups):
bits = gr[i * 2]
if i < num_groups - 1:
qrows = gr[i * 2 + 3] - gr[i * 2 + 1]
else:
qrows = num_qrows - gr[i * 2 + 1]
rows = qrows * 32 // bits
for j in range(rows):
group_map += [i]
group_map += [rows - j]
return torch.tensor(group_map, dtype=torch.short, device=q_groups.device)
The provided code snippet includes necessary dependencies for implementing the `ext_make_q_matrix` function. Write a Python function `def ext_make_q_matrix(w: dict, temp_dq, key: str = None)` to solve the following problem:
Create Q matrix
Here is the function:
def ext_make_q_matrix(w: dict, temp_dq, key: str = None):
"""
Create Q matrix
"""
# EXL2
# won't work as the moment because the tensors are not the same.
if "q_weight" in w:
w["q_scale_max"] /= 256
w["q_perm"] = w["q_perm"].short()
w["q_invperm"] = w["q_invperm"].short()
if "q_group_map" not in w:
w["q_group_map"] = make_group_map(w["q_groups"], w["q_weight"].shape[0])
return make_q_matrix(
w["q_weight"],
w["q_perm"],
w["q_invperm"],
w["q_scale"],
w["q_scale_max"],
w["q_groups"],
w["q_group_map"],
none_tensor,
none_tensor,
none_tensor,
temp_dq,
)
# GPTQ
elif "qweight" in w:
if w["scales"].dtype == torch.float:
w["scales"] = w["scales"].half()
# GPTQ with g_idx (act_order)
if w.get("g_idx", None) is not None and not (w["g_idx"] == 0).all().item():
w["q_perm"] = torch.empty(
(w["qweight"].shape[0] * 8,),
dtype=torch.short,
device=w["qweight"].device,
)
w["q_invperm"] = torch.empty_like(w["q_perm"])
# make_q4 segfaults if g_idx is not on cpu in the act-order case. In the non act-order case, None needs to be passed for g_idx.
return make_q_matrix(
w["qweight"],
w["q_perm"],
w["q_invperm"],
none_tensor,
none_tensor,
none_tensor,
none_tensor,
w["qzeros"],
w["scales"],
w["g_idx"].cpu(),
temp_dq,
)
# GPTQ without g_idx
else:
return make_q_matrix(
w["qweight"],
none_tensor,
none_tensor,
none_tensor,
none_tensor,
none_tensor,
none_tensor,
w["qzeros"],
w["scales"],
none_tensor,
temp_dq,
) | Create Q matrix |
2,217 | import torch
import torch.nn as nn
from loguru import logger
DEVICE = None
def set_device(device):
global DEVICE
DEVICE = device | null |
2,218 | import torch
import torch.nn as nn
from loguru import logger
DEVICE = None
FIXED_BYTES = 0
LAYERS = []
class ExLlamaV2DeviceTensors:
device_idx: int
scratch_bytes: int
scratch_idx: int
scratch: torch.tensor = None
def __init__(self, device, scratch_bytes):
self.device = device
self.scratch_bytes = scratch_bytes
def prepare(self):
self.scratch = torch.empty(
(self.scratch_bytes // 2,), dtype=torch.half, device=self.device
)
def get_scratch_slice(self, size_bytes):
if self.scratch is None:
self.prepare()
size_bytes = ((size_bytes + 127) // 128) * 128
size_half = size_bytes // 2
scratch_slice = self.scratch.narrow(0, 0, size_half)
return scratch_slice
def create_exllama_buffers(max_total_tokens: int):
global FIXED_BYTES, LAYERS, DEVICE
temp_dq = ExLlamaV2DeviceTensors(DEVICE, FIXED_BYTES)
for layer in LAYERS:
layer.post_init(temp_dq) | null |
2,219 | import time
import torch.nn as nn
import math
import json
import os
import torch
import transformers
from texttable import Texttable
from transformers import AutoModelForCausalLM, AutoConfig, AutoTokenizer
from huggingface_hub import HfApi
from accelerate import init_empty_weights
from text_generation_server.utils import initialize_torch_distributed, Weights
from text_generation_server.utils.hub import weight_files
from text_generation_server.utils.gptq.quant_linear import QuantLinear
from loguru import logger
from typing import Optional
DEV = torch.device("cuda:0")
def get_loaders(
name, nsamples=128, seed=0, seqlen=2048, model_id="", trust_remote_code=False
):
if "wikitext2" in name:
return get_wikitext2(nsamples, seed, seqlen, model_id, trust_remote_code)
if "ptb" in name:
if "new" in name:
return get_ptb_new(nsamples, seed, seqlen, model_id, trust_remote_code)
return get_ptb(nsamples, seed, seqlen, model_id, trust_remote_code)
if "c4" in name:
if "new" in name:
return get_c4_new(nsamples, seed, seqlen, model_id, trust_remote_code)
return get_c4(nsamples, seed, seqlen, model_id, trust_remote_code)
def sequential(
model,
dataloader,
dev,
nsamples,
bits,
groupsize,
*,
hooks,
percdamp=0.01,
sym: bool = False,
act_order: bool = False,
):
print("Starting ...")
use_cache = model.config.use_cache
model.config.use_cache = False
try:
layers = model.model.layers
prefix = "model.layers"
except Exception:
layers = model.transformer.h
prefix = "transformer.h"
dtype = next(iter(model.parameters())).dtype
inps = torch.zeros(
(nsamples, model.seqlen, model.config.hidden_size), dtype=dtype, device=dev
)
cache = {"i": 0}
extra = {}
class Catcher(nn.Module):
def __init__(self, module):
super().__init__()
self.module = module
def forward(self, inp, **kwargs):
inps[cache["i"]] = inp
cache["i"] += 1
extra.update(kwargs.copy())
raise ValueError
layers[0] = Catcher(layers[0])
for batch in dataloader:
try:
model(batch[0].cuda())
except ValueError:
pass
layers[0] = layers[0].module
# layers[0] = layers[0].cpu()
# model.model.embed_tokens = model.model.embed_tokens.cpu()
# model.model.norm = model.model.norm.cpu()
torch.cuda.empty_cache()
for hook in hooks:
hook.remove()
outs = torch.zeros_like(inps)
extra = {
k: v.to(dev) if isinstance(v, torch.Tensor) else v for k, v in extra.items()
}
print("Ready.")
quantizers = {}
for i in range(len(layers)):
print(f"Quantizing layer {i+1}/{len(layers)}..")
print("+------------------+--------------+------------+-----------+-------+")
print("| name | weight_error | fp_inp_SNR | q_inp_SNR | time |")
print("+==================+==============+============+===========+=======+")
layer = layers[i]
layer.load()
full = find_layers(layer)
sequential = [list(full.keys())]
for names in sequential:
subset = {n: full[n] for n in names}
gptq = {}
for name in subset:
gptq[name] = GPTQ(subset[name])
gptq[name].quantizer.configure(
bits, perchannel=True, sym=sym, mse=False
)
pass
def add_batch(name):
def tmp(_, inp, out):
gptq[name].add_batch(inp[0].data, out.data)
return tmp
handles = []
for name in subset:
handles.append(subset[name].register_forward_hook(add_batch(name)))
for j in range(nsamples):
outs[j] = layer(inps[j].unsqueeze(0), **extra)[0]
for h in handles:
h.remove()
for name in subset:
scale, zero, g_idx, error = gptq[name].fasterquant(
percdamp=percdamp,
groupsize=groupsize,
act_order=act_order,
name=name,
)
quantizers[f"{prefix}.{i}.{name}"] = (
gptq[name].quantizer.cpu(),
scale.cpu(),
zero.cpu(),
g_idx.cpu(),
bits,
groupsize,
)
gptq[name].free()
for j in range(nsamples):
outs[j] = layer(inps[j].unsqueeze(0), **extra)[0]
layer.unload()
del layer
del gptq
torch.cuda.empty_cache()
inps, outs = outs, inps
print("+------------------+--------------+------------+-----------+-------+")
print("\n")
model.config.use_cache = use_cache
return quantizers
def pack(model, quantizers, bits, groupsize):
layers = find_layers(model)
layers = {n: layers[n] for n in quantizers}
make_quant_linear(model, quantizers, bits, groupsize)
qlayers = find_layers(model, (QuantLinear,))
print("Packing ...")
for name in qlayers:
print(name)
quantizers[name], scale, zero, g_idx, _, _ = quantizers[name]
qlayers[name].pack(layers[name], scale, zero, g_idx)
print("Done.")
return model
def load_weights_pre_hook(module_name, weights, recursive=False):
def inner(module, args):
print(f"Pre hook {module_name}")
local_params = {}
for k, v in module.named_parameters():
if not recursive and k.count(".") != 1:
continue
local_params[k] = v
for k, v in module.named_buffers():
if not recursive and k.count(".") != 1:
continue
local_params[k] = v
for local_param in local_params:
current_tensor = getdeepattr(module, local_param)
if current_tensor.device == torch.device("meta"):
# print(f"Loading {local_param}")
if module_name:
tensor_name = f"{module_name}.{local_param}"
else:
tensor_name = local_param
tensor = weights.get_tensor(tensor_name)
setdeepattr(module, local_param, nn.Parameter(tensor))
else:
tensor = current_tensor.to(device=torch.device("cuda:0"))
if current_tensor.requires_grad:
tensor = nn.Parameter(tensor)
setdeepattr(module, local_param, tensor)
return inner
def load_weights_post_hook(module_name, weights, recursive=False):
def inner(module, args, output):
print(f"Post hook {module_name}")
local_params = {}
for k, v in module.named_parameters():
if not recursive and k.count(".") != 1:
continue
local_params[k] = v
for k, v in module.named_buffers():
if not recursive and k.count(".") != 1:
continue
local_params[k] = v
for local_param in local_params:
# print(f"Unloading {local_param}")
current_tensor = getdeepattr(module, local_param)
setdeepattr(
module,
local_param,
nn.Parameter(current_tensor.to(device=torch.device("cpu"))),
)
return output
return inner
def weight_files(
model_id: str, revision: Optional[str] = None, extension: str = ".safetensors"
) -> List[Path]:
"""Get the local files"""
# Local model
d = Path(model_id)
if d.exists() and d.is_dir():
local_files = _weight_files_from_dir(d, extension)
if not local_files:
raise FileNotFoundError(
f"No local weights found in {model_id} with extension {extension}"
)
return [Path(f) for f in local_files]
try:
filenames = weight_hub_files(model_id, revision, extension)
except EntryNotFoundError as e:
if extension != ".safetensors":
raise e
# Try to see if there are pytorch weights
pt_filenames = weight_hub_files(model_id, revision, extension=".bin")
# Change pytorch extension to safetensors extension
# It is possible that we have safetensors weights locally even though they are not on the
# hub if we converted weights locally without pushing them
filenames = [
f"{Path(f).stem.lstrip('pytorch_')}.safetensors" for f in pt_filenames
]
if WEIGHTS_CACHE_OVERRIDE is not None:
files = []
for filename in filenames:
p = Path(WEIGHTS_CACHE_OVERRIDE) / filename
if not p.exists():
raise FileNotFoundError(
f"File {p} not found in {WEIGHTS_CACHE_OVERRIDE}."
)
files.append(p)
return files
files = []
for filename in filenames:
cache_file = try_to_load_from_cache(
model_id, revision=revision, filename=filename
)
if cache_file is None:
raise LocalEntryNotFoundError(
f"File {filename} of model {model_id} not found in "
f"{os.getenv('HUGGINGFACE_HUB_CACHE', 'the local cache')}. "
f"Please run `text-generation-server download-weights {model_id}` first."
)
files.append(cache_file)
return files
def quantize(
model_id: str,
bits: int,
groupsize: int,
output_dir: str,
revision: str,
trust_remote_code: bool,
upload_to_model_id: Optional[str],
percdamp: float,
act_order: bool,
):
print("loading model")
config = AutoConfig.from_pretrained(
model_id,
trust_remote_code=trust_remote_code,
)
with init_empty_weights():
model = AutoModelForCausalLM.from_config(
config, torch_dtype=torch.float16, trust_remote_code=trust_remote_code
)
model = model.eval()
print("LOADED model")
files = weight_files(model_id, revision, extension=".safetensors")
process_group, _, _ = initialize_torch_distributed()
weights = Weights(
files,
device=torch.device("cuda:0"),
dtype=torch.float16,
process_group=process_group,
aliases={"embed_tokens.weight": ["lm_head.weight"]},
)
hooks = []
for name, module in model.named_modules():
def load(module, name):
def _load():
load_weights_pre_hook(name, weights, recursive=True)(module, None)
return _load
def unload(module, name):
def _unload():
load_weights_post_hook(name, weights, recursive=True)(
module, None, None
)
return _unload
module.load = load(module, name)
module.unload = unload(module, name)
hooks.append(
module.register_forward_pre_hook(load_weights_pre_hook(name, weights))
)
hooks.append(
module.register_forward_hook(load_weights_post_hook(name, weights))
)
model.seqlen = 2048
dataset = "wikitext2"
nsamples = 128
seed = None
dataloader, testloader = get_loaders(
dataset,
nsamples=nsamples,
seed=seed,
model_id=model_id,
seqlen=model.seqlen,
trust_remote_code=trust_remote_code,
)
tick = time.time()
quantizers = sequential(
model,
dataloader,
DEV,
nsamples,
bits,
groupsize,
percdamp=percdamp,
act_order=act_order,
hooks=hooks,
)
print(time.time() - tick)
pack(model, quantizers, bits, groupsize)
from safetensors.torch import save_file
from transformers.modeling_utils import shard_checkpoint
state_dict = model.state_dict()
state_dict = {k: v.cpu().contiguous() for k, v in state_dict.items()}
state_dict["gptq_bits"] = torch.LongTensor([bits])
state_dict["gptq_groupsize"] = torch.LongTensor([groupsize])
max_shard_size = "10GB"
shards, index = shard_checkpoint(
state_dict, max_shard_size=max_shard_size, weights_name="model.safetensors"
)
os.makedirs(output_dir, exist_ok=True)
for shard_file, shard in shards.items():
save_file(
shard,
os.path.join(output_dir, shard_file),
metadata={
"format": "pt",
"quantized": "gptq",
"origin": "text-generation-inference",
},
)
if index is None:
path_to_weights = os.path.join(output_dir, "model.safetensors")
logger.info(f"Model weights saved in {path_to_weights}")
else:
save_index_file = "model.safetensors.index.json"
save_index_file = os.path.join(output_dir, save_index_file)
with open(save_index_file, "w", encoding="utf-8") as f:
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
f.write(content)
logger.info(
f"The model is bigger than the maximum size per checkpoint ({max_shard_size}) and is going to be "
f"split in {len(shards)} checkpoint shards. You can find where each parameters has been saved in the "
f"index located at {save_index_file}."
)
config = AutoConfig.from_pretrained(model_id, trust_remote_code=trust_remote_code)
config.save_pretrained(output_dir)
logger.info("Saved config")
logger.info("Saving tokenizer")
tokenizer = AutoTokenizer.from_pretrained(
model_id, trust_remote_code=trust_remote_code
)
tokenizer.save_pretrained(output_dir)
logger.info("Saved tokenizer")
if upload_to_model_id:
api = HfApi()
api.upload_folder(
folder_path=output_dir, repo_id=upload_to_model_id, repo_type="model"
) | null |
2,220 | import math
import numpy as np
import torch
import torch.nn as nn
from torch.cuda.amp import custom_bwd, custom_fwd
try:
import triton
import triton.language as tl
from . import custom_autotune
# code based https://github.com/fpgaminer/GPTQ-triton
configs=[
triton.Config(
{
"BLOCK_SIZE_M": 64,
"BLOCK_SIZE_N": 256,
"BLOCK_SIZE_K": 32,
"GROUP_SIZE_M": 8,
},
num_stages=4,
num_warps=4,
),
triton.Config(
{
"BLOCK_SIZE_M": 128,
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 32,
"GROUP_SIZE_M": 8,
},
num_stages=4,
num_warps=4,
),
triton.Config(
{
"BLOCK_SIZE_M": 64,
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 32,
"GROUP_SIZE_M": 8,
},
num_stages=4,
num_warps=4,
),
triton.Config(
{
"BLOCK_SIZE_M": 128,
"BLOCK_SIZE_N": 32,
"BLOCK_SIZE_K": 32,
"GROUP_SIZE_M": 8,
},
num_stages=4,
num_warps=4,
),
triton.Config(
{
"BLOCK_SIZE_M": 64,
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 32,
"GROUP_SIZE_M": 8,
},
num_stages=4,
num_warps=4,
),
triton.Config(
{
"BLOCK_SIZE_M": 64,
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 32,
"GROUP_SIZE_M": 8,
},
num_stages=2,
num_warps=8,
),
triton.Config(
{
"BLOCK_SIZE_M": 64,
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
},
num_stages=3,
num_warps=8,
),
triton.Config(
{
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 32,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
},
num_stages=2,
num_warps=4,
),
],
key=["M", "N", "K"],
nearest_power_of_two=True,
prune_configs_by={
"early_config_prune": custom_autotune.matmul248_kernel_config_pruner,
"perf_model": None,
"top_k": None,
},
)
def matmul_248_kernel(
a_ptr,
b_ptr,
c_ptr,
scales_ptr,
zeros_ptr,
g_ptr,
M,
N,
K,
bits,
maxq,
stride_am,
stride_ak,
stride_bk,
stride_bn,
stride_cm,
stride_cn,
stride_scales,
stride_zeros,
BLOCK_SIZE_M: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
BLOCK_SIZE_K: tl.constexpr,
GROUP_SIZE_M: tl.constexpr,
):
"""
Compute the matrix multiplication C = A x B.
A is of shape (M, K) float16
B is of shape (K//8, N) int32
C is of shape (M, N) float16
scales is of shape (G, N) float16
zeros is of shape (G, N) float16
g_ptr is of shape (K) int32
"""
infearure_per_bits = 32 // bits
pid = tl.program_id(axis=0)
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
num_pid_k = tl.cdiv(K, BLOCK_SIZE_K)
num_pid_in_group = GROUP_SIZE_M * num_pid_n
group_id = pid // num_pid_in_group
first_pid_m = group_id * GROUP_SIZE_M
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
pid_m = first_pid_m + (pid % group_size_m)
pid_n = (pid % num_pid_in_group) // group_size_m
offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
offs_k = tl.arange(0, BLOCK_SIZE_K)
a_ptrs = a_ptr + (
offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak
) # (BLOCK_SIZE_M, BLOCK_SIZE_K)
a_mask = offs_am[:, None] < M
# b_ptrs is set up such that it repeats elements along the K axis 8 times
b_ptrs = b_ptr + (
(offs_k[:, None] // infearure_per_bits) * stride_bk
+ offs_bn[None, :] * stride_bn
) # (BLOCK_SIZE_K, BLOCK_SIZE_N)
g_ptrs = g_ptr + offs_k
# shifter is used to extract the N bits of each element in the 32-bit word from B
scales_ptrs = scales_ptr + offs_bn[None, :]
zeros_ptrs = zeros_ptr + (offs_bn[None, :] // infearure_per_bits)
shifter = (offs_k % infearure_per_bits) * bits
zeros_shifter = (offs_bn % infearure_per_bits) * bits
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
for k in range(0, num_pid_k):
g_idx = tl.load(g_ptrs)
# Fetch scales and zeros; these are per-outfeature and thus reused in the inner loop
scales = tl.load(
scales_ptrs + g_idx[:, None] * stride_scales
) # (BLOCK_SIZE_K, BLOCK_SIZE_N,)
zeros = tl.load(
zeros_ptrs + g_idx[:, None] * stride_zeros
) # (BLOCK_SIZE_K, BLOCK_SIZE_N,)
zeros = (zeros >> zeros_shifter[None, :]) & maxq
zeros = (zeros + 1) & maxq # eventually avoid overflow
a = tl.load(a_ptrs, mask=a_mask, other=0.0) # (BLOCK_SIZE_M, BLOCK_SIZE_K)
b = tl.load(b_ptrs) # (BLOCK_SIZE_K, BLOCK_SIZE_N), but repeated
# Now we need to unpack b (which is N-bit values) into 32-bit values
b = (b >> shifter[:, None]) & maxq # Extract the N-bit values
b = (b - zeros) * scales # Scale and shift
accumulator += tl.dot(a, b)
a_ptrs += BLOCK_SIZE_K
b_ptrs += (BLOCK_SIZE_K // infearure_per_bits) * stride_bk
g_ptrs += BLOCK_SIZE_K
c_ptrs = c_ptr + stride_cm * offs_am[:, None] + stride_cn * offs_bn[None, :]
c_mask = (offs_am[:, None] < M) & (offs_bn[None, :] < N)
tl.store(c_ptrs, accumulator, mask=c_mask)
except:
print("triton not installed.")
def matmul248(input, qweight, scales, qzeros, g_idx, bits, maxq):
with torch.cuda.device(input.device):
output = torch.empty(
(input.shape[0], qweight.shape[1]), device=input.device, dtype=torch.float16
)
grid = lambda META: (
triton.cdiv(input.shape[0], META["BLOCK_SIZE_M"])
* triton.cdiv(qweight.shape[1], META["BLOCK_SIZE_N"]),
)
matmul_248_kernel[grid](
input,
qweight,
output,
scales,
qzeros,
g_idx,
input.shape[0],
qweight.shape[1],
input.shape[1],
bits,
maxq,
input.stride(0),
input.stride(1),
qweight.stride(0),
qweight.stride(1),
output.stride(0),
output.stride(1),
scales.stride(0),
qzeros.stride(0),
)
return output | null |
2,221 | from functools import lru_cache
def log_once(log, msg: str):
log(msg) | null |
2,222 | import math
import torch
from loguru import logger
from typing import Dict, Union
from text_generation_server.pb.generate_pb2 import GrammarType
from outlines.fsm.fsm import RegexFSM
from outlines.fsm.json_schema import build_regex_from_object
from functools import lru_cache
from typing import List, Optional, DefaultDict
import time
from transformers import (
LogitsWarper,
LogitsProcessor,
TemperatureLogitsWarper,
TopKLogitsWarper,
TopPLogitsWarper,
TypicalLogitsWarper,
)
class StaticWarper:
def __init__(
self,
temperature=1.0,
top_k=None,
top_p=None,
typical_p=None,
):
def __call__(self, scores):
def static_warper(
temperature: Optional[float],
top_k: Optional[int],
top_p: Optional[float],
typical_p: Optional[float],
) -> StaticWarper:
return StaticWarper(
temperature=temperature, top_k=top_k, top_p=top_p, typical_p=typical_p
) | null |
2,223 | import ast
def get_model_node_type(child_node) -> str:
direct_node_types_mapping = [
(ast.If, lambda n: 'if'),
(ast.Pass, lambda n: 'pass'),
((ast.Assign, ast.AnnAssign), lambda n: get_assighment_type(n)),
((ast.FunctionDef, ast.AsyncFunctionDef), lambda n: get_funcdef_type(n)),
(ast.Expr, lambda n: 'docstring' if isinstance(n.value, ast.Str) else 'expression'),
(ast.ClassDef, lambda n: 'meta_class' if child_node.name == 'Meta' else 'nested_class'),
]
for type_or_type_tuple, type_getter in direct_node_types_mapping:
if isinstance(child_node, type_or_type_tuple): # type: ignore
return type_getter(child_node)
def get_model_parts_info(model_ast):
parts_info = []
for child_node in model_ast.body:
node_type = get_model_node_type(child_node)
parts_info.append({
'model_name': model_ast.name,
'node': child_node,
'type': node_type
})
return parts_info | null |
2,224 | from __future__ import annotations
import ast
from typing import Any
FORBIDDEN_TYPES = {
"field",
}
SKIP_SPECIAL_ATTRIBUTES = {
"__code__",
"__slots__",
}
def skip_dataclasses(class_def: ast.ClassDef) -> bool:
if class_def.decorator_list is not None:
for decorator in class_def.decorator_list:
if not isinstance(decorator, ast.Name):
return True
if decorator.id == 'dataclass':
return True
return False
def skip_typed_dicts(class_def: ast.ClassDef) -> bool:
if class_def.bases:
for base in class_def.bases:
if not isinstance(base, ast.Name):
return True
if base.id in SKIP_TYPING_CLASSES:
return True
return False
def get_node_name(node, node_type: str):
special_methods_names = (
'__new__',
'__init__',
'__post_init__',
'__str__',
'save',
'delete',
)
name_getters_by_type = [
('docstring', lambda n: 'docstring'),
('meta_class', lambda n: 'Meta'),
('constant', lambda n: n.target.id if isinstance(n, ast.AnnAssign) else n.targets[0].id), # type: ignore
('field', get_name_for_field_node_type),
(('method',) + special_methods_names, lambda n: n.name),
('nested_class', lambda n: n.name),
('expression', lambda n: '<class_level_expression>'),
('if', lambda n: 'if ...'),
]
for type_postfix, name_getter in name_getters_by_type:
if node_type.endswith(type_postfix): # type: ignore
return name_getter(node)
def get_class_members_errors(
model_parts_info: list[dict[str, Any]], class_def: ast.ClassDef
) -> list[tuple[int, int, str]]:
errors: list[tuple[int, int, str]] = []
if skip_dataclasses(class_def):
return errors
if skip_typed_dicts(class_def):
return errors
for model_part in model_parts_info:
if model_part['type'] in FORBIDDEN_TYPES:
node_name = get_node_name(model_part['node'], model_part['type'])
if node_name in SKIP_SPECIAL_ATTRIBUTES:
continue
errors.append((model_part['node'].lineno, model_part['node'].col_offset, f"CCE003 Class level {model_part['type']} '{node_name}' detected in class {model_part['model_name']}",))
return errors | null |
2,225 | from __future__ import annotations
import itertools
import logging
from collections import defaultdict
from dataclasses import dataclass
from typing import List, Union, Dict, Any
from prettytable import PrettyTable, SINGLE_BORDER
from checkov.common.bridgecrew.severities import BcSeverities
from checkov.common.models.enums import CheckResult
from checkov.common.output.record import Record, SCA_PACKAGE_SCAN_CHECK_NAME, SCA_LICENSE_CHECK_NAME
from checkov.common.output.common import get_package_name_with_lines, validate_lines, get_reachability_output_indication
from checkov.common.packaging import version as packaging_version
from checkov.common.sca.commons import UNFIXABLE_VERSION, get_package_alias
from checkov.common.typing import _LicenseStatusWithLines
from checkov.common.output.common import compare_table_items_severity
REACHABILITY_RISK_FACTORS_KEYS = ["IsUsed", "ReachableFunction"]
class CveCount:
total: int = 0
critical: int = 0
high: int = 0
medium: int = 0
low: int = 0
skipped: int = 0
used: int = 0
has_fix: int = 0
to_fix: int = 0
fixable: bool = True
def output_row(self) -> List[str]:
return [
f"Total CVEs: {self.total}",
f"critical: {self.critical}",
f"high: {self.high}",
f"medium: {self.medium}",
f"low: {self.low}",
f"skipped: {self.skipped}",
f"Total Packages Used: {self.used}",
]
def calculate_lowest_compliant_version(
fix_versions_lists: List[List[Union[packaging_version.Version, packaging_version.LegacyVersion]]]
) -> str:
"""A best effort approach to find the lowest compliant version"""
package_min_versions = set()
package_versions = set()
for fix_versions in fix_versions_lists:
if fix_versions:
package_min_versions.add(min(fix_versions))
package_versions.update(fix_versions)
if package_min_versions:
package_min_version = min(package_min_versions)
package_max_version = max(package_min_versions)
if isinstance(package_min_version, packaging_version.LegacyVersion) or isinstance(
package_max_version, packaging_version.LegacyVersion
):
return str(package_max_version)
elif package_min_version.major == package_max_version.major:
return str(package_max_version)
else:
lowest_version = max(
version
for version in package_versions
if isinstance(version, packaging_version.Version) and version.major == package_max_version.major
)
return str(lowest_version)
return UNFIXABLE_VERSION
def create_cli_license_violations_table(file_path: str,
package_licenses_details_map: Dict[str, List[_LicenseStatusWithLines]],
lines_details_found: bool) -> str:
package_table_lines: List[str] = []
columns = 5
table_width = 136
column_width = int(table_width / columns)
package_table = PrettyTable(min_table_width=table_width, max_table_width=table_width)
package_table.set_style(SINGLE_BORDER)
package_table.field_names = [
"Package name [Lines]" if lines_details_found else "Package name",
"Package version",
"Policy ID",
"License",
"Status",
]
for package_idx, (_, license_statuses) in enumerate(package_licenses_details_map.items()):
if package_idx > 0:
del package_table_lines[-1]
package_table.header = False
package_table.clear_rows()
for idx, license_status in enumerate(license_statuses):
col_package_name = ""
col_package_version = ""
if idx == 0:
col_package_name = get_package_name_with_lines(license_status["package_name"], license_status["lines"])
col_package_version = license_status["package_version"]
curr_row = [
col_package_name,
col_package_version,
license_status["policy"],
license_status["license"],
license_status["status"],
]
package_table.add_row(curr_row)
package_table.align = "l"
package_table.min_width = column_width
package_table.max_width = column_width
for idx, line in enumerate(package_table.get_string().splitlines(keepends=True)):
if idx == 0 and package_idx != 0:
# hack to make multiple tables look like one
line = line.replace(package_table.top_left_junction_char, package_table.left_junction_char).replace(
package_table.top_right_junction_char, package_table.right_junction_char
)
if package_idx > 0:
# hack to make multiple package tables look like one
line = line.replace(package_table.top_junction_char, package_table.junction_char)
# hack for making the table's width as same as the cves-table's
package_table_lines.append(f"\t{line[:-2]}{line[-3]}{line[-2:]}")
return (
f"\t{file_path} - Licenses Statuses:\n"
f"{''.join(package_table_lines)}\n"
)
def create_cli_cves_table(file_path: str, cve_count: CveCount, package_details_map: Dict[str, Dict[str, Any]],
lines_details_found: bool) -> str:
columns = 7
table_width = 159
column_width = int(table_width / columns)
cve_table_lines = create_cve_summary_table_part(
table_width=table_width, column_width=column_width, cve_count=cve_count
)
vulnerable_packages = True if package_details_map else False
fixable_table_lines = create_fixable_cve_summary_table_part(
table_width=table_width, column_count=columns, cve_count=cve_count, vulnerable_packages=vulnerable_packages
)
package_table_lines = create_package_overview_table_part(
table_width=table_width, column_width=column_width, package_details_map=package_details_map,
lines_details_found=lines_details_found
)
return (
f"\t{file_path} - CVEs Summary:\n"
f"{''.join(cve_table_lines)}\n"
f"{''.join(fixable_table_lines)}"
f"{''.join(package_table_lines)}\n"
)
class BcSeverities:
NONE = 'NONE'
INFO = 'INFO'
LOW = 'LOW'
MEDIUM = 'MEDIUM'
HIGH = 'HIGH'
CRITICAL = 'CRITICAL'
MODERATE = 'MODERATE'
IMPORTANT = 'IMPORTANT'
OFF = 'OFF'
class CheckResult(str, Enum):
PASSED = "PASSED"
FAILED = "FAILED"
# Unknown should be used when a check does not wish to return a result, generally due to the inability
# to resolve a value or similar types of errors.
UNKNOWN = "UNKNOWN"
# Skipped is used by the framework when a test is suppressed and should not be used directly by checks.
SKIPPED = "SKIPPED"
SCA_PACKAGE_SCAN_CHECK_NAME = "SCA package scan"
SCA_LICENSE_CHECK_NAME = "SCA license"
class Record:
def __init__(
self,
check_id: str,
check_name: str,
check_result: _CheckResult,
code_block: List[Tuple[int, str]],
file_path: str,
file_line_range: List[int],
resource: str,
evaluations: Optional[Dict[str, Any]],
check_class: str,
file_abs_path: str,
entity_tags: Optional[Dict[str, str]] = None,
caller_file_path: Optional[str] = None,
caller_file_line_range: tuple[int, int] | None = None,
bc_check_id: Optional[str] = None,
resource_address: Optional[str] = None,
severity: Optional[Severity] = None,
bc_category: Optional[str] = None,
benchmarks: dict[str, list[str]] | None = None,
description: Optional[str] = None,
short_description: Optional[str] = None,
vulnerability_details: Optional[Dict[str, Any]] = None,
connected_node: Optional[Dict[str, Any]] = None,
details: Optional[List[str]] = None,
check_len: int | None = None,
definition_context_file_path: Optional[str] = None
) -> None:
"""
:param evaluations: A dict with the key being the variable name, value being a dict containing:
- 'var_file'
- 'value'
- 'definitions', a list of dicts which contain 'definition_expression'
"""
self.check_id = check_id
self.bc_check_id = bc_check_id
self.check_name = check_name
self.check_result = check_result
self.code_block = code_block
self.file_path = file_path
self.file_abs_path = file_abs_path
self.repo_file_path = self._determine_repo_file_path(file_abs_path)
self.file_line_range = file_line_range
self.resource = resource
self.evaluations = evaluations
self.check_class = check_class
self.fixed_definition = None
self.entity_tags = entity_tags
self.caller_file_path = caller_file_path # When created from a module
self.caller_file_line_range = caller_file_line_range # When created from a module
self.resource_address = resource_address
self.severity = severity
self.bc_category = bc_category
self.benchmarks = benchmarks
self.description = description # used by SARIF output
self.short_description = short_description # used by SARIF and GitLab SAST output
self.vulnerability_details = vulnerability_details # Stores package vulnerability details
self.connected_node = connected_node
self.guideline: str | None = None
self.details: List[str] = details or []
self.check_len = check_len
self.definition_context_file_path = definition_context_file_path
def _determine_repo_file_path(file_path: Union[str, "os.PathLike[str]"]) -> str:
# matches file paths given in the BC platform and should always be a unix path
repo_file_path = Path(file_path)
if CURRENT_LOCAL_DRIVE == repo_file_path.drive:
return convert_to_unix_path(f"/{os.path.relpath(repo_file_path)}").replace("/..", "")
return f"/{'/'.join(repo_file_path.parts[1:])}"
def set_guideline(self, guideline: Optional[str]) -> None:
self.guideline = guideline
def _trim_special_chars(expression: str) -> str:
return "".join(re.findall(re.compile(r"[^ ${\}]+"), expression))
def _is_expression_in_code_lines(expression: str, code_block: List[Tuple[int, str]]) -> bool:
stripped_expression = Record._trim_special_chars(expression)
return any(stripped_expression in Record._trim_special_chars(line) for (_, line) in code_block)
def _code_line_string(code_block: List[Tuple[int, str]], colorized: bool = True) -> str:
code_output = []
color_codes = (Fore.WHITE if colorized else "", Fore.YELLOW if colorized else "")
last_line_number_len = len(str(code_block[-1][0]))
if len(code_block) >= OUTPUT_CODE_LINE_LIMIT:
return f'\t\t{color_codes[1]}Code lines for this resource are too many. ' \
f'Please use IDE of your choice to review the file.'
for line_num, line in code_block:
spaces = " " * (last_line_number_len - len(str(line_num)))
if line.lstrip().startswith("#"):
code_output.append(f"\t\t{color_codes[0]}{line_num}{spaces} | {line}")
elif line.lstrip() == PLACEHOLDER_LINE:
code_output.append(f"\t\t{line}")
else:
code_output.append(f"\t\t{color_codes[0]}{line_num}{spaces} | {color_codes[1]}{line}")
return "".join(code_output)
def get_guideline_string(guideline: Optional[str]) -> str:
if guideline:
return (
"\tGuide: "
+ Style.BRIGHT
+ colored(f"{guideline}\n", "blue", attrs=["underline"])
+ Style.RESET_ALL
)
return ''
def get_code_lines_string(code_block: List[Tuple[int, str]]) -> str:
if code_block:
return "\n{}\n".format("".join([Record._code_line_string(code_block, not (ANSI_COLORS_DISABLED))]))
return ''
def get_details_string(details: List[str]) -> str:
if details:
detail_buffer = [colored(f"\tDetails: {details[0]}\n", "blue")]
for t in details[1:]:
detail_buffer.append(colored(f"\t {t}\n", "blue"))
return "".join(detail_buffer)
return ''
def get_caller_file_details_string(caller_file_path: Optional[str], caller_file_line_range: Optional[Tuple[int, int]]) -> str:
if caller_file_path and caller_file_line_range:
return colored(
"\tCalling File: {}:{}\n".format(
caller_file_path, "-".join([str(x) for x in caller_file_line_range])
),
"magenta",
)
return ''
def get_evaluation_string(evaluations: Optional[Dict[str, Any]], code_block: List[Tuple[int, str]]) -> str:
if evaluations:
for (var_name, var_evaluations) in evaluations.items():
var_file = var_evaluations["var_file"]
var_definitions = var_evaluations["definitions"]
for definition_obj in var_definitions:
definition_expression = definition_obj["definition_expression"]
if Record._is_expression_in_code_lines(definition_expression, code_block):
return colored(
f'\tVariable {colored(var_name, "yellow")} (of {var_file}) evaluated to value "{colored(var_evaluations["value"], "yellow")}" '
f'in expression: {colored(definition_obj["definition_name"] + " = ", "yellow")}{colored(definition_obj["definition_expression"], "yellow")}\n',
"white",
)
return ''
def to_string(self, compact: bool = False, use_bc_ids: bool = False) -> str:
status = ""
status_color = "white"
suppress_comment = ""
if self.check_result["result"] == CheckResult.PASSED:
status = CheckResult.PASSED.name
status_color = "green"
elif self.check_result["result"] == CheckResult.FAILED:
status = CheckResult.FAILED.name
status_color = "red"
elif self.check_result["result"] == CheckResult.SKIPPED:
status = CheckResult.SKIPPED.name
status_color = "blue"
suppress_comment = "\tSuppress comment: {}\n".format(self.check_result.get("suppress_comment", ""))
check_message = colored('Check: {}: "{}"\n'.format(self.get_output_id(use_bc_ids), self.check_name), "white")
guideline_message = self.get_guideline_string(self.guideline)
severity_message = f'\tSeverity: {self.severity.name}\n' if self.severity else ''
file_details = colored(
"\tFile: {}:{}\n".format(self.file_path, "-".join([str(x) for x in self.file_line_range])), "magenta"
)
code_lines = self.get_code_lines_string(self.code_block)
detail = self.get_details_string(self.details)
caller_file_details = self.get_caller_file_details_string(self.caller_file_path, self.caller_file_line_range)
evaluation_message = self.get_evaluation_string(self.evaluations, self.code_block)
status_message = colored("\t{} for resource: {}\n".format(status, self.resource), status_color)
if self.check_result["result"] == CheckResult.FAILED and code_lines and not compact:
return f"{check_message}{status_message}{severity_message}{detail}{file_details}{caller_file_details}{guideline_message}{code_lines}{evaluation_message}"
if self.check_result["result"] == CheckResult.SKIPPED:
return f"{check_message}{status_message}{severity_message}{suppress_comment}{detail}{file_details}{caller_file_details}{guideline_message}"
else:
return f"{check_message}{status_message}{severity_message}{detail}{file_details}{caller_file_details}{evaluation_message}{guideline_message}"
def __str__(self) -> str:
return self.to_string()
def get_output_id(self, use_bc_ids: bool) -> str:
return self.bc_check_id if self.bc_check_id and use_bc_ids else self.check_id
def get_unique_string(self) -> str:
return f"{self.check_id}.{self.file_abs_path}.{self.file_line_range}.{self.resource}"
def from_reduced_json(cls, record_json: dict[str, Any]) -> Record:
return Record(
check_id=record_json['check_id'],
bc_check_id=record_json['bc_check_id'],
check_name=record_json['check_name'],
check_result=record_json['check_result'],
code_block=record_json['code_block'],
file_path=record_json['file_path'],
file_line_range=record_json['file_line_range'],
resource=record_json['resource'],
evaluations=record_json.get('evaluations'),
check_class='',
file_abs_path=record_json['file_abs_path'],
severity=record_json.get('severity')
)
def compare_table_items_severity(table_item: dict[str, str]) -> int:
severity = (table_item.get("severity") or DEFAULT_SEVERITY).upper()
return Severities[severity].level
def validate_lines(lines: list[int] | None) -> list[int] | None:
if lines and lines[0] > 0 and lines[1] > 0:
return lines
return None
UNFIXABLE_VERSION = "N/A"
def get_package_alias(package_name: str, package_version: str) -> str:
return f"{package_name}@{package_version}"
class _LicenseStatusWithLines(_LicenseStatus):
lines: list[int] | None # noqa: CCE003 # a static attribute
def create_cli_output(fixable: bool = True, *cve_records: list[Record]) -> str:
cli_outputs = []
group_by_file_path_package_map: dict[str, dict[str, list[Record]]] = defaultdict(dict)
for record in itertools.chain(*cve_records):
if not record.vulnerability_details:
# this shouldn't happen
logging.error(f"'vulnerability_details' is not set for {record.check_id}")
continue
if record.vulnerability_details.get("root_package_name"):
_root_package_alias = get_package_alias(
record.vulnerability_details["root_package_name"],
record.vulnerability_details["root_package_version"])
else: # in case it's license record
_root_package_alias = get_package_alias(record.vulnerability_details["package_name"],
record.vulnerability_details["package_version"])
group_by_file_path_package_map[record.file_path].setdefault(
_root_package_alias, []).append(record)
for file_path, packages in group_by_file_path_package_map.items():
cve_count = CveCount(fixable=fixable)
package_cves_details_map: dict[str, dict[str, Any]] = defaultdict(dict)
package_licenses_details_map = defaultdict(list)
should_print_licenses_table = False
lines_details_found_cves = False
lines_details_found_licenses = False
for root_package_alias, records in packages.items():
fix_versions_lists = []
for record in records:
if not record.vulnerability_details:
# this shouldn't happen
logging.error(f"'vulnerability_details' is not set for {record.check_id}")
continue
package_name = record.vulnerability_details["package_name"]
package_version = record.vulnerability_details["package_version"]
lines = validate_lines(record.file_line_range)
if record.check_name == SCA_PACKAGE_SCAN_CHECK_NAME:
cve_count.total += 1
if record.check_result["result"] == CheckResult.SKIPPED:
cve_count.skipped += 1
continue
else:
cve_count.to_fix += 1
# best way to dynamically access a class instance attribute.
# (we can't just do cve_count.severity_str to access the correct severity)
severity_str = record.severity.name.upper() if record.severity else BcSeverities.NONE.upper()
setattr(cve_count, severity_str.lower(), getattr(cve_count, severity_str.lower()) + 1)
if record.vulnerability_details["lowest_fixed_version"] != UNFIXABLE_VERSION:
cve_count.has_fix += 1
is_root_package = root_package_alias == get_package_alias(package_name, package_version)
if is_root_package: # we want fixed versions just for root packages
fix_versions_lists.append(record.vulnerability_details["fixed_versions"])
else:
root_package_fix_version = record.vulnerability_details.get("root_package_fix_version")
if root_package_fix_version:
parsed_version = packaging_version.parse(root_package_fix_version.strip())
fix_versions_lists.append([parsed_version])
root_package_lines = validate_lines(
record.vulnerability_details.get("root_package_file_line_range"))
if lines or root_package_lines:
lines_details_found_cves = True
risk_factors = {} if not record.vulnerability_details or not record.vulnerability_details.get("risk_factors", {}) else record.vulnerability_details.get("risk_factors", {})
reachability_risk_factors_tmp = {key: value for key, value in risk_factors.items()
if key in REACHABILITY_RISK_FACTORS_KEYS}
if any([value for value in reachability_risk_factors_tmp.values()]):
cve_count.used += 1
package_cves_details_map[root_package_alias].setdefault("cves", []).append(
{
"id": record.vulnerability_details["id"],
"severity": severity_str,
"fixed_version": record.vulnerability_details["lowest_fixed_version"],
"root_package_name": record.vulnerability_details["root_package_name"],
"root_package_version": record.vulnerability_details["root_package_version"],
"root_package_fix_version": record.vulnerability_details.get("root_package_fix_version",
""),
"package_name": package_name,
"package_version": package_version,
"lines": lines,
"root_package_lines": root_package_lines,
"is_private_fix": record.vulnerability_details.get("is_private_fix"),
"reachability_risk_factors": reachability_risk_factors_tmp
}
)
elif record.check_name == SCA_LICENSE_CHECK_NAME:
if record.check_result["result"] == CheckResult.SKIPPED:
continue
should_print_licenses_table = True
if lines:
lines_details_found_licenses = True
package_licenses_details_map[get_package_alias(package_name, package_version)].append(
_LicenseStatusWithLines(package_name=package_name,
package_version=package_version,
policy=record.vulnerability_details["policy"],
license=record.vulnerability_details["license"],
status=record.vulnerability_details["status"],
lines=lines)
)
if root_package_alias in package_cves_details_map:
package_cves_details_map[root_package_alias]["cves"].sort(key=compare_table_items_severity,
reverse=True)
package_cves_details_map[root_package_alias]["compliant_version"] = calculate_lowest_compliant_version(
fix_versions_lists)
if cve_count.total > 0:
cli_outputs.append(
create_cli_cves_table(
file_path=file_path,
cve_count=cve_count,
package_details_map=package_cves_details_map,
lines_details_found=lines_details_found_cves
)
)
if should_print_licenses_table:
cli_outputs.append(
create_cli_license_violations_table(
file_path=file_path,
package_licenses_details_map=package_licenses_details_map,
lines_details_found=lines_details_found_licenses
)
)
return "\n".join(cli_outputs) | null |
2,226 | from __future__ import annotations
import logging
import re
from pathlib import Path
from typing import Any
from checkov.ansible.graph_builder.graph_components.resource_types import ResourceType
from checkov.common.parsers.yaml.parser import parse
from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger
from checkov.common.util.consts import START_LINE, END_LINE
from checkov.common.util.file_utils import read_file_with_any_encoding
from checkov.common.util.suppression import collect_suppressions_for_context
The provided code snippet includes necessary dependencies for implementing the `get_scannable_file_paths` function. Write a Python function `def get_scannable_file_paths(root_folder: str | Path) -> set[Path]` to solve the following problem:
Finds yaml files
Here is the function:
def get_scannable_file_paths(root_folder: str | Path) -> set[Path]:
"""Finds yaml files"""
file_paths: set[Path] = set()
if root_folder:
root_path = root_folder if isinstance(root_folder, Path) else Path(root_folder)
file_paths = {file_path for file_path in root_path.rglob("*.[y][am]*[l]") if file_path.is_file()}
return file_paths | Finds yaml files |
2,227 | from __future__ import annotations
import logging
import re
from pathlib import Path
from typing import Any
from checkov.ansible.graph_builder.graph_components.resource_types import ResourceType
from checkov.common.parsers.yaml.parser import parse
from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger
from checkov.common.util.consts import START_LINE, END_LINE
from checkov.common.util.file_utils import read_file_with_any_encoding
from checkov.common.util.suppression import collect_suppressions_for_context
def get_relevant_file_content(file_path: str | Path) -> str | None:
if not str(file_path).endswith((".yaml", ".yml")):
return None
content = read_file_with_any_encoding(file_path=file_path)
if "name:" not in content:
# the following regex will search more precisely, but no need to further process
return None
match_task_name = re.search(TASK_NAME_PATTERN, content)
if match_task_name:
# there are more files, which belong to an ansible playbook,
# but we are currently only interested in 'tasks'
return content
return None
def parse(
filename: str, file_content: str | None = None
) -> tuple[dict[str, Any] | list[dict[str, Any]], list[tuple[int, str]]] | None:
template = None
template_lines = None
try:
if filename.endswith(".yaml") or filename.endswith(".yml"):
template, template_lines = loader.load(filename, file_content)
if template and template_lines:
if isinstance(template, list):
for t in template:
if t and isinstance(t, (list, dict)):
return t, template_lines
else:
return None
else:
return None
except IOError as e:
if e.errno == 2:
logger.error(f"Template file not found: {filename}")
return None
elif e.errno == 21:
logger.error(f"Template references a directory, not a file: {filename}")
return None
elif e.errno == 13:
logger.error(f"Permission denied when accessing template file: {filename}")
return None
except UnicodeDecodeError:
logger.error(f"Cannot read file contents: {filename}")
return None
except YAMLError:
if filename.endswith(".yaml") or filename.endswith(".yml"):
logger.debug(f"Cannot read file contents: {filename} - is it a yaml?")
return None
return None
def parse_file(
f: str | Path, file_content: str | None = None
) -> tuple[dict[str, Any] | list[dict[str, Any]], list[tuple[int, str]]] | None:
file_content = get_relevant_file_content(file_path=f)
if file_content:
content = parse(filename=str(f), file_content=file_content)
return content
return None | null |
2,228 | from __future__ import annotations
import logging
import re
from pathlib import Path
from typing import Any
from checkov.ansible.graph_builder.graph_components.resource_types import ResourceType
from checkov.common.parsers.yaml.parser import parse
from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger
from checkov.common.util.consts import START_LINE, END_LINE
from checkov.common.util.file_utils import read_file_with_any_encoding
from checkov.common.util.suppression import collect_suppressions_for_context
logger = logging.getLogger(__name__)
def _process_blocks(
definition_raw: list[tuple[int, str]],
file_path_context: dict[str, Any],
task: Any,
prefix: str = "",
) -> None:
"""Checks for possible block usage"""
if not task or not isinstance(task, dict):
return
if ResourceType.BLOCK in task and isinstance(task[ResourceType.BLOCK], list):
prefix += f"{ResourceType.BLOCK}." # with each nested level an extra block prefix is added
block_name = f"{prefix}.{task.get('name') or 'unknown'}"
resource_context = _create_resource_context(definition_raw=definition_raw, resource=task)
file_path_context[block_name] = resource_context
for block_task in task[ResourceType.BLOCK]:
_process_blocks(
definition_raw=definition_raw, file_path_context=file_path_context, task=block_task, prefix=prefix
)
else:
resource_context = _create_resource_context(definition_raw=definition_raw, resource=task)
task_name = generate_task_name(task=task, prefix=prefix)
if task_name:
file_path_context[task_name] = resource_context
class ResourceType(str, Enum):
BLOCK = "block"
TASKS = "tasks"
def __str__(self) -> str:
# needed, because of a Python 3.11 change
return self.value
def build_definitions_context(
definitions: dict[str, dict[str, Any] | list[dict[str, Any]]],
definitions_raw: dict[str, list[tuple[int, str]]],
) -> dict[str, dict[str, Any]]:
definitions_context: dict[str, dict[str, Any]] = {}
for file_path, definition in definitions.items():
file_path_context: dict[str, Any] = {}
definition_raw = definitions_raw[file_path]
if not isinstance(definition, list):
logger.info(f"File {file_path} has the wrong type {type(definition)}")
continue
for code_block in definition:
if ResourceType.TASKS in code_block:
for task in code_block[ResourceType.TASKS]:
_process_blocks(definition_raw=definition_raw, file_path_context=file_path_context, task=task)
else:
_process_blocks(definition_raw=definition_raw, file_path_context=file_path_context, task=code_block)
definitions_context[file_path] = file_path_context
return definitions_context | null |
2,229 | from __future__ import annotations
import json
import logging
import os
import platform
from pathlib import Path
from typing import Any, Tuple
import dpath
import yaml
from jsonschema import validate, ValidationError
from checkov.common.parsers.yaml.loader import SafeLineLoaderGhaSchema
from checkov.common.parsers.yaml.parser import parse
from checkov.common.util.file_utils import read_file_with_any_encoding
from checkov.common.util.type_forcers import force_dict
from checkov.github_actions.graph_builder.graph_components.resource_types import ResourceType
from checkov.github_actions.schemas import gha_schema, gha_workflow
from checkov.runner_filter import RunnerFilter
def get_scannable_file_paths(root_folder: str | Path) -> set[Path]:
"""Finds yaml files"""
file_paths: set[Path] = set()
if root_folder:
root_path = root_folder if isinstance(root_folder, Path) else Path(root_folder)
file_paths = {file_path for file_path in root_path.rglob("*.[y][am]*[l]") if file_path.is_file()}
return file_paths
def parse_file(
f: str | Path, file_content: str | None = None
) -> tuple[dict[str, Any] | list[dict[str, Any]], list[tuple[int, str]]] | None:
file_path = f if isinstance(f, Path) else Path(f)
if is_workflow_file(file_path):
if not file_content:
file_content = read_file_with_any_encoding(file_path=file_path)
entity_schema = parse(filename=str(f), file_content=file_content)
if entity_schema and is_schema_valid(yaml.load(file_content, Loader=SafeLineLoaderGhaSchema)): # nosec
return entity_schema
return None
class RunnerFilter(object):
# NOTE: This needs to be static because different filters may be used at load time versus runtime
# (see note in BaseCheckRegistery.register). The concept of which checks are external is
# logically a "static" concept anyway, so this makes logical sense.
__EXTERNAL_CHECK_IDS: Set[str] = set()
def __init__(
self,
framework: Optional[List[str]] = None,
checks: Union[str, List[str], None] = None,
skip_checks: Union[str, List[str], None] = None,
include_all_checkov_policies: bool = True,
download_external_modules: bool = False,
external_modules_download_path: str = DEFAULT_EXTERNAL_MODULES_DIR,
evaluate_variables: bool = True,
runners: Optional[List[str]] = None,
skip_framework: Optional[List[str]] = None,
excluded_paths: Optional[List[str]] = None,
all_external: bool = False,
var_files: Optional[List[str]] = None,
skip_cve_package: Optional[List[str]] = None,
use_enforcement_rules: bool = False,
filtered_policy_ids: Optional[List[str]] = None,
show_progress_bar: Optional[bool] = True,
run_image_referencer: bool = False,
enable_secret_scan_all_files: bool = False,
block_list_secret_scan: Optional[List[str]] = None,
deep_analysis: bool = False,
repo_root_for_plan_enrichment: Optional[List[str]] = None,
resource_attr_to_omit: Optional[Dict[str, Set[str]]] = None,
enable_git_history_secret_scan: bool = False,
git_history_timeout: str = '12h',
git_history_last_commit_scanned: Optional[str] = None, # currently not exposed by a CLI flag
report_sast_imports: bool = False,
remove_default_sast_policies: bool = False,
report_sast_reachability: bool = False
) -> None:
checks = convert_csv_string_arg_to_list(checks)
skip_checks = convert_csv_string_arg_to_list(skip_checks)
self.skip_invalid_secrets = skip_checks and any(skip_check.capitalize() == ValidationStatus.INVALID.value
for skip_check in skip_checks)
self.use_enforcement_rules = use_enforcement_rules
self.enforcement_rule_configs: Dict[str, Severity | Dict[CodeCategoryType, Severity]] = {}
# we will store the lowest value severity we find in checks, and the highest value we find in skip-checks
# so the logic is "run all checks >= severity" and/or "skip all checks <= severity"
self.check_threshold = None
self.skip_check_threshold = None
self.checks = []
self.bc_cloned_checks: dict[str, list[dict[str, Any]]] = defaultdict(list)
self.skip_checks = []
self.skip_checks_regex_patterns = defaultdict(list)
self.show_progress_bar = show_progress_bar
# split out check/skip thresholds so we can access them easily later
for val in (checks or []):
if val.upper() in Severities:
val = val.upper()
if not self.check_threshold or self.check_threshold.level > Severities[val].level:
self.check_threshold = Severities[val]
else:
self.checks.append(val)
# Get regex patterns to split checks and remove it from skip checks:
updated_skip_checks = set(skip_checks)
for val in (skip_checks or []):
splitted_check = val.split(":")
# In case it's not expected pattern
if len(splitted_check) != 2:
continue
self.skip_checks_regex_patterns[splitted_check[0]].append(splitted_check[1])
updated_skip_checks -= {val}
skip_checks = list(updated_skip_checks)
for val in (skip_checks or []):
if val.upper() in Severities:
val = val.upper()
if not self.skip_check_threshold or self.skip_check_threshold.level < Severities[val].level:
self.skip_check_threshold = Severities[val]
else:
self.skip_checks.append(val)
self.include_all_checkov_policies = include_all_checkov_policies
if not framework or "all" in framework:
self.framework_flag_values = []
else:
self.framework_flag_values = framework
self.framework: "Iterable[str]" = framework if framework else ["all"]
if skip_framework:
if "all" in self.framework:
if runners is None:
runners = []
self.framework = set(runners) - set(skip_framework)
else:
self.framework = set(self.framework) - set(skip_framework)
logging.debug(f"Resultant set of frameworks (removing skipped frameworks): {','.join(self.framework)}")
self.download_external_modules = download_external_modules
self.external_modules_download_path = external_modules_download_path
self.evaluate_variables = evaluate_variables
self.excluded_paths = excluded_paths or []
self.all_external = all_external
self.var_files = var_files
self.skip_cve_package = skip_cve_package
self.filtered_policy_ids = filtered_policy_ids or []
self.run_image_referencer = run_image_referencer
self.enable_secret_scan_all_files = enable_secret_scan_all_files
self.block_list_secret_scan = block_list_secret_scan
self.suppressed_policies: List[str] = []
self.deep_analysis = deep_analysis
self.repo_root_for_plan_enrichment = repo_root_for_plan_enrichment
self.resource_attr_to_omit: DefaultDict[str, Set[str]] = RunnerFilter._load_resource_attr_to_omit(
resource_attr_to_omit
)
self.sast_languages: Set[SastLanguages] = RunnerFilter.get_sast_languages(framework, skip_framework)
if self.sast_languages and any(item for item in self.framework if item.startswith(CheckType.SAST) or item == 'all'):
self.framework = [item for item in self.framework if not item.startswith(CheckType.SAST)]
self.framework.append(CheckType.SAST)
elif not self.sast_languages:
# remove all SAST and CDK frameworks
self.framework = [
item for item in self.framework if not item.startswith(CheckType.SAST) and item != CheckType.CDK
]
self.enable_git_history_secret_scan: bool = enable_git_history_secret_scan
if self.enable_git_history_secret_scan:
self.git_history_timeout = convert_to_seconds(git_history_timeout)
self.framework = [CheckType.SECRETS]
logging.debug("Scan secrets history was enabled ignoring other frameworks")
self.git_history_last_commit_scanned = git_history_last_commit_scanned
self.report_sast_imports = report_sast_imports
self.remove_default_sast_policies = remove_default_sast_policies
self.report_sast_reachability = report_sast_reachability
def _load_resource_attr_to_omit(resource_attr_to_omit_input: Optional[Dict[str, Set[str]]]) -> DefaultDict[str, Set[str]]:
resource_attributes_to_omit: DefaultDict[str, Set[str]] = defaultdict(set)
# In order to create new object (and not a reference to the given one)
if resource_attr_to_omit_input:
resource_attributes_to_omit.update(resource_attr_to_omit_input)
return resource_attributes_to_omit
def apply_enforcement_rules(self, enforcement_rule_configs: Dict[str, CodeCategoryConfiguration]) -> None:
self.enforcement_rule_configs = {}
for report_type, code_category in CodeCategoryMapping.items():
if isinstance(code_category, list):
self.enforcement_rule_configs[report_type] = {c: enforcement_rule_configs.get(c).soft_fail_threshold for c in code_category} # type:ignore[union-attr] # will not be None
else:
config = enforcement_rule_configs.get(code_category)
if not config:
raise Exception(f'Could not find an enforcement rule config for category {code_category} (runner: {report_type})')
self.enforcement_rule_configs[report_type] = config.soft_fail_threshold
def extract_enforcement_rule_threshold(self, check_id: str, report_type: str) -> Severity:
if 'sca_' in report_type and '_LIC_' in check_id:
return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.LICENSES]
elif 'sca_' in report_type: # vulnerability
return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.VULNERABILITIES]
else:
return cast(Severity, self.enforcement_rule_configs[report_type])
def should_run_check(
self,
check: BaseCheck | BaseGraphCheck | BaseSastCheck | None = None,
check_id: str | None = None,
bc_check_id: str | None = None,
severity: Severity | None = None,
report_type: str | None = None,
file_origin_paths: List[str] | None = None,
root_folder: str | None = None
) -> bool:
if check:
check_id = check.id
bc_check_id = check.bc_id
severity = check.severity
assert check_id is not None # nosec (for mypy (and then for bandit))
check_threshold: Optional[Severity]
skip_check_threshold: Optional[Severity]
# apply enforcement rules if specified, but let --check/--skip-check with a severity take priority
if self.use_enforcement_rules and report_type:
if not self.check_threshold and not self.skip_check_threshold:
check_threshold = self.extract_enforcement_rule_threshold(check_id, report_type)
skip_check_threshold = None
else:
check_threshold = self.check_threshold
skip_check_threshold = self.skip_check_threshold
else:
if self.use_enforcement_rules:
# this is a warning for us (but there is nothing the user can do about it)
logging.debug(f'Use enforcement rules is true, but check {check_id} was not passed to the runner filter with a report type')
check_threshold = self.check_threshold
skip_check_threshold = self.skip_check_threshold
run_severity = severity and check_threshold and severity.level >= check_threshold.level
explicit_run = self.checks and self.check_matches(check_id, bc_check_id, self.checks)
implicit_run = not self.checks and not check_threshold
is_external = RunnerFilter.is_external_check(check_id)
is_policy_filtered = self.is_policy_filtered(check_id)
# True if this check is present in the allow list, or if there is no allow list
# this is not necessarily the return value (need to apply other filters)
should_run_check = (
run_severity or
explicit_run or
implicit_run or
(is_external and self.all_external)
)
if not should_run_check:
logging.debug(f'Should run check {check_id}: False')
return False
# If a policy is not present in the list of filtered policies, it should not be run - implicitly or explicitly.
# It can, however, be skipped.
if not is_policy_filtered:
logging.debug(f'not is_policy_filtered {check_id}: should_run_check = False')
should_run_check = False
skip_severity = severity and skip_check_threshold and severity.level <= skip_check_threshold.level
explicit_skip = self.skip_checks and self.check_matches(check_id, bc_check_id, self.skip_checks)
regex_match = self._match_regex_pattern(check_id, file_origin_paths, root_folder)
should_skip_check = (
skip_severity or
explicit_skip or
regex_match or
(not bc_check_id and not self.include_all_checkov_policies and not is_external and not explicit_run) or
(bc_check_id in self.suppressed_policies and bc_check_id not in self.bc_cloned_checks)
)
logging.debug(f'skip_severity = {skip_severity}, explicit_skip = {explicit_skip}, regex_match = {regex_match}, suppressed_policies: {self.suppressed_policies}')
logging.debug(
f'bc_check_id = {bc_check_id}, include_all_checkov_policies = {self.include_all_checkov_policies}, is_external = {is_external}, explicit_run: {explicit_run}')
if should_skip_check:
result = False
logging.debug(f'should_skip_check {check_id}: {should_skip_check}')
elif should_run_check:
result = True
logging.debug(f'should_run_check {check_id}: {result}')
else:
result = False
logging.debug(f'default {check_id}: {result}')
return result
def _match_regex_pattern(self, check_id: str, file_origin_paths: List[str] | None, root_folder: str | None) -> bool:
"""
Check if skip check_id for a certain file_types, according to given path pattern
"""
if not file_origin_paths:
return False
regex_patterns = self.skip_checks_regex_patterns.get(check_id, [])
# In case skip is generic, for example, CKV_AZURE_*.
generic_check_id = f"{'_'.join(i for i in check_id.split('_')[:-1])}_*"
generic_check_regex_patterns = self.skip_checks_regex_patterns.get(generic_check_id, [])
regex_patterns.extend(generic_check_regex_patterns)
if not regex_patterns:
return False
for pattern in regex_patterns:
if not pattern:
continue
full_regex_pattern = fr"^{root_folder}/{pattern}" if root_folder else pattern
try:
if any(re.search(full_regex_pattern, path) for path in file_origin_paths):
return True
except Exception as exc:
logging.error(
"Invalid regex pattern has been supplied",
extra={"regex_pattern": pattern, "exc": str(exc)}
)
return False
def check_matches(check_id: str,
bc_check_id: Optional[str],
pattern_list: List[str]) -> bool:
return any(
(fnmatch.fnmatch(check_id, pattern) or (bc_check_id and fnmatch.fnmatch(bc_check_id, pattern))) for pattern
in pattern_list)
def within_threshold(self, severity: Severity) -> bool:
above_min = (not self.check_threshold) or self.check_threshold.level <= severity.level
below_max = self.skip_check_threshold and self.skip_check_threshold.level >= severity.level
return above_min and not below_max
def secret_validation_status_matches(secret_validation_status: str, statuses_list: list[str]) -> bool:
return secret_validation_status in statuses_list
def notify_external_check(check_id: str) -> None:
RunnerFilter.__EXTERNAL_CHECK_IDS.add(check_id)
def is_external_check(check_id: str) -> bool:
return check_id in RunnerFilter.__EXTERNAL_CHECK_IDS
def is_policy_filtered(self, check_id: str) -> bool:
if not self.filtered_policy_ids:
return True
return check_id in self.filtered_policy_ids
def to_dict(self) -> Dict[str, Any]:
result: Dict[str, Any] = {}
for key, value in self.__dict__.items():
result[key] = value
return result
def from_dict(obj: Dict[str, Any]) -> RunnerFilter:
framework = obj.get('framework')
checks = obj.get('checks')
skip_checks = obj.get('skip_checks')
include_all_checkov_policies = obj.get('include_all_checkov_policies')
if include_all_checkov_policies is None:
include_all_checkov_policies = True
download_external_modules = obj.get('download_external_modules')
if download_external_modules is None:
download_external_modules = False
external_modules_download_path = obj.get('external_modules_download_path')
if external_modules_download_path is None:
external_modules_download_path = DEFAULT_EXTERNAL_MODULES_DIR
evaluate_variables = obj.get('evaluate_variables')
if evaluate_variables is None:
evaluate_variables = True
runners = obj.get('runners')
skip_framework = obj.get('skip_framework')
excluded_paths = obj.get('excluded_paths')
all_external = obj.get('all_external')
if all_external is None:
all_external = False
var_files = obj.get('var_files')
skip_cve_package = obj.get('skip_cve_package')
use_enforcement_rules = obj.get('use_enforcement_rules')
if use_enforcement_rules is None:
use_enforcement_rules = False
filtered_policy_ids = obj.get('filtered_policy_ids')
show_progress_bar = obj.get('show_progress_bar')
if show_progress_bar is None:
show_progress_bar = True
run_image_referencer = obj.get('run_image_referencer')
if run_image_referencer is None:
run_image_referencer = False
enable_secret_scan_all_files = bool(obj.get('enable_secret_scan_all_files'))
block_list_secret_scan = obj.get('block_list_secret_scan')
runner_filter = RunnerFilter(framework, checks, skip_checks, include_all_checkov_policies,
download_external_modules, external_modules_download_path, evaluate_variables,
runners, skip_framework, excluded_paths, all_external, var_files,
skip_cve_package, use_enforcement_rules, filtered_policy_ids, show_progress_bar,
run_image_referencer, enable_secret_scan_all_files, block_list_secret_scan)
return runner_filter
def set_suppressed_policies(self, policy_level_suppressions: List[str]) -> None:
logging.debug(f"Received the following policy-level suppressions, that will be skipped from running: {policy_level_suppressions}")
self.suppressed_policies = policy_level_suppressions
def get_sast_languages(frameworks: Optional[List[str]], skip_framework: Optional[List[str]]) -> Set[SastLanguages]:
langs: Set[SastLanguages] = set()
if not frameworks or (skip_framework and "sast" in skip_framework):
return langs
if 'all' in frameworks:
sast_languages = SastLanguages.set()
skip_framework = [] if not skip_framework else [f.split("sast_")[-1] for f in skip_framework]
return set([lang for lang in sast_languages if lang.value not in skip_framework])
for framework in frameworks:
if framework in [CheckType.SAST, CheckType.CDK]:
for sast_lang in SastLanguages:
langs.add(sast_lang)
return langs
if not framework.startswith(CheckType.SAST):
continue
lang = '_'.join(framework.split('_')[1:])
langs.add(SastLanguages[lang.upper()])
return langs
def get_gha_files_definitions(root_folder: str | Path,
files: "list[str] | None" = None,
runner_filter: RunnerFilter | None = None,) -> tuple[dict[str, Any], dict[str, Any]]:
definitions = {}
definitions_raw = {}
file_paths = get_scannable_file_paths(root_folder=root_folder)
files_set = set(files) if files else set()
for file_path in file_paths:
str_file_path = str(file_path)
should_parse: bool = str_file_path in files_set if files_set else True
if should_parse:
result = parse_file(f=file_path)
# result should be tuple of dict representing the file payload structure and list of lines of the payload
if result is not None:
definitions[str_file_path] = result[0]
definitions_raw[str_file_path] = result[1]
return definitions, definitions_raw | null |
2,230 | from __future__ import annotations
import json
import logging
import os
import platform
from pathlib import Path
from typing import Any, Tuple
import dpath
import yaml
from jsonschema import validate, ValidationError
from checkov.common.parsers.yaml.loader import SafeLineLoaderGhaSchema
from checkov.common.parsers.yaml.parser import parse
from checkov.common.util.file_utils import read_file_with_any_encoding
from checkov.common.util.type_forcers import force_dict
from checkov.github_actions.graph_builder.graph_components.resource_types import ResourceType
from checkov.github_actions.schemas import gha_schema, gha_workflow
from checkov.runner_filter import RunnerFilter
def definition_locator_helper(definition: str | list[str], target: str) -> bool:
if isinstance(definition, str):
return definition in target
elif isinstance(definition, list):
return all(item in target for item in definition)
return False
class ResourceType(str, Enum):
JOBS = "jobs"
PERMISSIONS = "permissions"
STEPS = "steps"
ON = "on"
def __str__(self) -> str:
# needed, because of a Python 3.11 change
return self.value
def build_gha_definitions_context(definitions: dict[str, dict[str, Any]], definitions_raw: dict[str, list[Tuple[int, str]]]) -> dict[str, dict[str, Any]]:
definitions_context: dict[str, dict[str, Any]] = {}
resources = [e.value for e in ResourceType]
# iterate on the files
for file_path, file_path_definitions in definitions.items():
# iterate on the definitions (Parameters, Resources, Outputs...)
for file_path_definition, definition in file_path_definitions.items():
if isinstance(file_path_definition, str) and file_path_definition in resources:
# iterate on the actual objects of each definition
if isinstance(definition, dict):
for attribute, attr_value in definition.items():
if isinstance(attr_value, dict):
start_line = attr_value['__startline__']
end_line = attr_value['__endline__']
elif isinstance(attr_value, str) and '__startline__' in definition and '__endline__' in definition:
start_line = definition['__startline__']
end_line = definition['__endline__']
else:
continue
code_lines = definitions_raw[file_path][start_line - 1: end_line - 1]
dpath.new(
definitions_context,
[file_path, str(file_path_definition), str(attribute)],
{"start_line": start_line, "end_line": end_line, "code_lines": code_lines},
)
elif isinstance(definition, (str, list)):
for line_tuple in definitions_raw[file_path]:
if file_path_definition in line_tuple[1] and definition_locator_helper(definition, line_tuple[1]):
code_lines = definitions_raw[file_path][line_tuple[0] - 1:line_tuple[0]]
dpath.new(
definitions_context,
[file_path, str(file_path_definition), str(definition)],
{"start_line": line_tuple[0], "end_line": line_tuple[0] + 1, "code_lines": code_lines},
)
break
return definitions_context | null |
2,231 | from __future__ import annotations
import logging
import re
from collections.abc import Collection
from pathlib import Path
from typing import Any
from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger
from checkov.terraform_json.parser import parse
TF_JSON_POSSIBLE_FILE_ENDINGS = (".tf.json",)
The provided code snippet includes necessary dependencies for implementing the `get_scannable_file_paths` function. Write a Python function `def get_scannable_file_paths( root_folder: str | Path | None = None, files: list[str] | None = None, excluded_paths: list[str] | None = None ) -> set[Path]` to solve the following problem:
Finds Terraform JSON files
Here is the function:
def get_scannable_file_paths(
root_folder: str | Path | None = None, files: list[str] | None = None, excluded_paths: list[str] | None = None
) -> set[Path]:
"""Finds Terraform JSON files"""
file_paths: set[Path] = set()
if root_folder:
root_path = Path(root_folder)
file_paths = {
file_path
for file_ending in TF_JSON_POSSIBLE_FILE_ENDINGS
for file_path in root_path.rglob(f"*{file_ending}")
if file_path.is_file()
}
if excluded_paths:
compiled = [re.compile(p.replace(".terraform", r"\.terraform")) for p in excluded_paths]
file_paths = {
file_path for file_path in file_paths if not any(pattern.search(str(file_path)) for pattern in compiled)
}
if files:
for file in files:
if file.endswith(TF_JSON_POSSIBLE_FILE_ENDINGS):
file_paths.add(Path(file))
return file_paths | Finds Terraform JSON files |
2,232 | from __future__ import annotations
import logging
import re
from collections.abc import Collection
from pathlib import Path
from typing import Any
from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger
from checkov.terraform_json.parser import parse
logger = logging.getLogger(__name__)
def parse(file_path: Path) -> tuple[dict[str, Any], list[tuple[int, str]]] | tuple[None, None]:
"""Parse file to dict object"""
template = None
template_lines = None
try:
template, template_lines = loads(file_path=file_path)
except IOError as e:
if e.errno == 2:
logger.error(f"Template file not found: {file_path}")
elif e.errno == 21:
logger.error(f"Template references a directory, not a file: {file_path}")
elif e.errno == 13:
logger.error(f"Permission denied when accessing template file: {file_path}")
except UnicodeDecodeError:
logger.error(f"Cannot read file contents: {file_path}")
except ScannerError as err:
if err.problem in ("found character '\\t' that cannot start any token", "found unknown escape character"):
try:
result = json_parse(file_path, allow_nulls=False)
if result:
template, template_lines = result # type:ignore[assignment] # this is handled by the next line
if isinstance(template, list):
# should not happen and is more relevant for type safety
template = template[0]
except Exception:
logger.error(f"Template {file_path} is malformed: {err.problem}")
logger.error(f"Tried to parse {file_path} as JSON", exc_info=True)
except YAMLError:
pass
if template is None or template_lines is None:
return None, None
return template, template_lines
The provided code snippet includes necessary dependencies for implementing the `create_definitions` function. Write a Python function `def create_definitions( file_paths: Collection[Path], ) -> tuple[dict[str, dict[str, Any]], dict[str, list[tuple[int, str]]], list[str]]` to solve the following problem:
Creates dict objects and code lines for given files
Here is the function:
def create_definitions(
file_paths: Collection[Path],
) -> tuple[dict[str, dict[str, Any]], dict[str, list[tuple[int, str]]], list[str]]:
"""Creates dict objects and code lines for given files"""
logger.info(f"Start to parse {len(file_paths)} files")
definitions: "dict[str, dict[str, Any]]" = {}
definitions_raw: "dict[str, list[tuple[int, str]]]" = {}
parsing_errors: "list[str]" = []
for file_path in file_paths:
template, file_lines = parse(file_path)
if template and file_lines:
file_path_str = str(file_path)
definitions[file_path_str] = template
definitions_raw[file_path_str] = file_lines
else:
parsing_errors.append(str(file_path.resolve()))
logging.info(f"Successfully parsed {len(definitions)} files")
return definitions, definitions_raw, parsing_errors | Creates dict objects and code lines for given files |
2,233 | from __future__ import annotations
import os
import re
import inspect
from typing import List, Optional, Tuple, Union
from tabulate import tabulate
from checkov.ansible.checks.registry import registry as ansible_registry
from checkov.argo_workflows.checks.registry import registry as argo_workflows_registry
from checkov.arm.registry import arm_resource_registry, arm_parameter_registry
from checkov.azure_pipelines.checks.registry import registry as azure_pipelines_registry
from checkov.bicep.checks.param.registry import registry as bicep_param_registry
from checkov.bicep.checks.resource.registry import registry as bicep_resource_registry
from checkov.bitbucket.registry import registry as bitbucket_configuration_registry
from checkov.bitbucket_pipelines.registry import registry as bitbucket_pipelines_registry
from checkov.circleci_pipelines.registry import registry as circleci_pipelines_registry
from checkov.cloudformation.checks.resource.registry import cfn_registry as cfn_registry
from checkov.common.checks.base_check_registry import BaseCheckRegistry
from checkov.common.checks_infra.registry import BaseRegistry as BaseGraphRegistry, get_graph_checks_registry
from checkov.common.runners.base_runner import strtobool
from checkov.dockerfile.registry import registry as dockerfile_registry
from checkov.github.registry import registry as github_configuration_registry
from checkov.github_actions.checks.registry import registry as github_actions_jobs_registry
from checkov.gitlab.registry import registry as gitlab_configuration_registry
from checkov.gitlab_ci.checks.registry import registry as gitlab_ci_jobs_registry
from checkov.kubernetes.checks.resource.registry import registry as k8_registry
from checkov.secrets.runner import CHECK_ID_TO_SECRET_TYPE
from checkov.serverless.registry import sls_registry
from checkov.terraform.checks.data.registry import data_registry
from checkov.terraform.checks.module.registry import module_registry
from checkov.terraform.checks.provider.registry import provider_registry
from checkov.terraform.checks.resource.registry import resource_registry
from checkov.openapi.checks.registry import openapi_registry
from checkov.common.bridgecrew.integration_features.features.policy_metadata_integration import integration as metadata_integration
from checkov.runner_filter import RunnerFilter
def get_checks(frameworks: Optional[List[str]] = None, use_bc_ids: bool = False,
include_all_checkov_policies: bool = True, filtered_policy_ids: Optional[List[str]] = None) -> List[Tuple[str, str, int, int, str, str]]: # type:ignore[arg-type]
def print_checks(frameworks: Optional[List[str]] = None, use_bc_ids: bool = False,
include_all_checkov_policies: bool = True, filtered_policy_ids: Optional[List[str]] = None) -> None:
framework_list = frameworks if frameworks else ["all"]
printable_checks_list = get_checks(framework_list, use_bc_ids=use_bc_ids,
include_all_checkov_policies=include_all_checkov_policies,
filtered_policy_ids=filtered_policy_ids or [])
print(
tabulate(printable_checks_list, headers=["Id", "Type", "Entity", "Policy", "IaC", "Resource Link"], tablefmt="github",
showindex=True))
print("\n\n---\n\n") | null |
2,234 | import ctypes
from datetime import datetime
import json
import logging
import os
import platform
import re
import stat
from pathlib import Path
from typing import Optional, List, Set, Union, Dict, Any, Tuple, cast
from cachetools import cached, TTLCache
from pydantic import ValidationError
from checkov.common.bridgecrew.check_type import CheckType
from checkov.common.bridgecrew.platform_integration import bc_integration
from checkov.common.bridgecrew.platform_key import bridgecrew_dir
from checkov.common.bridgecrew.severities import get_severity, Severity, Severities, BcSeverities
from checkov.common.models.enums import CheckResult
from checkov.common.output.report import Report
from checkov.common.sast.consts import CDKLanguages, SastLanguages
from checkov.common.sca.reachability.sast_contract.data_fetcher_sast_lib import SastReachabilityDataFetcher
from checkov.common.typing import _CheckResult
from checkov.common.util.http_utils import request_wrapper
from checkov.sast.checks_infra.base_registry import Registry
from checkov.sast.common import get_code_block_from_start
from checkov.sast.engines.base_engine import SastEngine
from checkov.sast.prisma_models.library_input import LibraryInput
from checkov.sast.prisma_models.policies_list import SastPolicies
from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX
from checkov.common.sast.report_types import PrismaReport, RuleMatch, create_empty_report
from checkov.sast.record import SastRecord
from checkov.sast.report import SastReport
from checkov.cdk.report import CDKReport
class SastLanguages(Enum):
def list(cls) -> List[Any]:
return list(map(lambda c: c.value, cls))
def set(cls) -> Set["SastLanguages"]:
return set(cls)
PYTHON = 'python'
JAVA = 'java'
JAVASCRIPT = 'javascript'
def validate_params(languages: Set[SastLanguages],
source_codes: List[str],
list_policies: bool) -> None:
if list_policies:
return
if len(source_codes) == 0:
raise Exception('must provide source code file or dir for sast runner')
if len(languages) == 0:
raise Exception('must provide a language for sast runner') | null |
2,235 | import ctypes
from datetime import datetime
import json
import logging
import os
import platform
import re
import stat
from pathlib import Path
from typing import Optional, List, Set, Union, Dict, Any, Tuple, cast
from cachetools import cached, TTLCache
from pydantic import ValidationError
from checkov.common.bridgecrew.check_type import CheckType
from checkov.common.bridgecrew.platform_integration import bc_integration
from checkov.common.bridgecrew.platform_key import bridgecrew_dir
from checkov.common.bridgecrew.severities import get_severity, Severity, Severities, BcSeverities
from checkov.common.models.enums import CheckResult
from checkov.common.output.report import Report
from checkov.common.sast.consts import CDKLanguages, SastLanguages
from checkov.common.sca.reachability.sast_contract.data_fetcher_sast_lib import SastReachabilityDataFetcher
from checkov.common.typing import _CheckResult
from checkov.common.util.http_utils import request_wrapper
from checkov.sast.checks_infra.base_registry import Registry
from checkov.sast.common import get_code_block_from_start
from checkov.sast.engines.base_engine import SastEngine
from checkov.sast.prisma_models.library_input import LibraryInput
from checkov.sast.prisma_models.policies_list import SastPolicies
from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX
from checkov.common.sast.report_types import PrismaReport, RuleMatch, create_empty_report
from checkov.sast.record import SastRecord
from checkov.sast.report import SastReport
from checkov.cdk.report import CDKReport
def get_machine() -> str:
machine = platform.machine().lower()
if machine in ['amd64', 'x86', 'x86_64', 'x64']:
return "amd64"
if machine in ['arm', 'arm64', 'armv8', 'aarch64', 'arm64-v8a']:
return 'arm64'
return '' | null |
2,236 | import ctypes
from datetime import datetime
import json
import logging
import os
import platform
import re
import stat
from pathlib import Path
from typing import Optional, List, Set, Union, Dict, Any, Tuple, cast
from cachetools import cached, TTLCache
from pydantic import ValidationError
from checkov.common.bridgecrew.check_type import CheckType
from checkov.common.bridgecrew.platform_integration import bc_integration
from checkov.common.bridgecrew.platform_key import bridgecrew_dir
from checkov.common.bridgecrew.severities import get_severity, Severity, Severities, BcSeverities
from checkov.common.models.enums import CheckResult
from checkov.common.output.report import Report
from checkov.common.sast.consts import CDKLanguages, SastLanguages
from checkov.common.sca.reachability.sast_contract.data_fetcher_sast_lib import SastReachabilityDataFetcher
from checkov.common.typing import _CheckResult
from checkov.common.util.http_utils import request_wrapper
from checkov.sast.checks_infra.base_registry import Registry
from checkov.sast.common import get_code_block_from_start
from checkov.sast.engines.base_engine import SastEngine
from checkov.sast.prisma_models.library_input import LibraryInput
from checkov.sast.prisma_models.policies_list import SastPolicies
from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX
from checkov.common.sast.report_types import PrismaReport, RuleMatch, create_empty_report
from checkov.sast.record import SastRecord
from checkov.sast.report import SastReport
from checkov.cdk.report import CDKReport
class SastReachabilityDataFetcher:
def __init__(self) -> None:
self.alias_mapping_creator = AliasMappingCreator()
self.reachability_run_config_raw: Union[Dict[str, Any], None] = None
self.reachability_run_config: Union[ReachabilityRunConfig, None] = None
def fetch(self, repository_name: str, repository_root_dir: str) -> Union[ReachabilityData, None]:
self.reachability_run_config_raw = bc_integration.get_reachability_run_config()
if not self.reachability_run_config_raw:
logging.error('reachability_run_config is null, unable to proceed', exc_info=True)
return None
try:
self.reachability_run_config = ReachabilityRunConfig(packageNamesForMapping=RELEVANT_PACKAGES)
except ValidationError:
logging.error('Unable to serialize reachability run_config', exc_info=True)
return None
try:
result = ReachabilityData(
aliasMapping=self._fetch_alias_mapping(repository_name=repository_name,
repository_root_dir=repository_root_dir,
relevant_packages=self.reachability_run_config.packageNamesForMapping)
)
except ValidationError:
logging.error('Unable to serialize reachability data', exc_info=True)
return None
return result
def _fetch_alias_mapping(self, repository_name: str, repository_root_dir: str, relevant_packages: Set[str]) -> Dict[str, Any]:
self.alias_mapping_creator.update_alias_mapping_for_repository(
repository_name=repository_name,
repository_root_dir=repository_root_dir,
relevant_packages=relevant_packages
)
res: Dict[str, Any] = self.alias_mapping_creator.get_alias_mapping()
asyncio.run(bc_integration.persist_reachability_alias_mapping(res))
return res
def get_reachability_data(repo_path: str) -> Dict[str, Any]:
fetcher = SastReachabilityDataFetcher()
reachability_data = fetcher.fetch(repository_name=repo_path, repository_root_dir=repo_path)
data: Dict[str, Any] = {}
if not reachability_data:
return data
langs = reachability_data.aliasMapping.get("languages")
if not langs:
return {}
for lang, lang_data in langs.items():
if lang == "nodejs":
lang = "javascript"
data[lang] = {"package_alias": {}}
for _, files in lang_data.get("repositories", {}).items():
for _, files_data in files.get("files", {}).items():
for original_package_name, package_alias in files_data.get("packageAliases", {}).items():
aliases = package_alias.get("packageAliases", [])
if aliases:
data[lang]["package_alias"][original_package_name] = aliases[0]
return data | null |
2,237 | from __future__ import annotations
from typing import List, Tuple
def cut_code_block_ident(code_block: List[Tuple[int, str]]) -> List[Tuple[int, str]]:
min_ident = len(code_block[0][1]) - len(code_block[0][1].lstrip())
for item in code_block[1:]:
current_min_ident = len(item[1]) - len(item[1].lstrip())
if current_min_ident < min_ident:
min_ident = current_min_ident
if min_ident == 0:
return code_block
code_block_cut_ident = []
for item in code_block:
code_block_cut_ident.append((item[0], item[1][min_ident:]))
return code_block_cut_ident
def get_code_block_from_start(lines: List[str], start: int) -> List[Tuple[int, str]]:
code_block = [(index, line) for index, line in enumerate(lines, start=start)]
return cut_code_block_ident(code_block) | null |
2,238 | from __future__ import annotations
import logging
import os
from typing import Type, Any, TYPE_CHECKING
from typing_extensions import TypeAlias
from checkov.common.checks_infra.registry import get_graph_checks_registry
from checkov.common.graph.checks_infra.registry import BaseRegistry
from checkov.common.typing import LibraryGraphConnector
from checkov.common.graph.graph_builder import CustomAttributes
from checkov.common.graph.graph_builder.consts import GraphSource
from checkov.common.images.image_referencer import ImageReferencerMixin
from checkov.common.output.extra_resource import ExtraResource
from checkov.common.output.record import Record
from checkov.common.output.report import Report, merge_reports
from checkov.common.bridgecrew.check_type import CheckType
from checkov.common.runners.base_runner import BaseRunner
from checkov.common.util.data_structures_utils import pickle_deepcopy
from checkov.kubernetes.checks.resource.registry import registry
from checkov.kubernetes.graph_builder.local_graph import KubernetesLocalGraph
from checkov.kubernetes.graph_manager import KubernetesGraphManager
from checkov.kubernetes.image_referencer.manager import KubernetesImageReferencerManager
from checkov.kubernetes.kubernetes_utils import (
create_definitions,
build_definitions_context,
get_skipped_checks,
get_resource_id,
K8_POSSIBLE_ENDINGS,
PARENT_RESOURCE_ID_KEY_NAME,
create_check_result,
)
from checkov.runner_filter import RunnerFilter
class TimeoutError(Exception):
pass
def handle_timeout(signum: int, frame: FrameType | None) -> Any:
raise TimeoutError('command got timeout') | null |
2,239 | from __future__ import annotations
import logging
import os
from typing import Type, Any, TYPE_CHECKING
from typing_extensions import TypeAlias
from checkov.common.checks_infra.registry import get_graph_checks_registry
from checkov.common.graph.checks_infra.registry import BaseRegistry
from checkov.common.typing import LibraryGraphConnector
from checkov.common.graph.graph_builder import CustomAttributes
from checkov.common.graph.graph_builder.consts import GraphSource
from checkov.common.images.image_referencer import ImageReferencerMixin
from checkov.common.output.extra_resource import ExtraResource
from checkov.common.output.record import Record
from checkov.common.output.report import Report, merge_reports
from checkov.common.bridgecrew.check_type import CheckType
from checkov.common.runners.base_runner import BaseRunner
from checkov.common.util.data_structures_utils import pickle_deepcopy
from checkov.kubernetes.checks.resource.registry import registry
from checkov.kubernetes.graph_builder.local_graph import KubernetesLocalGraph
from checkov.kubernetes.graph_manager import KubernetesGraphManager
from checkov.kubernetes.image_referencer.manager import KubernetesImageReferencerManager
from checkov.kubernetes.kubernetes_utils import (
create_definitions,
build_definitions_context,
get_skipped_checks,
get_resource_id,
K8_POSSIBLE_ENDINGS,
PARENT_RESOURCE_ID_KEY_NAME,
create_check_result,
)
from checkov.runner_filter import RunnerFilter
def get_relative_file_path(file_abs_path: str, root_folder: str | None) -> str:
return f"/{os.path.relpath(file_abs_path, root_folder)}" | null |
2,240 | from __future__ import annotations
import logging
import os
from typing import Type, Any, TYPE_CHECKING
from typing_extensions import TypeAlias
from checkov.common.checks_infra.registry import get_graph_checks_registry
from checkov.common.graph.checks_infra.registry import BaseRegistry
from checkov.common.typing import LibraryGraphConnector
from checkov.common.graph.graph_builder import CustomAttributes
from checkov.common.graph.graph_builder.consts import GraphSource
from checkov.common.images.image_referencer import ImageReferencerMixin
from checkov.common.output.extra_resource import ExtraResource
from checkov.common.output.record import Record
from checkov.common.output.report import Report, merge_reports
from checkov.common.bridgecrew.check_type import CheckType
from checkov.common.runners.base_runner import BaseRunner
from checkov.common.util.data_structures_utils import pickle_deepcopy
from checkov.kubernetes.checks.resource.registry import registry
from checkov.kubernetes.graph_builder.local_graph import KubernetesLocalGraph
from checkov.kubernetes.graph_manager import KubernetesGraphManager
from checkov.kubernetes.image_referencer.manager import KubernetesImageReferencerManager
from checkov.kubernetes.kubernetes_utils import (
create_definitions,
build_definitions_context,
get_skipped_checks,
get_resource_id,
K8_POSSIBLE_ENDINGS,
PARENT_RESOURCE_ID_KEY_NAME,
create_check_result,
)
from checkov.runner_filter import RunnerFilter
def _get_entity_abs_path(root_folder: str | None, entity_file_path: str) -> str:
if entity_file_path[0] == '/' and (root_folder and not entity_file_path.startswith(root_folder)):
path_to_convert = (root_folder + entity_file_path) if root_folder else entity_file_path
else:
path_to_convert = (os.path.join(root_folder, entity_file_path)) if root_folder else entity_file_path
return os.path.abspath(path_to_convert) | null |
2,241 | from __future__ import annotations
from typing import Any
def extract_commands(conf: dict[str, Any]) -> tuple[list[str], list[str]]:
commands = conf.get("command")
if not commands or not isinstance(commands, list):
return [], []
values = []
keys = []
for cmd in commands:
if cmd is None:
continue
if "=" in cmd:
key, value = cmd.split("=", maxsplit=1)
keys.append(key)
values.append(value)
else:
keys.append(cmd)
values.append(None)
return keys, values | null |
2,242 | from __future__ import annotations
import logging
import os
from typing import Dict, Any, TYPE_CHECKING
import dpath
from checkov.common.models.enums import CheckResult
from checkov.common.util.consts import LINE_FIELD_NAMES, START_LINE, END_LINE
from checkov.runner_filter import RunnerFilter
from checkov.common.bridgecrew.integration_features.features.policy_metadata_integration import integration as metadata_integration
from checkov.common.models.consts import YAML_COMMENT_MARK
from checkov.common.parallelizer.parallel_runner import parallel_runner
from checkov.common.runners.base_runner import filter_ignored_paths
from checkov.common.util.type_forcers import force_list
from checkov.kubernetes.parser.parser import parse
def get_folder_definitions(
root_folder: str, excluded_paths: list[str] | None
) -> tuple[dict[str, list[dict[str, Any]]], dict[str, list[tuple[int, str]]]]:
files_list = []
for root, d_names, f_names in os.walk(root_folder):
filter_ignored_paths(root, d_names, excluded_paths)
filter_ignored_paths(root, f_names, excluded_paths)
for file in f_names:
file_ending = os.path.splitext(file)[1]
if file_ending in K8_POSSIBLE_ENDINGS:
full_path = os.path.join(root, file)
if "/." not in full_path and file not in EXCLUDED_FILE_NAMES:
# skip temp directories
files_list.append(full_path)
return get_files_definitions(files_list)
def get_files_definitions(files: list[str]) -> tuple[dict[str, list[dict[str, Any]]], dict[str, list[tuple[int, str]]]]:
definitions = {}
definitions_raw = {}
results = parallel_runner.run_function(_parse_file, files)
for result in results:
if result:
path, parse_result = result
if parse_result:
definitions[path], definitions_raw[path] = parse_result
return definitions, definitions_raw
class RunnerFilter(object):
# NOTE: This needs to be static because different filters may be used at load time versus runtime
# (see note in BaseCheckRegistery.register). The concept of which checks are external is
# logically a "static" concept anyway, so this makes logical sense.
__EXTERNAL_CHECK_IDS: Set[str] = set()
def __init__(
self,
framework: Optional[List[str]] = None,
checks: Union[str, List[str], None] = None,
skip_checks: Union[str, List[str], None] = None,
include_all_checkov_policies: bool = True,
download_external_modules: bool = False,
external_modules_download_path: str = DEFAULT_EXTERNAL_MODULES_DIR,
evaluate_variables: bool = True,
runners: Optional[List[str]] = None,
skip_framework: Optional[List[str]] = None,
excluded_paths: Optional[List[str]] = None,
all_external: bool = False,
var_files: Optional[List[str]] = None,
skip_cve_package: Optional[List[str]] = None,
use_enforcement_rules: bool = False,
filtered_policy_ids: Optional[List[str]] = None,
show_progress_bar: Optional[bool] = True,
run_image_referencer: bool = False,
enable_secret_scan_all_files: bool = False,
block_list_secret_scan: Optional[List[str]] = None,
deep_analysis: bool = False,
repo_root_for_plan_enrichment: Optional[List[str]] = None,
resource_attr_to_omit: Optional[Dict[str, Set[str]]] = None,
enable_git_history_secret_scan: bool = False,
git_history_timeout: str = '12h',
git_history_last_commit_scanned: Optional[str] = None, # currently not exposed by a CLI flag
report_sast_imports: bool = False,
remove_default_sast_policies: bool = False,
report_sast_reachability: bool = False
) -> None:
checks = convert_csv_string_arg_to_list(checks)
skip_checks = convert_csv_string_arg_to_list(skip_checks)
self.skip_invalid_secrets = skip_checks and any(skip_check.capitalize() == ValidationStatus.INVALID.value
for skip_check in skip_checks)
self.use_enforcement_rules = use_enforcement_rules
self.enforcement_rule_configs: Dict[str, Severity | Dict[CodeCategoryType, Severity]] = {}
# we will store the lowest value severity we find in checks, and the highest value we find in skip-checks
# so the logic is "run all checks >= severity" and/or "skip all checks <= severity"
self.check_threshold = None
self.skip_check_threshold = None
self.checks = []
self.bc_cloned_checks: dict[str, list[dict[str, Any]]] = defaultdict(list)
self.skip_checks = []
self.skip_checks_regex_patterns = defaultdict(list)
self.show_progress_bar = show_progress_bar
# split out check/skip thresholds so we can access them easily later
for val in (checks or []):
if val.upper() in Severities:
val = val.upper()
if not self.check_threshold or self.check_threshold.level > Severities[val].level:
self.check_threshold = Severities[val]
else:
self.checks.append(val)
# Get regex patterns to split checks and remove it from skip checks:
updated_skip_checks = set(skip_checks)
for val in (skip_checks or []):
splitted_check = val.split(":")
# In case it's not expected pattern
if len(splitted_check) != 2:
continue
self.skip_checks_regex_patterns[splitted_check[0]].append(splitted_check[1])
updated_skip_checks -= {val}
skip_checks = list(updated_skip_checks)
for val in (skip_checks or []):
if val.upper() in Severities:
val = val.upper()
if not self.skip_check_threshold or self.skip_check_threshold.level < Severities[val].level:
self.skip_check_threshold = Severities[val]
else:
self.skip_checks.append(val)
self.include_all_checkov_policies = include_all_checkov_policies
if not framework or "all" in framework:
self.framework_flag_values = []
else:
self.framework_flag_values = framework
self.framework: "Iterable[str]" = framework if framework else ["all"]
if skip_framework:
if "all" in self.framework:
if runners is None:
runners = []
self.framework = set(runners) - set(skip_framework)
else:
self.framework = set(self.framework) - set(skip_framework)
logging.debug(f"Resultant set of frameworks (removing skipped frameworks): {','.join(self.framework)}")
self.download_external_modules = download_external_modules
self.external_modules_download_path = external_modules_download_path
self.evaluate_variables = evaluate_variables
self.excluded_paths = excluded_paths or []
self.all_external = all_external
self.var_files = var_files
self.skip_cve_package = skip_cve_package
self.filtered_policy_ids = filtered_policy_ids or []
self.run_image_referencer = run_image_referencer
self.enable_secret_scan_all_files = enable_secret_scan_all_files
self.block_list_secret_scan = block_list_secret_scan
self.suppressed_policies: List[str] = []
self.deep_analysis = deep_analysis
self.repo_root_for_plan_enrichment = repo_root_for_plan_enrichment
self.resource_attr_to_omit: DefaultDict[str, Set[str]] = RunnerFilter._load_resource_attr_to_omit(
resource_attr_to_omit
)
self.sast_languages: Set[SastLanguages] = RunnerFilter.get_sast_languages(framework, skip_framework)
if self.sast_languages and any(item for item in self.framework if item.startswith(CheckType.SAST) or item == 'all'):
self.framework = [item for item in self.framework if not item.startswith(CheckType.SAST)]
self.framework.append(CheckType.SAST)
elif not self.sast_languages:
# remove all SAST and CDK frameworks
self.framework = [
item for item in self.framework if not item.startswith(CheckType.SAST) and item != CheckType.CDK
]
self.enable_git_history_secret_scan: bool = enable_git_history_secret_scan
if self.enable_git_history_secret_scan:
self.git_history_timeout = convert_to_seconds(git_history_timeout)
self.framework = [CheckType.SECRETS]
logging.debug("Scan secrets history was enabled ignoring other frameworks")
self.git_history_last_commit_scanned = git_history_last_commit_scanned
self.report_sast_imports = report_sast_imports
self.remove_default_sast_policies = remove_default_sast_policies
self.report_sast_reachability = report_sast_reachability
def _load_resource_attr_to_omit(resource_attr_to_omit_input: Optional[Dict[str, Set[str]]]) -> DefaultDict[str, Set[str]]:
resource_attributes_to_omit: DefaultDict[str, Set[str]] = defaultdict(set)
# In order to create new object (and not a reference to the given one)
if resource_attr_to_omit_input:
resource_attributes_to_omit.update(resource_attr_to_omit_input)
return resource_attributes_to_omit
def apply_enforcement_rules(self, enforcement_rule_configs: Dict[str, CodeCategoryConfiguration]) -> None:
self.enforcement_rule_configs = {}
for report_type, code_category in CodeCategoryMapping.items():
if isinstance(code_category, list):
self.enforcement_rule_configs[report_type] = {c: enforcement_rule_configs.get(c).soft_fail_threshold for c in code_category} # type:ignore[union-attr] # will not be None
else:
config = enforcement_rule_configs.get(code_category)
if not config:
raise Exception(f'Could not find an enforcement rule config for category {code_category} (runner: {report_type})')
self.enforcement_rule_configs[report_type] = config.soft_fail_threshold
def extract_enforcement_rule_threshold(self, check_id: str, report_type: str) -> Severity:
if 'sca_' in report_type and '_LIC_' in check_id:
return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.LICENSES]
elif 'sca_' in report_type: # vulnerability
return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.VULNERABILITIES]
else:
return cast(Severity, self.enforcement_rule_configs[report_type])
def should_run_check(
self,
check: BaseCheck | BaseGraphCheck | BaseSastCheck | None = None,
check_id: str | None = None,
bc_check_id: str | None = None,
severity: Severity | None = None,
report_type: str | None = None,
file_origin_paths: List[str] | None = None,
root_folder: str | None = None
) -> bool:
if check:
check_id = check.id
bc_check_id = check.bc_id
severity = check.severity
assert check_id is not None # nosec (for mypy (and then for bandit))
check_threshold: Optional[Severity]
skip_check_threshold: Optional[Severity]
# apply enforcement rules if specified, but let --check/--skip-check with a severity take priority
if self.use_enforcement_rules and report_type:
if not self.check_threshold and not self.skip_check_threshold:
check_threshold = self.extract_enforcement_rule_threshold(check_id, report_type)
skip_check_threshold = None
else:
check_threshold = self.check_threshold
skip_check_threshold = self.skip_check_threshold
else:
if self.use_enforcement_rules:
# this is a warning for us (but there is nothing the user can do about it)
logging.debug(f'Use enforcement rules is true, but check {check_id} was not passed to the runner filter with a report type')
check_threshold = self.check_threshold
skip_check_threshold = self.skip_check_threshold
run_severity = severity and check_threshold and severity.level >= check_threshold.level
explicit_run = self.checks and self.check_matches(check_id, bc_check_id, self.checks)
implicit_run = not self.checks and not check_threshold
is_external = RunnerFilter.is_external_check(check_id)
is_policy_filtered = self.is_policy_filtered(check_id)
# True if this check is present in the allow list, or if there is no allow list
# this is not necessarily the return value (need to apply other filters)
should_run_check = (
run_severity or
explicit_run or
implicit_run or
(is_external and self.all_external)
)
if not should_run_check:
logging.debug(f'Should run check {check_id}: False')
return False
# If a policy is not present in the list of filtered policies, it should not be run - implicitly or explicitly.
# It can, however, be skipped.
if not is_policy_filtered:
logging.debug(f'not is_policy_filtered {check_id}: should_run_check = False')
should_run_check = False
skip_severity = severity and skip_check_threshold and severity.level <= skip_check_threshold.level
explicit_skip = self.skip_checks and self.check_matches(check_id, bc_check_id, self.skip_checks)
regex_match = self._match_regex_pattern(check_id, file_origin_paths, root_folder)
should_skip_check = (
skip_severity or
explicit_skip or
regex_match or
(not bc_check_id and not self.include_all_checkov_policies and not is_external and not explicit_run) or
(bc_check_id in self.suppressed_policies and bc_check_id not in self.bc_cloned_checks)
)
logging.debug(f'skip_severity = {skip_severity}, explicit_skip = {explicit_skip}, regex_match = {regex_match}, suppressed_policies: {self.suppressed_policies}')
logging.debug(
f'bc_check_id = {bc_check_id}, include_all_checkov_policies = {self.include_all_checkov_policies}, is_external = {is_external}, explicit_run: {explicit_run}')
if should_skip_check:
result = False
logging.debug(f'should_skip_check {check_id}: {should_skip_check}')
elif should_run_check:
result = True
logging.debug(f'should_run_check {check_id}: {result}')
else:
result = False
logging.debug(f'default {check_id}: {result}')
return result
def _match_regex_pattern(self, check_id: str, file_origin_paths: List[str] | None, root_folder: str | None) -> bool:
"""
Check if skip check_id for a certain file_types, according to given path pattern
"""
if not file_origin_paths:
return False
regex_patterns = self.skip_checks_regex_patterns.get(check_id, [])
# In case skip is generic, for example, CKV_AZURE_*.
generic_check_id = f"{'_'.join(i for i in check_id.split('_')[:-1])}_*"
generic_check_regex_patterns = self.skip_checks_regex_patterns.get(generic_check_id, [])
regex_patterns.extend(generic_check_regex_patterns)
if not regex_patterns:
return False
for pattern in regex_patterns:
if not pattern:
continue
full_regex_pattern = fr"^{root_folder}/{pattern}" if root_folder else pattern
try:
if any(re.search(full_regex_pattern, path) for path in file_origin_paths):
return True
except Exception as exc:
logging.error(
"Invalid regex pattern has been supplied",
extra={"regex_pattern": pattern, "exc": str(exc)}
)
return False
def check_matches(check_id: str,
bc_check_id: Optional[str],
pattern_list: List[str]) -> bool:
return any(
(fnmatch.fnmatch(check_id, pattern) or (bc_check_id and fnmatch.fnmatch(bc_check_id, pattern))) for pattern
in pattern_list)
def within_threshold(self, severity: Severity) -> bool:
above_min = (not self.check_threshold) or self.check_threshold.level <= severity.level
below_max = self.skip_check_threshold and self.skip_check_threshold.level >= severity.level
return above_min and not below_max
def secret_validation_status_matches(secret_validation_status: str, statuses_list: list[str]) -> bool:
return secret_validation_status in statuses_list
def notify_external_check(check_id: str) -> None:
RunnerFilter.__EXTERNAL_CHECK_IDS.add(check_id)
def is_external_check(check_id: str) -> bool:
return check_id in RunnerFilter.__EXTERNAL_CHECK_IDS
def is_policy_filtered(self, check_id: str) -> bool:
if not self.filtered_policy_ids:
return True
return check_id in self.filtered_policy_ids
def to_dict(self) -> Dict[str, Any]:
result: Dict[str, Any] = {}
for key, value in self.__dict__.items():
result[key] = value
return result
def from_dict(obj: Dict[str, Any]) -> RunnerFilter:
framework = obj.get('framework')
checks = obj.get('checks')
skip_checks = obj.get('skip_checks')
include_all_checkov_policies = obj.get('include_all_checkov_policies')
if include_all_checkov_policies is None:
include_all_checkov_policies = True
download_external_modules = obj.get('download_external_modules')
if download_external_modules is None:
download_external_modules = False
external_modules_download_path = obj.get('external_modules_download_path')
if external_modules_download_path is None:
external_modules_download_path = DEFAULT_EXTERNAL_MODULES_DIR
evaluate_variables = obj.get('evaluate_variables')
if evaluate_variables is None:
evaluate_variables = True
runners = obj.get('runners')
skip_framework = obj.get('skip_framework')
excluded_paths = obj.get('excluded_paths')
all_external = obj.get('all_external')
if all_external is None:
all_external = False
var_files = obj.get('var_files')
skip_cve_package = obj.get('skip_cve_package')
use_enforcement_rules = obj.get('use_enforcement_rules')
if use_enforcement_rules is None:
use_enforcement_rules = False
filtered_policy_ids = obj.get('filtered_policy_ids')
show_progress_bar = obj.get('show_progress_bar')
if show_progress_bar is None:
show_progress_bar = True
run_image_referencer = obj.get('run_image_referencer')
if run_image_referencer is None:
run_image_referencer = False
enable_secret_scan_all_files = bool(obj.get('enable_secret_scan_all_files'))
block_list_secret_scan = obj.get('block_list_secret_scan')
runner_filter = RunnerFilter(framework, checks, skip_checks, include_all_checkov_policies,
download_external_modules, external_modules_download_path, evaluate_variables,
runners, skip_framework, excluded_paths, all_external, var_files,
skip_cve_package, use_enforcement_rules, filtered_policy_ids, show_progress_bar,
run_image_referencer, enable_secret_scan_all_files, block_list_secret_scan)
return runner_filter
def set_suppressed_policies(self, policy_level_suppressions: List[str]) -> None:
logging.debug(f"Received the following policy-level suppressions, that will be skipped from running: {policy_level_suppressions}")
self.suppressed_policies = policy_level_suppressions
def get_sast_languages(frameworks: Optional[List[str]], skip_framework: Optional[List[str]]) -> Set[SastLanguages]:
langs: Set[SastLanguages] = set()
if not frameworks or (skip_framework and "sast" in skip_framework):
return langs
if 'all' in frameworks:
sast_languages = SastLanguages.set()
skip_framework = [] if not skip_framework else [f.split("sast_")[-1] for f in skip_framework]
return set([lang for lang in sast_languages if lang.value not in skip_framework])
for framework in frameworks:
if framework in [CheckType.SAST, CheckType.CDK]:
for sast_lang in SastLanguages:
langs.add(sast_lang)
return langs
if not framework.startswith(CheckType.SAST):
continue
lang = '_'.join(framework.split('_')[1:])
langs.add(SastLanguages[lang.upper()])
return langs
def create_definitions(
root_folder: str | None,
files: list[str] | None = None,
runner_filter: RunnerFilter | None = None,
) -> tuple[dict[str, list[dict[str, Any]]], dict[str, list[tuple[int, str]]]]:
runner_filter = runner_filter or RunnerFilter()
definitions: dict[str, list[dict[str, Any]]] = {}
definitions_raw: dict[str, list[tuple[int, str]]] = {}
if files:
definitions, definitions_raw = get_files_definitions(files)
if root_folder:
definitions, definitions_raw = get_folder_definitions(root_folder, runner_filter.excluded_paths)
return definitions, definitions_raw | null |
2,243 | from __future__ import annotations
import logging
import os
from typing import Dict, Any, TYPE_CHECKING
import dpath
from checkov.common.models.enums import CheckResult
from checkov.common.util.consts import LINE_FIELD_NAMES, START_LINE, END_LINE
from checkov.runner_filter import RunnerFilter
from checkov.common.bridgecrew.integration_features.features.policy_metadata_integration import integration as metadata_integration
from checkov.common.models.consts import YAML_COMMENT_MARK
from checkov.common.parallelizer.parallel_runner import parallel_runner
from checkov.common.runners.base_runner import filter_ignored_paths
from checkov.common.util.type_forcers import force_list
from checkov.kubernetes.parser.parser import parse
def get_skipped_checks(entity_conf: dict[str, Any]) -> list[_SkippedCheck]:
def calculate_code_lines(raw_code: list[tuple[int, str]], start_line: int, end_line: int) \
-> tuple[list[tuple[int, str]], int, int]:
def is_invalid_k8_definition(definition: Dict[str, Any]) -> bool:
def get_resource_id(resource: dict[str, Any] | None) -> str | None:
START_LINE = '__startline__'
END_LINE = '__endline__'
def build_definitions_context(
definitions: dict[str, list[dict[str, Any]]], definitions_raw: dict[str, list[tuple[int, str]]]
) -> dict[str, dict[str, Any]]:
definitions_context: Dict[str, Dict[str, Any]] = {}
# iterate on the files
for file_path, resources in definitions.items():
for resource in resources[:]:
if resource.get("kind") == "List":
# this could be inefficient, if more than one 'List' object exists in the same file
resources = resources[:]
resources.extend(item for item in resource.get("items", []) if item)
resources.remove(resource)
# iterate on the resources
for resource in resources:
if is_invalid_k8_definition(resource):
continue
resource_id = get_resource_id(resource)
if not resource_id:
continue
relative_resource_path = None
if 'metadata' in resource:
metadata = resource['metadata']
if 'annotations' in metadata and metadata['annotations'] is not None\
and 'config.kubernetes.io/origin' in metadata['annotations']:
metadata_path = metadata['annotations']['config.kubernetes.io/origin']
if 'path:' in metadata_path:
relative_resource_path = metadata_path.split('path:')[1].strip()
resource_start_line = resource[START_LINE]
resource_end_line = min(resource[END_LINE], len(definitions_raw[file_path]))
raw_code = definitions_raw[file_path]
code_lines, start_line, end_line = calculate_code_lines(raw_code, resource_start_line, resource_end_line)
dpath.new(
definitions_context,
[file_path, resource_id],
{"start_line": start_line, "end_line": end_line, "code_lines": code_lines,
"origin_relative_path": relative_resource_path},
)
skipped_checks = get_skipped_checks(resource)
dpath.new(
definitions_context,
[file_path, resource_id, "skipped_checks"],
skipped_checks,
)
return definitions_context | null |
2,244 | from __future__ import annotations
import logging
import os
from typing import Dict, Any, TYPE_CHECKING
import dpath
from checkov.common.models.enums import CheckResult
from checkov.common.util.consts import LINE_FIELD_NAMES, START_LINE, END_LINE
from checkov.runner_filter import RunnerFilter
from checkov.common.bridgecrew.integration_features.features.policy_metadata_integration import integration as metadata_integration
from checkov.common.models.consts import YAML_COMMENT_MARK
from checkov.common.parallelizer.parallel_runner import parallel_runner
from checkov.common.runners.base_runner import filter_ignored_paths
from checkov.common.util.type_forcers import force_list
from checkov.kubernetes.parser.parser import parse
def is_invalid_k8_pod_definition(definition: Dict[str, Any]) -> bool:
if not isinstance(definition, dict):
return True
metadata = definition.get('metadata')
if not isinstance(metadata, dict):
return True
spec = definition.get('spec')
if not isinstance(spec, dict) and not isinstance(spec, list):
return True
labels = metadata.get('labels')
name = metadata.get('name')
if name is None and labels is None:
return True
return False | null |
2,245 | from __future__ import annotations
import logging
import os
from typing import Dict, Any, TYPE_CHECKING
import dpath
from checkov.common.models.enums import CheckResult
from checkov.common.util.consts import LINE_FIELD_NAMES, START_LINE, END_LINE
from checkov.runner_filter import RunnerFilter
from checkov.common.bridgecrew.integration_features.features.policy_metadata_integration import integration as metadata_integration
from checkov.common.models.consts import YAML_COMMENT_MARK
from checkov.common.parallelizer.parallel_runner import parallel_runner
from checkov.common.runners.base_runner import filter_ignored_paths
from checkov.common.util.type_forcers import force_list
from checkov.kubernetes.parser.parser import parse
def remove_metadata_from_attribute(attribute: dict[str, Any] | None) -> None:
if isinstance(attribute, dict):
attribute.pop("__startline__", None)
attribute.pop("__endline__", None) | null |
2,246 | from __future__ import annotations
import logging
import os
from typing import Dict, Any, TYPE_CHECKING
import dpath
from checkov.common.models.enums import CheckResult
from checkov.common.util.consts import LINE_FIELD_NAMES, START_LINE, END_LINE
from checkov.runner_filter import RunnerFilter
from checkov.common.bridgecrew.integration_features.features.policy_metadata_integration import integration as metadata_integration
from checkov.common.models.consts import YAML_COMMENT_MARK
from checkov.common.parallelizer.parallel_runner import parallel_runner
from checkov.common.runners.base_runner import filter_ignored_paths
from checkov.common.util.type_forcers import force_list
from checkov.kubernetes.parser.parser import parse
class CheckResult(str, Enum):
PASSED = "PASSED"
FAILED = "FAILED"
# Unknown should be used when a check does not wish to return a result, generally due to the inability
# to resolve a value or similar types of errors.
UNKNOWN = "UNKNOWN"
# Skipped is used by the framework when a test is suppressed and should not be used directly by checks.
SKIPPED = "SKIPPED"
class _CheckResult(TypedDict, total=False):
result: Union["CheckResult", Tuple["CheckResult", dict[str, Any]]]
suppress_comment: str
evaluated_keys: list[str]
results_configuration: dict[str, Any] | None
check: BaseCheck
entity: dict[str, Any] # only exists for graph results
class _EntityContext(TypedDict, total=False):
start_line: int
end_line: int
policy: str
code_lines: list[tuple[int, str]]
skipped_checks: list[_SkippedCheck]
origin_relative_path: str
The provided code snippet includes necessary dependencies for implementing the `create_check_result` function. Write a Python function `def create_check_result(check_result: _CheckResult, entity_context: _EntityContext, check_id: str) -> _CheckResult` to solve the following problem:
Creates a cleaned version of check_result for further usage
Here is the function:
def create_check_result(check_result: _CheckResult, entity_context: _EntityContext, check_id: str) -> _CheckResult:
"""Creates a cleaned version of check_result for further usage"""
clean_check_result: _CheckResult = {
"result": check_result["result"],
"evaluated_keys": check_result["evaluated_keys"],
}
for skipped_check in entity_context.get("skipped_checks", []):
if skipped_check["id"] == check_id:
clean_check_result["result"] = CheckResult.SKIPPED
clean_check_result["suppress_comment"] = skipped_check["suppress_comment"]
break
return clean_check_result | Creates a cleaned version of check_result for further usage |
2,247 | from __future__ import annotations
from typing import TYPE_CHECKING, Any
from checkov.common.util.data_structures_utils import find_in_dict
from checkov.kubernetes.image_referencer.base_provider import BaseKubernetesProvider
def _extract_images_from_spec(spec: dict[str, Any] | None) -> list[str]:
image_names: set[str] = set()
if isinstance(spec, dict):
containers = spec.get("containers")
image_names.update(extract_images_from_containers(containers=containers))
containers = spec.get("initContainers")
image_names.update(extract_images_from_containers(containers=containers))
# Makes sure we return no duplications
return list(image_names)
def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any:
"""Tries to retrieve the value under the given 'key_path', otherwise returns None."""
value: Any = input_dict
key_list = key_path.split("/")
try:
for key in key_list:
if key.startswith("[") and key.endswith("]"):
if isinstance(value, list):
idx = int(key[1:-1])
value = value[idx]
continue
else:
return None
value = value.get(key)
if value is None:
return None
except (AttributeError, IndexError, KeyError, TypeError, ValueError):
logging.debug(f"Could not find {key_path} in dict")
return None
return value
def extract_images_from_cron_job(resource: dict[str, Any]) -> list[str]:
spec = find_in_dict(input_dict=resource, key_path="spec/jobTemplate/spec/template/spec")
return _extract_images_from_spec(spec) | null |
2,248 | from __future__ import annotations
from typing import TYPE_CHECKING, Any
from checkov.common.util.data_structures_utils import find_in_dict
from checkov.kubernetes.image_referencer.base_provider import BaseKubernetesProvider
def _extract_images_from_spec(spec: dict[str, Any] | None) -> list[str]:
image_names: set[str] = set()
if isinstance(spec, dict):
containers = spec.get("containers")
image_names.update(extract_images_from_containers(containers=containers))
containers = spec.get("initContainers")
image_names.update(extract_images_from_containers(containers=containers))
# Makes sure we return no duplications
return list(image_names)
def extract_images_from_pod(resource: dict[str, Any]) -> list[str]:
spec = resource.get("spec")
return _extract_images_from_spec(spec) | null |
2,249 | from __future__ import annotations
from typing import TYPE_CHECKING, Any
from checkov.common.util.data_structures_utils import find_in_dict
from checkov.kubernetes.image_referencer.base_provider import BaseKubernetesProvider
def _extract_images_from_spec(spec: dict[str, Any] | None) -> list[str]:
def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any:
def extract_images_from_pod_template(resource: dict[str, Any]) -> list[str]:
# the 'PodTemplate' object is usually not defined by the user, but rather used by Kubernetes internally
spec = find_in_dict(input_dict=resource, key_path="template/spec")
return _extract_images_from_spec(spec) | null |
2,250 | from __future__ import annotations
from typing import TYPE_CHECKING, Any
from checkov.common.util.data_structures_utils import find_in_dict
from checkov.kubernetes.image_referencer.base_provider import BaseKubernetesProvider
def _extract_images_from_spec(spec: dict[str, Any] | None) -> list[str]:
image_names: set[str] = set()
if isinstance(spec, dict):
containers = spec.get("containers")
image_names.update(extract_images_from_containers(containers=containers))
containers = spec.get("initContainers")
image_names.update(extract_images_from_containers(containers=containers))
# Makes sure we return no duplications
return list(image_names)
def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any:
"""Tries to retrieve the value under the given 'key_path', otherwise returns None."""
value: Any = input_dict
key_list = key_path.split("/")
try:
for key in key_list:
if key.startswith("[") and key.endswith("]"):
if isinstance(value, list):
idx = int(key[1:-1])
value = value[idx]
continue
else:
return None
value = value.get(key)
if value is None:
return None
except (AttributeError, IndexError, KeyError, TypeError, ValueError):
logging.debug(f"Could not find {key_path} in dict")
return None
return value
def extract_images_from_template(resource: dict[str, Any]) -> list[str]:
spec = find_in_dict(input_dict=resource, key_path="spec/template/spec")
return _extract_images_from_spec(spec) | null |
2,251 | from __future__ import annotations
from pathlib import Path
from typing import cast, List, Tuple, Dict, Any, TYPE_CHECKING
from checkov.common.util.suppression import collect_suppressions_for_report
BICEP_COMMENT = "//"
DEFINITIONS_KEYS_TO_PARSE = {"parameters": "parameters", "resources": "resources"}
def collect_suppressions_for_report(code_lines: list[tuple[int, str]]) -> dict[str, _CheckResult]:
"""Searches for suppressions in a config block to be used in a report"""
suppressions = {}
for _, line in code_lines:
skip_search = re.search(COMMENT_REGEX, line)
if skip_search:
check_result: _CheckResult = {
"result": CheckResult.SKIPPED,
"suppress_comment": skip_search.group(3)[1:] if skip_search.group(3) else "No comment provided",
}
suppressions[skip_search.group(2)] = check_result
return suppressions
def build_definitions_context(definitions: Dict[Path, BicepJson], definitions_raw: Dict[Path, List[Tuple[int, str]]]
) -> Dict[str, Dict[str, Any]]:
definitions_context: Dict[str, Dict[str, Any]] = {}
for file_path_object, file_path_definitions in definitions.items():
file_path = str(file_path_object)
definitions_context[file_path] = {}
for definition_attribute, resources in file_path_definitions.items():
if definition_attribute not in DEFINITIONS_KEYS_TO_PARSE.values():
continue
definitions_context[file_path][definition_attribute] = {}
# ignore mypy mismatched type warning since it can't resolve this type correctly
for resource_key, resource_attributes in resources.items(): # type:ignore[attr-defined]
definition_resource = {"start_line": resource_attributes["__start_line__"], "end_line": resource_attributes["__end_line__"]}
if definition_attribute == DEFINITIONS_KEYS_TO_PARSE["resources"]:
definition_key = f"{resource_attributes['type']}.{resource_key}"
int_start_line = cast(int, definition_resource["start_line"])
int_end_line = cast(int, definition_resource["end_line"])
code_lines_for_suppressions_check = definitions_raw[file_path_object][int_start_line: int_end_line]
definition_resource['skipped_checks'] = collect_suppressions_for_report(code_lines=code_lines_for_suppressions_check)
elif definition_attribute == DEFINITIONS_KEYS_TO_PARSE["parameters"]:
definition_key = resource_key
definition_resource["type"] = resource_attributes['type']
start_line = resource_attributes["__start_line__"]
end_line = resource_attributes["__end_line__"]
# add resource comments to definition lines
current_line = str.strip(definitions_raw[file_path_object][start_line - 1][1])
while not current_line or current_line[0] == BICEP_COMMENT:
start_line -= 1
current_line = str.strip(definitions_raw[file_path_object][start_line - 1][1])
# remove next resource comments from definition lines
current_line = str.strip(definitions_raw[file_path_object][end_line - 1][1])
while not current_line or current_line[0] == BICEP_COMMENT:
end_line -= 1
current_line = str.strip(definitions_raw[file_path_object][end_line - 1][1])
definition_resource["code_lines"] = definitions_raw[file_path_object][start_line - 1: end_line]
definitions_context[file_path][definition_attribute][definition_key] = definition_resource
return definitions_context | null |
2,252 | from __future__ import annotations
import os
from pathlib import Path
from typing import Any, TYPE_CHECKING, cast
from checkov.bicep.graph_builder.graph_components.block_types import BlockType, BlockTypeAlias
from checkov.bicep.graph_builder.local_graph import BicepElements, BicepElementsAlias
BLOCK_TYPE_TO_BICEP_ELEMENTS_MAP = {
BlockType.MODULE: BicepElements.MODULES,
BlockType.OUTPUT: BicepElements.OUTPUTS,
BlockType.PARAM: BicepElements.PARAMETERS,
BlockType.RESOURCE: BicepElements.RESOURCES,
BlockType.TARGET_SCOPE: BicepElements.GLOBALS,
BlockType.VAR: BicepElements.VARIABLES,
}
def add_breadcrumbs(vertex: BicepBlock, breadcrumbs: dict[str, dict[str, Any]], relative_block_path: str) -> None:
breadcrumbs.setdefault(relative_block_path, {})[vertex.name] = vertex.breadcrumbs
class BlockType(CommonBlockType):
TARGET_SCOPE: Literal["targetScope"] = "targetScope"
PARAM: Literal["param"] = "param"
VAR: Literal["var"] = "var"
MODULE: Literal["module"] = "module"
OUTPUT: Literal["output"] = "output"
BicepElementsAlias: TypeAlias = Literal["globals", "parameters", "variables", "resources", "modules", "outputs"]
class BicepBlock(Block):
def __init__(
self,
name: str,
config: dict[str, Any],
path: str,
block_type: str,
attributes: dict[str, Any],
id: str = "",
) -> None:
super().__init__(name, config, path, block_type, attributes, id, GraphSource.BICEP)
def convert_graph_vertices_to_tf_definitions(
vertices: list[BicepBlock], root_folder: str | Path | None
) -> tuple[dict[Path, BicepJson], dict[str, dict[str, Any]]]:
tf_definitions: dict[Path, BicepJson] = {}
breadcrumbs: dict[str, dict[str, Any]] = {}
for vertex in vertices:
block_path = Path(vertex.path)
# in theory block_type could be any string, but not in a Bicep Graph
block_type = cast("BlockTypeAlias", vertex.block_type)
bicep_element: BicepElementsAlias = BLOCK_TYPE_TO_BICEP_ELEMENTS_MAP[block_type].value
element_name = vertex.name
if block_type == BlockType.TARGET_SCOPE:
element_name = "scope"
tf_definitions.setdefault(block_path, {}).setdefault(bicep_element, {})[element_name] = vertex.config # type:ignore[typeddict-item]
if vertex.breadcrumbs:
relative_block_path = f"/{os.path.relpath(block_path, root_folder)}"
add_breadcrumbs(vertex, breadcrumbs, relative_block_path)
return tf_definitions, breadcrumbs | null |
2,253 | from __future__ import annotations
import logging
import os
import re
from collections.abc import Collection
from pathlib import Path
from typing import Any, TYPE_CHECKING
from checkov.common.runners.base_runner import filter_ignored_paths
from checkov.runner_filter import RunnerFilter
from checkov.bicep.parser import Parser
The provided code snippet includes necessary dependencies for implementing the `get_scannable_file_paths` function. Write a Python function `def get_scannable_file_paths( root_folder: str | Path | None = None, files: list[str] | None = None, excluded_paths: list[str] | None = None ) -> set[Path]` to solve the following problem:
Finds Bicep files
Here is the function:
def get_scannable_file_paths(
root_folder: str | Path | None = None, files: list[str] | None = None, excluded_paths: list[str] | None = None
) -> set[Path]:
"""Finds Bicep files"""
file_paths: set[Path] = set()
if root_folder:
root_path = Path(root_folder)
file_paths = {file_path for file_path in root_path.rglob("*.bicep") if file_path.is_file()}
if excluded_paths:
compiled = [re.compile(p.replace(".terraform", r"\.terraform")) for p in excluded_paths]
file_paths = {
file_path for file_path in file_paths if not any(pattern.search(str(file_path)) for pattern in compiled)
}
if files:
for file in files:
if file.endswith(".bicep"):
file_paths.add(Path(file))
return file_paths | Finds Bicep files |
2,254 | from __future__ import annotations
import logging
import os
import re
from collections.abc import Collection
from pathlib import Path
from typing import Any, TYPE_CHECKING
from checkov.common.runners.base_runner import filter_ignored_paths
from checkov.runner_filter import RunnerFilter
from checkov.bicep.parser import Parser
def clean_file_path(file_path: Path) -> Path:
path_parts = [part for part in file_path.parts if part not in (".", "..")]
return Path(*path_parts) | null |
2,255 | from __future__ import annotations
import logging
import os
import re
from collections.abc import Collection
from pathlib import Path
from typing import Any, TYPE_CHECKING
from checkov.common.runners.base_runner import filter_ignored_paths
from checkov.runner_filter import RunnerFilter
from checkov.bicep.parser import Parser
def get_folder_definitions(
root_folder: str, excluded_paths: list[str] | None
) -> tuple[dict[Path, BicepJson], dict[Path, list[tuple[int, str]]], list[str]]:
files_list: set[Path] = set()
for root, d_names, f_names in os.walk(root_folder):
filter_ignored_paths(root, d_names, excluded_paths)
filter_ignored_paths(root, f_names, excluded_paths)
for file in f_names:
file_ending = os.path.splitext(file)[1]
if file_ending in BICEP_POSSIBLE_ENDINGS:
full_path = os.path.join(root, file)
files_list.add(Path(full_path))
parser = Parser()
return parser.get_files_definitions(files_list)
class RunnerFilter(object):
# NOTE: This needs to be static because different filters may be used at load time versus runtime
# (see note in BaseCheckRegistery.register). The concept of which checks are external is
# logically a "static" concept anyway, so this makes logical sense.
__EXTERNAL_CHECK_IDS: Set[str] = set()
def __init__(
self,
framework: Optional[List[str]] = None,
checks: Union[str, List[str], None] = None,
skip_checks: Union[str, List[str], None] = None,
include_all_checkov_policies: bool = True,
download_external_modules: bool = False,
external_modules_download_path: str = DEFAULT_EXTERNAL_MODULES_DIR,
evaluate_variables: bool = True,
runners: Optional[List[str]] = None,
skip_framework: Optional[List[str]] = None,
excluded_paths: Optional[List[str]] = None,
all_external: bool = False,
var_files: Optional[List[str]] = None,
skip_cve_package: Optional[List[str]] = None,
use_enforcement_rules: bool = False,
filtered_policy_ids: Optional[List[str]] = None,
show_progress_bar: Optional[bool] = True,
run_image_referencer: bool = False,
enable_secret_scan_all_files: bool = False,
block_list_secret_scan: Optional[List[str]] = None,
deep_analysis: bool = False,
repo_root_for_plan_enrichment: Optional[List[str]] = None,
resource_attr_to_omit: Optional[Dict[str, Set[str]]] = None,
enable_git_history_secret_scan: bool = False,
git_history_timeout: str = '12h',
git_history_last_commit_scanned: Optional[str] = None, # currently not exposed by a CLI flag
report_sast_imports: bool = False,
remove_default_sast_policies: bool = False,
report_sast_reachability: bool = False
) -> None:
checks = convert_csv_string_arg_to_list(checks)
skip_checks = convert_csv_string_arg_to_list(skip_checks)
self.skip_invalid_secrets = skip_checks and any(skip_check.capitalize() == ValidationStatus.INVALID.value
for skip_check in skip_checks)
self.use_enforcement_rules = use_enforcement_rules
self.enforcement_rule_configs: Dict[str, Severity | Dict[CodeCategoryType, Severity]] = {}
# we will store the lowest value severity we find in checks, and the highest value we find in skip-checks
# so the logic is "run all checks >= severity" and/or "skip all checks <= severity"
self.check_threshold = None
self.skip_check_threshold = None
self.checks = []
self.bc_cloned_checks: dict[str, list[dict[str, Any]]] = defaultdict(list)
self.skip_checks = []
self.skip_checks_regex_patterns = defaultdict(list)
self.show_progress_bar = show_progress_bar
# split out check/skip thresholds so we can access them easily later
for val in (checks or []):
if val.upper() in Severities:
val = val.upper()
if not self.check_threshold or self.check_threshold.level > Severities[val].level:
self.check_threshold = Severities[val]
else:
self.checks.append(val)
# Get regex patterns to split checks and remove it from skip checks:
updated_skip_checks = set(skip_checks)
for val in (skip_checks or []):
splitted_check = val.split(":")
# In case it's not expected pattern
if len(splitted_check) != 2:
continue
self.skip_checks_regex_patterns[splitted_check[0]].append(splitted_check[1])
updated_skip_checks -= {val}
skip_checks = list(updated_skip_checks)
for val in (skip_checks or []):
if val.upper() in Severities:
val = val.upper()
if not self.skip_check_threshold or self.skip_check_threshold.level < Severities[val].level:
self.skip_check_threshold = Severities[val]
else:
self.skip_checks.append(val)
self.include_all_checkov_policies = include_all_checkov_policies
if not framework or "all" in framework:
self.framework_flag_values = []
else:
self.framework_flag_values = framework
self.framework: "Iterable[str]" = framework if framework else ["all"]
if skip_framework:
if "all" in self.framework:
if runners is None:
runners = []
self.framework = set(runners) - set(skip_framework)
else:
self.framework = set(self.framework) - set(skip_framework)
logging.debug(f"Resultant set of frameworks (removing skipped frameworks): {','.join(self.framework)}")
self.download_external_modules = download_external_modules
self.external_modules_download_path = external_modules_download_path
self.evaluate_variables = evaluate_variables
self.excluded_paths = excluded_paths or []
self.all_external = all_external
self.var_files = var_files
self.skip_cve_package = skip_cve_package
self.filtered_policy_ids = filtered_policy_ids or []
self.run_image_referencer = run_image_referencer
self.enable_secret_scan_all_files = enable_secret_scan_all_files
self.block_list_secret_scan = block_list_secret_scan
self.suppressed_policies: List[str] = []
self.deep_analysis = deep_analysis
self.repo_root_for_plan_enrichment = repo_root_for_plan_enrichment
self.resource_attr_to_omit: DefaultDict[str, Set[str]] = RunnerFilter._load_resource_attr_to_omit(
resource_attr_to_omit
)
self.sast_languages: Set[SastLanguages] = RunnerFilter.get_sast_languages(framework, skip_framework)
if self.sast_languages and any(item for item in self.framework if item.startswith(CheckType.SAST) or item == 'all'):
self.framework = [item for item in self.framework if not item.startswith(CheckType.SAST)]
self.framework.append(CheckType.SAST)
elif not self.sast_languages:
# remove all SAST and CDK frameworks
self.framework = [
item for item in self.framework if not item.startswith(CheckType.SAST) and item != CheckType.CDK
]
self.enable_git_history_secret_scan: bool = enable_git_history_secret_scan
if self.enable_git_history_secret_scan:
self.git_history_timeout = convert_to_seconds(git_history_timeout)
self.framework = [CheckType.SECRETS]
logging.debug("Scan secrets history was enabled ignoring other frameworks")
self.git_history_last_commit_scanned = git_history_last_commit_scanned
self.report_sast_imports = report_sast_imports
self.remove_default_sast_policies = remove_default_sast_policies
self.report_sast_reachability = report_sast_reachability
def _load_resource_attr_to_omit(resource_attr_to_omit_input: Optional[Dict[str, Set[str]]]) -> DefaultDict[str, Set[str]]:
resource_attributes_to_omit: DefaultDict[str, Set[str]] = defaultdict(set)
# In order to create new object (and not a reference to the given one)
if resource_attr_to_omit_input:
resource_attributes_to_omit.update(resource_attr_to_omit_input)
return resource_attributes_to_omit
def apply_enforcement_rules(self, enforcement_rule_configs: Dict[str, CodeCategoryConfiguration]) -> None:
self.enforcement_rule_configs = {}
for report_type, code_category in CodeCategoryMapping.items():
if isinstance(code_category, list):
self.enforcement_rule_configs[report_type] = {c: enforcement_rule_configs.get(c).soft_fail_threshold for c in code_category} # type:ignore[union-attr] # will not be None
else:
config = enforcement_rule_configs.get(code_category)
if not config:
raise Exception(f'Could not find an enforcement rule config for category {code_category} (runner: {report_type})')
self.enforcement_rule_configs[report_type] = config.soft_fail_threshold
def extract_enforcement_rule_threshold(self, check_id: str, report_type: str) -> Severity:
if 'sca_' in report_type and '_LIC_' in check_id:
return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.LICENSES]
elif 'sca_' in report_type: # vulnerability
return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.VULNERABILITIES]
else:
return cast(Severity, self.enforcement_rule_configs[report_type])
def should_run_check(
self,
check: BaseCheck | BaseGraphCheck | BaseSastCheck | None = None,
check_id: str | None = None,
bc_check_id: str | None = None,
severity: Severity | None = None,
report_type: str | None = None,
file_origin_paths: List[str] | None = None,
root_folder: str | None = None
) -> bool:
if check:
check_id = check.id
bc_check_id = check.bc_id
severity = check.severity
assert check_id is not None # nosec (for mypy (and then for bandit))
check_threshold: Optional[Severity]
skip_check_threshold: Optional[Severity]
# apply enforcement rules if specified, but let --check/--skip-check with a severity take priority
if self.use_enforcement_rules and report_type:
if not self.check_threshold and not self.skip_check_threshold:
check_threshold = self.extract_enforcement_rule_threshold(check_id, report_type)
skip_check_threshold = None
else:
check_threshold = self.check_threshold
skip_check_threshold = self.skip_check_threshold
else:
if self.use_enforcement_rules:
# this is a warning for us (but there is nothing the user can do about it)
logging.debug(f'Use enforcement rules is true, but check {check_id} was not passed to the runner filter with a report type')
check_threshold = self.check_threshold
skip_check_threshold = self.skip_check_threshold
run_severity = severity and check_threshold and severity.level >= check_threshold.level
explicit_run = self.checks and self.check_matches(check_id, bc_check_id, self.checks)
implicit_run = not self.checks and not check_threshold
is_external = RunnerFilter.is_external_check(check_id)
is_policy_filtered = self.is_policy_filtered(check_id)
# True if this check is present in the allow list, or if there is no allow list
# this is not necessarily the return value (need to apply other filters)
should_run_check = (
run_severity or
explicit_run or
implicit_run or
(is_external and self.all_external)
)
if not should_run_check:
logging.debug(f'Should run check {check_id}: False')
return False
# If a policy is not present in the list of filtered policies, it should not be run - implicitly or explicitly.
# It can, however, be skipped.
if not is_policy_filtered:
logging.debug(f'not is_policy_filtered {check_id}: should_run_check = False')
should_run_check = False
skip_severity = severity and skip_check_threshold and severity.level <= skip_check_threshold.level
explicit_skip = self.skip_checks and self.check_matches(check_id, bc_check_id, self.skip_checks)
regex_match = self._match_regex_pattern(check_id, file_origin_paths, root_folder)
should_skip_check = (
skip_severity or
explicit_skip or
regex_match or
(not bc_check_id and not self.include_all_checkov_policies and not is_external and not explicit_run) or
(bc_check_id in self.suppressed_policies and bc_check_id not in self.bc_cloned_checks)
)
logging.debug(f'skip_severity = {skip_severity}, explicit_skip = {explicit_skip}, regex_match = {regex_match}, suppressed_policies: {self.suppressed_policies}')
logging.debug(
f'bc_check_id = {bc_check_id}, include_all_checkov_policies = {self.include_all_checkov_policies}, is_external = {is_external}, explicit_run: {explicit_run}')
if should_skip_check:
result = False
logging.debug(f'should_skip_check {check_id}: {should_skip_check}')
elif should_run_check:
result = True
logging.debug(f'should_run_check {check_id}: {result}')
else:
result = False
logging.debug(f'default {check_id}: {result}')
return result
def _match_regex_pattern(self, check_id: str, file_origin_paths: List[str] | None, root_folder: str | None) -> bool:
"""
Check if skip check_id for a certain file_types, according to given path pattern
"""
if not file_origin_paths:
return False
regex_patterns = self.skip_checks_regex_patterns.get(check_id, [])
# In case skip is generic, for example, CKV_AZURE_*.
generic_check_id = f"{'_'.join(i for i in check_id.split('_')[:-1])}_*"
generic_check_regex_patterns = self.skip_checks_regex_patterns.get(generic_check_id, [])
regex_patterns.extend(generic_check_regex_patterns)
if not regex_patterns:
return False
for pattern in regex_patterns:
if not pattern:
continue
full_regex_pattern = fr"^{root_folder}/{pattern}" if root_folder else pattern
try:
if any(re.search(full_regex_pattern, path) for path in file_origin_paths):
return True
except Exception as exc:
logging.error(
"Invalid regex pattern has been supplied",
extra={"regex_pattern": pattern, "exc": str(exc)}
)
return False
def check_matches(check_id: str,
bc_check_id: Optional[str],
pattern_list: List[str]) -> bool:
return any(
(fnmatch.fnmatch(check_id, pattern) or (bc_check_id and fnmatch.fnmatch(bc_check_id, pattern))) for pattern
in pattern_list)
def within_threshold(self, severity: Severity) -> bool:
above_min = (not self.check_threshold) or self.check_threshold.level <= severity.level
below_max = self.skip_check_threshold and self.skip_check_threshold.level >= severity.level
return above_min and not below_max
def secret_validation_status_matches(secret_validation_status: str, statuses_list: list[str]) -> bool:
return secret_validation_status in statuses_list
def notify_external_check(check_id: str) -> None:
RunnerFilter.__EXTERNAL_CHECK_IDS.add(check_id)
def is_external_check(check_id: str) -> bool:
return check_id in RunnerFilter.__EXTERNAL_CHECK_IDS
def is_policy_filtered(self, check_id: str) -> bool:
if not self.filtered_policy_ids:
return True
return check_id in self.filtered_policy_ids
def to_dict(self) -> Dict[str, Any]:
result: Dict[str, Any] = {}
for key, value in self.__dict__.items():
result[key] = value
return result
def from_dict(obj: Dict[str, Any]) -> RunnerFilter:
framework = obj.get('framework')
checks = obj.get('checks')
skip_checks = obj.get('skip_checks')
include_all_checkov_policies = obj.get('include_all_checkov_policies')
if include_all_checkov_policies is None:
include_all_checkov_policies = True
download_external_modules = obj.get('download_external_modules')
if download_external_modules is None:
download_external_modules = False
external_modules_download_path = obj.get('external_modules_download_path')
if external_modules_download_path is None:
external_modules_download_path = DEFAULT_EXTERNAL_MODULES_DIR
evaluate_variables = obj.get('evaluate_variables')
if evaluate_variables is None:
evaluate_variables = True
runners = obj.get('runners')
skip_framework = obj.get('skip_framework')
excluded_paths = obj.get('excluded_paths')
all_external = obj.get('all_external')
if all_external is None:
all_external = False
var_files = obj.get('var_files')
skip_cve_package = obj.get('skip_cve_package')
use_enforcement_rules = obj.get('use_enforcement_rules')
if use_enforcement_rules is None:
use_enforcement_rules = False
filtered_policy_ids = obj.get('filtered_policy_ids')
show_progress_bar = obj.get('show_progress_bar')
if show_progress_bar is None:
show_progress_bar = True
run_image_referencer = obj.get('run_image_referencer')
if run_image_referencer is None:
run_image_referencer = False
enable_secret_scan_all_files = bool(obj.get('enable_secret_scan_all_files'))
block_list_secret_scan = obj.get('block_list_secret_scan')
runner_filter = RunnerFilter(framework, checks, skip_checks, include_all_checkov_policies,
download_external_modules, external_modules_download_path, evaluate_variables,
runners, skip_framework, excluded_paths, all_external, var_files,
skip_cve_package, use_enforcement_rules, filtered_policy_ids, show_progress_bar,
run_image_referencer, enable_secret_scan_all_files, block_list_secret_scan)
return runner_filter
def set_suppressed_policies(self, policy_level_suppressions: List[str]) -> None:
logging.debug(f"Received the following policy-level suppressions, that will be skipped from running: {policy_level_suppressions}")
self.suppressed_policies = policy_level_suppressions
def get_sast_languages(frameworks: Optional[List[str]], skip_framework: Optional[List[str]]) -> Set[SastLanguages]:
langs: Set[SastLanguages] = set()
if not frameworks or (skip_framework and "sast" in skip_framework):
return langs
if 'all' in frameworks:
sast_languages = SastLanguages.set()
skip_framework = [] if not skip_framework else [f.split("sast_")[-1] for f in skip_framework]
return set([lang for lang in sast_languages if lang.value not in skip_framework])
for framework in frameworks:
if framework in [CheckType.SAST, CheckType.CDK]:
for sast_lang in SastLanguages:
langs.add(sast_lang)
return langs
if not framework.startswith(CheckType.SAST):
continue
lang = '_'.join(framework.split('_')[1:])
langs.add(SastLanguages[lang.upper()])
return langs
class Parser:
def __init__(self) -> None:
self.bicep_parser = BicepParser(add_line_numbers=True)
def parse(self, file_path: Path) -> tuple[BicepJson, list[tuple[int, str]]] | tuple[None, None]:
try:
content = read_file_with_any_encoding(file_path=file_path)
template = self.bicep_parser.parse(text=content)
except Exception:
logging.debug(f"[bicep] Couldn't parse {file_path}", exc_info=True)
return None, None
file_lines = [(idx + 1, line) for idx, line in enumerate(content.splitlines(keepends=True))]
return template, file_lines
def get_files_definitions(
self, file_paths: "Collection[Path]"
) -> tuple[dict[Path, BicepJson], dict[Path, list[tuple[int, str]]], list[str]]:
logging.info(f"[bicep] start to parse {len(file_paths)} files")
definitions: dict[Path, BicepJson] = {}
definitions_raw: dict[Path, list[tuple[int, str]]] = {}
parsing_errors: list[str] = []
for file_path in file_paths:
template, file_lines = self.parse(file_path)
if template and file_lines:
definitions[file_path] = template
definitions_raw[file_path] = file_lines
else:
parsing_errors.append(os.path.normpath(file_path.absolute()))
logging.info(f"[bicep] successfully parsed {len(definitions)} files")
return definitions, definitions_raw, parsing_errors
def create_definitions(
root_folder: str,
files: "Collection[Path] | None" = None,
runner_filter: RunnerFilter | None = None,
) -> tuple[dict[Path, BicepJson], dict[Path, list[tuple[int, str]]]]:
definitions: dict[Path, BicepJson] = {}
definitions_raw: dict[Path, list[tuple[int, str]]] = {}
parsing_errors: list[str] = []
runner_filter = runner_filter or RunnerFilter()
if files:
parser = Parser()
definitions, definitions_raw, parsing_errors = parser.get_files_definitions(file_paths=files)
if root_folder:
definitions, definitions_raw, parsing_errors = get_folder_definitions(root_folder, runner_filter.excluded_paths)
if parsing_errors:
logging.warning(f"[bicep] found errors while parsing definitions: {parsing_errors}")
return definitions, definitions_raw | null |
2,256 | from __future__ import annotations
import logging
import os
import re
from collections.abc import Collection
from pathlib import Path
from typing import Any, TYPE_CHECKING
from checkov.common.runners.base_runner import filter_ignored_paths
from checkov.runner_filter import RunnerFilter
from checkov.bicep.parser import Parser
The provided code snippet includes necessary dependencies for implementing the `adjust_value` function. Write a Python function `def adjust_value(element_name: str, value: Any) -> Any` to solve the following problem:
Adjusts the value, if the 'element_name' references a nested key Ex: element_name = publicKey.keyData value = {"keyData": "key-data", "path": "path"} returns new_value = "key-data"
Here is the function:
def adjust_value(element_name: str, value: Any) -> Any:
"""Adjusts the value, if the 'element_name' references a nested key
Ex:
element_name = publicKey.keyData
value = {"keyData": "key-data", "path": "path"}
returns new_value = "key-data"
"""
if "." in element_name and isinstance(value, dict):
key_parts = element_name.split(".")
new_value = value.get(key_parts[1])
if new_value is None:
# couldn't find key in in value object
return None
return adjust_value(".".join(key_parts[1:]), new_value)
return value | Adjusts the value, if the 'element_name' references a nested key Ex: element_name = publicKey.keyData value = {"keyData": "key-data", "path": "path"} returns new_value = "key-data" |
2,257 | from __future__ import annotations
from typing import TYPE_CHECKING, Any
from checkov.bicep.image_referencer.base_provider import BaseBicepProvider
from checkov.common.util.data_structures_utils import find_in_dict
from checkov.common.util.type_forcers import force_list
def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any:
def extract_images_from_azurerm_batch_pool(resource: dict[str, Any]) -> list[str]:
image_names: list[str] = []
containers = find_in_dict(
input_dict=resource,
key_path="properties/virtualMachineConfiguration/containerConfiguration/containerImageNames",
)
if isinstance(containers, list):
image_names.extend(container for container in containers if isinstance(container, str))
return image_names | null |
2,258 | from __future__ import annotations
from typing import TYPE_CHECKING, Any
from checkov.bicep.image_referencer.base_provider import BaseBicepProvider
from checkov.common.util.data_structures_utils import find_in_dict
from checkov.common.util.type_forcers import force_list
def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any:
def force_list(var: list[T]) -> list[T]:
def force_list(var: T) -> list[T]:
def force_list(var: T | list[T]) -> list[T]:
def extract_images_from_azurerm_container_group(resource: dict[str, Any]) -> list[str]:
image_names: list[str] = []
properties = resource.get("properties")
if properties and isinstance(properties, dict):
containers = properties.get("containers")
if containers:
for container in force_list(containers):
name = find_in_dict(input_dict=container, key_path="properties/image")
if name and isinstance(name, str):
image_names.append(name)
containers = properties.get("initContainers")
if containers:
for container in force_list(containers):
name = find_in_dict(input_dict=container, key_path="properties/image")
if name and isinstance(name, str):
image_names.append(name)
return image_names | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.