code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def make_matrix(num_rows: int,
num_cols: int,
entry_fn: Callable[[int, int], float]) -> Matrix:
"""
Returns a num_rows x num_cols matrix
whose (i,j)-th entry is entry_fn(i, j)
"""
return [[entry_fn(i, j) # given i, create a list
for j in range... |
Returns a num_rows x num_cols matrix
whose (i,j)-th entry is entry_fn(i, j)
| make_matrix | python | joelgrus/data-science-from-scratch | scratch/linear_algebra.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/linear_algebra.py | MIT |
def _negative_log_likelihood(x: Vector, y: float, beta: Vector) -> float:
"""The negative log likelihood for one data point"""
if y == 1:
return -math.log(logistic(dot(x, beta)))
else:
return -math.log(1 - logistic(dot(x, beta))) | The negative log likelihood for one data point | _negative_log_likelihood | python | joelgrus/data-science-from-scratch | scratch/logistic_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/logistic_regression.py | MIT |
def _negative_log_gradient(x: Vector, y: float, beta: Vector) -> Vector:
"""
The gradient for one data point
"""
return [_negative_log_partial_j(x, y, beta, j)
for j in range(len(beta))] |
The gradient for one data point
| _negative_log_gradient | python | joelgrus/data-science-from-scratch | scratch/logistic_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/logistic_regression.py | MIT |
def split_data(data: List[X], prob: float) -> Tuple[List[X], List[X]]:
"""Split data into fractions [prob, 1 - prob]"""
data = data[:] # Make a shallow copy
random.shuffle(data) # because shuffle modifies the list.
cut = int(len(data) * prob) # Use prob to find a cu... | Split data into fractions [prob, 1 - prob] | split_data | python | joelgrus/data-science-from-scratch | scratch/machine_learning.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/machine_learning.py | MIT |
def wc_reducer(word: str,
counts: Iterable[int]) -> Iterator[Tuple[str, int]]:
"""Sum up the counts for a word"""
yield (word, sum(counts)) | Sum up the counts for a word | wc_reducer | python | joelgrus/data-science-from-scratch | scratch/mapreduce.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/mapreduce.py | MIT |
def word_count(documents: List[str]) -> List[Tuple[str, int]]:
"""Count the words in the input documents using MapReduce"""
collector = defaultdict(list) # To store grouped values
for document in documents:
for word, count in wc_mapper(document):
collector[word].append(count)
ret... | Count the words in the input documents using MapReduce | word_count | python | joelgrus/data-science-from-scratch | scratch/mapreduce.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/mapreduce.py | MIT |
def map_reduce(inputs: Iterable,
mapper: Mapper,
reducer: Reducer) -> List[KV]:
"""Run MapReduce on the inputs using mapper and reducer"""
collector = defaultdict(list)
for input in inputs:
for key, value in mapper(input):
collector[key].append(value)
... | Run MapReduce on the inputs using mapper and reducer | map_reduce | python | joelgrus/data-science-from-scratch | scratch/mapreduce.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/mapreduce.py | MIT |
def values_reducer(values_fn: Callable) -> Reducer:
"""Return a reducer that just applies values_fn to its values"""
def reduce(key, values: Iterable) -> KV:
return (key, values_fn(values))
return reduce | Return a reducer that just applies values_fn to its values | values_reducer | python | joelgrus/data-science-from-scratch | scratch/mapreduce.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/mapreduce.py | MIT |
def most_popular_word_reducer(user: str,
words_and_counts: Iterable[KV]):
"""
Given a sequence of (word, count) pairs,
return the word with the highest total count
"""
word_counts = Counter()
for word, count in words_and_counts:
... |
Given a sequence of (word, count) pairs,
return the word with the highest total count
| most_popular_word_reducer | python | joelgrus/data-science-from-scratch | scratch/mapreduce.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/mapreduce.py | MIT |
def least_squares_fit(xs: List[Vector],
ys: List[float],
learning_rate: float = 0.001,
num_steps: int = 1000,
batch_size: int = 1) -> Vector:
"""
Find the beta that minimizes the sum of squared errors
assuming the model ... |
Find the beta that minimizes the sum of squared errors
assuming the model y = dot(x, beta).
| least_squares_fit | python | joelgrus/data-science-from-scratch | scratch/multiple_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/multiple_regression.py | MIT |
def squared_error_ridge(x: Vector,
y: float,
beta: Vector,
alpha: float) -> float:
"""estimate error plus ridge penalty on beta"""
return error(x, y, beta) ** 2 + ridge_penalty(beta, alpha) | estimate error plus ridge penalty on beta | squared_error_ridge | python | joelgrus/data-science-from-scratch | scratch/multiple_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/multiple_regression.py | MIT |
def sqerror_ridge_gradient(x: Vector,
y: float,
beta: Vector,
alpha: float) -> Vector:
"""
the gradient corresponding to the ith squared error term
including the ridge penalty
"""
return add(sqerror_gradient(x, y, beta)... |
the gradient corresponding to the ith squared error term
including the ridge penalty
| sqerror_ridge_gradient | python | joelgrus/data-science-from-scratch | scratch/multiple_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/multiple_regression.py | MIT |
def _probabilities(self, token: str) -> Tuple[float, float]:
"""returns P(token | spam) and P(token | not spam)"""
spam = self.token_spam_counts[token]
ham = self.token_ham_counts[token]
p_token_spam = (spam + self.k) / (self.spam_messages + 2 * self.k)
p_token_ham = (ham + self... | returns P(token | spam) and P(token | not spam) | _probabilities | python | joelgrus/data-science-from-scratch | scratch/naive_bayes.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/naive_bayes.py | MIT |
def feed_forward(neural_network: List[List[Vector]],
input_vector: Vector) -> List[Vector]:
"""
Feeds the input vector through the neural network.
Returns the outputs of all layers (not just the last one).
"""
outputs: List[Vector] = []
for layer in neural_network:
inpu... |
Feeds the input vector through the neural network.
Returns the outputs of all layers (not just the last one).
| feed_forward | python | joelgrus/data-science-from-scratch | scratch/neural_networks.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/neural_networks.py | MIT |
def sqerror_gradients(network: List[List[Vector]],
input_vector: Vector,
target_vector: Vector) -> List[List[Vector]]:
"""
Given a neural network, an input vector, and a target vector,
make a prediction and compute the gradient of the squared error
loss with r... |
Given a neural network, an input vector, and a target vector,
make a prediction and compute the gradient of the squared error
loss with respect to the neuron weights.
| sqerror_gradients | python | joelgrus/data-science-from-scratch | scratch/neural_networks.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/neural_networks.py | MIT |
def sample_from(weights: List[float]) -> int:
"""returns i with probability weights[i] / sum(weights)"""
total = sum(weights)
rnd = total * random.random() # uniform between 0 and total
for i, w in enumerate(weights):
rnd -= w # return the smallest i such that
... | returns i with probability weights[i] / sum(weights) | sample_from | python | joelgrus/data-science-from-scratch | scratch/nlp.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/nlp.py | MIT |
def p_topic_given_document(topic: int, d: int, alpha: float = 0.1) -> float:
"""
The fraction of words in document _d_
that are assigned to _topic_ (plus some smoothing)
"""
return ((document_topic_counts[d][topic] + alpha) /
(document_lengths[d] + K * alpha)) |
The fraction of words in document _d_
that are assigned to _topic_ (plus some smoothing)
| p_topic_given_document | python | joelgrus/data-science-from-scratch | scratch/nlp.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/nlp.py | MIT |
def p_word_given_topic(word: str, topic: int, beta: float = 0.1) -> float:
"""
The fraction of words assigned to _topic_
that equal _word_ (plus some smoothing)
"""
return ((topic_word_counts[topic][word] + beta) /
(topic_counts[topic] + W * beta)) |
The fraction of words assigned to _topic_
that equal _word_ (plus some smoothing)
| p_word_given_topic | python | joelgrus/data-science-from-scratch | scratch/nlp.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/nlp.py | MIT |
def closest(self, word: str, n: int = 5) -> List[Tuple[float, str]]:
"""Returns the n closest words based on cosine similarity"""
vector = self[word]
# Compute pairs (similarity, other_word), and sort most similar first
scores = [(cosine_similarity(vector, self.embeddings[i]), other_wor... | Returns the n closest words based on cosine similarity | closest | python | joelgrus/data-science-from-scratch | scratch/nlp.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/nlp.py | MIT |
def uniform_cdf(x: float) -> float:
"""Returns the probability that a uniform random variable is <= x"""
if x < 0: return 0 # uniform random is never less than 0
elif x < 1: return x # e.g. P(X <= 0.4) = 0.4
else: return 1 # uniform random is always less than 1 | Returns the probability that a uniform random variable is <= x | uniform_cdf | python | joelgrus/data-science-from-scratch | scratch/probability.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/probability.py | MIT |
def inverse_normal_cdf(p: float,
mu: float = 0,
sigma: float = 1,
tolerance: float = 0.00001) -> float:
"""Find approximate inverse using binary search"""
# if not standard, compute standard and rescale
if mu != 0 or sigma != 1:
r... | Find approximate inverse using binary search | inverse_normal_cdf | python | joelgrus/data-science-from-scratch | scratch/probability.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/probability.py | MIT |
def binomial_histogram(p: float, n: int, num_points: int) -> None:
"""Picks points from a Binomial(n, p) and plots their histogram"""
data = [binomial(n, p) for _ in range(num_points)]
# use a bar chart to show the actual binomial samples
histogram = Counter(data)
plt.bar([x - 0.4 for x in histogra... | Picks points from a Binomial(n, p) and plots their histogram | binomial_histogram | python | joelgrus/data-science-from-scratch | scratch/probability.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/probability.py | MIT |
def make_user_interest_vector(user_interests: List[str]) -> List[int]:
"""
Given a list ofinterests, produce a vector whose ith element is 1
if unique_interests[i] is in the list, 0 otherwise
"""
return [1 if interest in user_interests else 0
for interest in unique_interests] |
Given a list ofinterests, produce a vector whose ith element is 1
if unique_interests[i] is in the list, 0 otherwise
| make_user_interest_vector | python | joelgrus/data-science-from-scratch | scratch/recommender_systems.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/recommender_systems.py | MIT |
def least_squares_fit(x: Vector, y: Vector) -> Tuple[float, float]:
"""
Given two vectors x and y,
find the least-squares values of alpha and beta
"""
beta = correlation(x, y) * standard_deviation(y) / standard_deviation(x)
alpha = mean(y) - beta * mean(x)
return alpha, beta |
Given two vectors x and y,
find the least-squares values of alpha and beta
| least_squares_fit | python | joelgrus/data-science-from-scratch | scratch/simple_linear_regression.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/simple_linear_regression.py | MIT |
def _median_even(xs: List[float]) -> float:
"""If len(xs) is even, it's the average of the middle two elements"""
sorted_xs = sorted(xs)
hi_midpoint = len(xs) // 2 # e.g. length 4 => hi_midpoint 2
return (sorted_xs[hi_midpoint - 1] + sorted_xs[hi_midpoint]) / 2 | If len(xs) is even, it's the average of the middle two elements | _median_even | python | joelgrus/data-science-from-scratch | scratch/statistics.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/statistics.py | MIT |
def mode(x: List[float]) -> List[float]:
"""Returns a list, since there might be more than one mode"""
counts = Counter(x)
max_count = max(counts.values())
return [x_i for x_i, count in counts.items()
if count == max_count] | Returns a list, since there might be more than one mode | mode | python | joelgrus/data-science-from-scratch | scratch/statistics.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/statistics.py | MIT |
def de_mean(xs: List[float]) -> List[float]:
"""Translate xs by subtracting its mean (so the result has mean 0)"""
x_bar = mean(xs)
return [x - x_bar for x in xs] | Translate xs by subtracting its mean (so the result has mean 0) | de_mean | python | joelgrus/data-science-from-scratch | scratch/statistics.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/statistics.py | MIT |
def variance(xs: List[float]) -> float:
"""Almost the average squared deviation from the mean"""
assert len(xs) >= 2, "variance requires at least two elements"
n = len(xs)
deviations = de_mean(xs)
return sum_of_squares(deviations) / (n - 1) | Almost the average squared deviation from the mean | variance | python | joelgrus/data-science-from-scratch | scratch/statistics.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/statistics.py | MIT |
def correlation(xs: List[float], ys: List[float]) -> float:
"""Measures how much xs and ys vary in tandem about their means"""
stdev_x = standard_deviation(xs)
stdev_y = standard_deviation(ys)
if stdev_x > 0 and stdev_y > 0:
return covariance(xs, ys) / stdev_x / stdev_y
else:
return ... | Measures how much xs and ys vary in tandem about their means | correlation | python | joelgrus/data-science-from-scratch | scratch/statistics.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/statistics.py | MIT |
def correlation_matrix(data: List[Vector]) -> Matrix:
"""
Returns the len(data) x len(data) matrix whose (i, j)-th entry
is the correlation between data[i] and data[j]
"""
def correlation_ij(i: int, j: int) -> float:
return correlation(data[i], data[j])
return make_matrix(len(data), len... |
Returns the len(data) x len(data) matrix whose (i, j)-th entry
is the correlation between data[i] and data[j]
| correlation_matrix | python | joelgrus/data-science-from-scratch | scratch/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/working_with_data.py | MIT |
def day_over_day_changes(prices: List[StockPrice]) -> List[DailyChange]:
"""
Assumes prices are for one stock and are in order
"""
return [DailyChange(symbol=today.symbol,
date=today.date,
pct_change=pct_change(yesterday, today))
for yesterday,... |
Assumes prices are for one stock and are in order
| day_over_day_changes | python | joelgrus/data-science-from-scratch | scratch/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/working_with_data.py | MIT |
def scale(data: List[Vector]) -> Tuple[Vector, Vector]:
"""returns the means and standard deviations for each position"""
dim = len(data[0])
means = vector_mean(data)
stdevs = [standard_deviation([vector[i] for vector in data])
for i in range(dim)]
return means, stdevs | returns the means and standard deviations for each position | scale | python | joelgrus/data-science-from-scratch | scratch/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/working_with_data.py | MIT |
def rescale(data: List[Vector]) -> List[Vector]:
"""
Rescales the input data so that each position has
mean 0 and standard deviation 1. (Leaves a position
as is if its standard deviation is 0.)
"""
dim = len(data[0])
means, stdevs = scale(data)
# Make a copy of each vector
rescaled ... |
Rescales the input data so that each position has
mean 0 and standard deviation 1. (Leaves a position
as is if its standard deviation is 0.)
| rescale | python | joelgrus/data-science-from-scratch | scratch/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/working_with_data.py | MIT |
def de_mean(data: List[Vector]) -> List[Vector]:
"""Recenters the data to have mean 0 in every dimension"""
mean = vector_mean(data)
return [subtract(vector, mean) for vector in data] | Recenters the data to have mean 0 in every dimension | de_mean | python | joelgrus/data-science-from-scratch | scratch/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/working_with_data.py | MIT |
def directional_variance(data: List[Vector], w: Vector) -> float:
"""
Returns the variance of x in the direction of w
"""
w_dir = direction(w)
return sum(dot(v, w_dir) ** 2 for v in data) |
Returns the variance of x in the direction of w
| directional_variance | python | joelgrus/data-science-from-scratch | scratch/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/working_with_data.py | MIT |
def directional_variance_gradient(data: List[Vector], w: Vector) -> Vector:
"""
The gradient of directional variance with respect to w
"""
w_dir = direction(w)
return [sum(2 * dot(v, w_dir) * v[i] for v in data)
for i in range(len(w))] |
The gradient of directional variance with respect to w
| directional_variance_gradient | python | joelgrus/data-science-from-scratch | scratch/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/working_with_data.py | MIT |
def project(v: Vector, w: Vector) -> Vector:
"""return the projection of v onto the direction w"""
projection_length = dot(v, w)
return scalar_multiply(projection_length, w) | return the projection of v onto the direction w | project | python | joelgrus/data-science-from-scratch | scratch/working_with_data.py | https://github.com/joelgrus/data-science-from-scratch/blob/master/scratch/working_with_data.py | MIT |
async def step(observation, action, label, **kwargs) -> Dict[str, Any]:
"""Execute one step of verification and return a random reward using torch.rand
Args:
observation: The input prompt/expression
action: The language model's response
label: Agent identifier or additional information
... | Execute one step of verification and return a random reward using torch.rand
Args:
observation: The input prompt/expression
action: The language model's response
label: Agent identifier or additional information
Returns:
Dict[str, Any]: A dictionary containing:
- re... | step | python | OpenRLHF/OpenRLHF | examples/python/agent_func.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/examples/python/agent_func.py | Apache-2.0 |
def reward_func(queries, prompts, labels, **kwargs):
"""
Reward function for calculating rewards of model outputs.
Args:
queries (torch.Tensor): Complete text sequences containing prompts and responses
prompts (torch.Tensor): Input prompt sequences
labels (torch.Tensor): Ground trut... |
Reward function for calculating rewards of model outputs.
Args:
queries (torch.Tensor): Complete text sequences containing prompts and responses
prompts (torch.Tensor): Input prompt sequences
labels (torch.Tensor): Ground truth answer sequences
**kwargs: Additional optional par... | reward_func | python | OpenRLHF/OpenRLHF | examples/python/reward_func.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/examples/python/reward_func.py | Apache-2.0 |
def preprocess_data(
data, input_template=None, input_key=None, output_key=None, label_key=None, apply_chat_template=None
):
"""
Preprocess data from raw dataset to prompt, response, label
Args:
data: raw data from dataset
"""
label = data[label_key]
if apply_chat_template:
... |
Preprocess data from raw dataset to prompt, response, label
Args:
data: raw data from dataset
| preprocess_data | python | OpenRLHF/OpenRLHF | openrlhf/datasets/unpaired_preference_dataset.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/datasets/unpaired_preference_dataset.py | Apache-2.0 |
def blending_datasets(
datasets,
probabilities=None,
strategy=None,
seed=42,
max_count=1e8,
stopping_strategy="all_exhausted",
dataset_split="train",
):
"""Blend multiple datasets with optional probability sampling.
Args:
datasets (str): Comma-separated list of dataset paths... | Blend multiple datasets with optional probability sampling.
Args:
datasets (str): Comma-separated list of dataset paths
probabilities (str, optional): Comma-separated list of probabilities for sampling.
If None, datasets will be concatenated without probability sampling.
strateg... | blending_datasets | python | OpenRLHF/OpenRLHF | openrlhf/datasets/utils.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/datasets/utils.py | Apache-2.0 |
def get_llm_for_sequence_regression(
model_name_or_path: str,
model_type: str,
*,
bf16=True,
load_in_4bit=False,
lora_rank=0,
lora_alpha=16,
target_modules=None,
lora_dropout=0,
normalize_reward=False,
use_flash_attention_2=False,
ds_config: dict = None,
init_value_he... | Retrieve a transformer model with a sequence regression head on top.
This function loads a pretrained transformer model and attaches a linear layer for sequence regression.
Args:
model_name_or_path (str): Path to the pretrained model.
model_type (str): Type of the model, either "reward" or "cr... | get_llm_for_sequence_regression | python | OpenRLHF/OpenRLHF | openrlhf/models/model.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/models/model.py | Apache-2.0 |
def reset_ring_attn_position_ids(start, end, packed_seq_lens):
"""
Calculate position ids for packed_seq_ids[start:end].
For example, if the packed_seq_lens is [3, 2, 4, 1], start=2, end=8,
the position ids will be [2, 0, 1, 0, 1, 2].
Args:
start: the start position
end: the end pos... |
Calculate position ids for packed_seq_ids[start:end].
For example, if the packed_seq_lens is [3, 2, 4, 1], start=2, end=8,
the position ids will be [2, 0, 1, 0, 1, 2].
Args:
start: the start position
end: the end position
packed_seq_lens: the sequence lengths of packed sequence... | reset_ring_attn_position_ids | python | OpenRLHF/OpenRLHF | openrlhf/models/ring_attn_utils.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/models/ring_attn_utils.py | Apache-2.0 |
def update_ring_attn_params(cu_seqlens):
"""
Calculate the cu_seqlens for the current forward pass and pass the value to
the substituted ring_flash_attn.
Note that total_seq_len may be larger than the sum of packed_seq_lens because of padding.
"""
assert RING_ATTN_GROUP is not None
from ri... |
Calculate the cu_seqlens for the current forward pass and pass the value to
the substituted ring_flash_attn.
Note that total_seq_len may be larger than the sum of packed_seq_lens because of padding.
| update_ring_attn_params | python | OpenRLHF/OpenRLHF | openrlhf/models/ring_attn_utils.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/models/ring_attn_utils.py | Apache-2.0 |
def get_tensor_in_current_ring_attn_rank(tensors: list[torch.Tensor] | torch.Tensor, ring_attn_group, pad_id):
"""
Deal with padding and slice the tensor to current ring_attn_rank.
Args:
tensors: Each tensor shaped (batch, seqlen) or (1, total_seqs)
ring_attn_group: Ring attention group
... |
Deal with padding and slice the tensor to current ring_attn_rank.
Args:
tensors: Each tensor shaped (batch, seqlen) or (1, total_seqs)
ring_attn_group: Ring attention group
pad_id: Padding id
Returns:
Processed tensor
| get_tensor_in_current_ring_attn_rank | python | OpenRLHF/OpenRLHF | openrlhf/models/ring_attn_utils.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/models/ring_attn_utils.py | Apache-2.0 |
def unpad_and_slice_tensor(sequences, attention_mask, ring_attn_group):
"""
Unpad and slice tensor for distributed training with ring attention.
This function performs several operations:
1. Removes padding, unpads sequences from (batch, seqlen) to (1, total_seqs)
2. Adapts to ring_attn_group, pads... |
Unpad and slice tensor for distributed training with ring attention.
This function performs several operations:
1. Removes padding, unpads sequences from (batch, seqlen) to (1, total_seqs)
2. Adapts to ring_attn_group, pads sequences to be divisible by ring_attn_group
3. Slices the sequences for t... | unpad_and_slice_tensor | python | OpenRLHF/OpenRLHF | openrlhf/models/ring_attn_utils.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/models/ring_attn_utils.py | Apache-2.0 |
def gather_and_pad_tensor(tensor, ring_attn_group, ring_attn_pad_len, indices, batch, seqlen):
"""
Gather and pad tensor data (such as logits, log_probs, etc.).
Example:
>>> # Input tensor from each rank (shape: (1, local_seq_len))
>>> # Rank 0: [1, 2, 3]
>>> # Rank 1: [4, 5, 0] # ... |
Gather and pad tensor data (such as logits, log_probs, etc.).
Example:
>>> # Input tensor from each rank (shape: (1, local_seq_len))
>>> # Rank 0: [1, 2, 3]
>>> # Rank 1: [4, 5, 0] # 0 is padding
>>> # After all_gather:
>>> # tensor: [1, 2, 3, 4, 5, 0] # shape (1, tot... | gather_and_pad_tensor | python | OpenRLHF/OpenRLHF | openrlhf/models/ring_attn_utils.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/models/ring_attn_utils.py | Apache-2.0 |
def compute_approx_kl(
log_probs: torch.Tensor,
log_probs_base: torch.Tensor,
kl_estimator: str = "k1",
) -> torch.Tensor:
"""
Compute the approximate KL divergence between two distributions.
Schulman blog: http://joschu.net/blog/kl-approx.html
Args:
log_probs: Log probabilities of ... |
Compute the approximate KL divergence between two distributions.
Schulman blog: http://joschu.net/blog/kl-approx.html
Args:
log_probs: Log probabilities of the new distribution.
log_probs_base: Log probabilities of the base distribution.
| compute_approx_kl | python | OpenRLHF/OpenRLHF | openrlhf/models/utils.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/models/utils.py | Apache-2.0 |
def concatenated_inputs(self, chosen_ids, c_mask, reject_ids, r_mask, prompt_id_lens):
"""Concatenate the chosen and rejected inputs into a single tensor.
Args:
batch: A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (batch_size,... | Concatenate the chosen and rejected inputs into a single tensor.
Args:
batch: A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (batch_size, sequence_length).
Returns:
A dictionary containing the concatenated inputs u... | concatenated_inputs | python | OpenRLHF/OpenRLHF | openrlhf/trainer/dpo_trainer.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/dpo_trainer.py | Apache-2.0 |
def _get_batch_logps(
self,
per_token_logps: torch.LongTensor,
attention_mask,
prompt_id_lens,
average_log_prob: bool = False,
) -> torch.FloatTensor:
"""Compute the log probabilities of the given labels under the given logits.
Args:
per_token_log... | Compute the log probabilities of the given labels under the given logits.
Args:
per_token_logps: Per token log probabilities. Shape: (batch_size, sequence_length)
average_log_prob: If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log p... | _get_batch_logps | python | OpenRLHF/OpenRLHF | openrlhf/trainer/dpo_trainer.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/dpo_trainer.py | Apache-2.0 |
def compute_model_logps_with_KL(self, model, input_ids, attention_mask, labels, prompt_id_lens):
"""
the front half is matched for spv, the latter half is unmatched for KL
"""
hsize = input_ids.shape[0] // 2
# front half
chosen_logps, reject_logps, aux_loss = self.comput... |
the front half is matched for spv, the latter half is unmatched for KL
| compute_model_logps_with_KL | python | OpenRLHF/OpenRLHF | openrlhf/trainer/kto_trainer.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/kto_trainer.py | Apache-2.0 |
def _get_batch_logps(
self,
logits: torch.FloatTensor,
labels: torch.LongTensor,
attention_mask: torch.LongTensor,
average_log_prob: bool = False,
prompt_id_lens=[],
) -> torch.FloatTensor:
"""Compute the log probabilities of the given labels under the given l... | Compute the log probabilities of the given labels under the given logits.
Args:
logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size)
labels: Labels for which to compute the log probabilities. Label tokens with a value of -100 are ignored. Shape: (... | _get_batch_logps | python | OpenRLHF/OpenRLHF | openrlhf/trainer/kto_trainer.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/kto_trainer.py | Apache-2.0 |
async def wait_generating(self):
"""Wait for generation to be allowed."""
return await self.generating_event.wait() | Wait for generation to be allowed. | wait_generating | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_trainer_async.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_trainer_async.py | Apache-2.0 |
async def wait_update_weights(self):
"""Wait for weight update to be allowed."""
return await self.update_weights_event.wait() | Wait for weight update to be allowed. | wait_update_weights | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_trainer_async.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_trainer_async.py | Apache-2.0 |
def set_generating(self, allow_generating):
"""Set generation state.
Args:
is_generating: True to allow generation, False to block it
"""
if allow_generating:
self.generating_event.set()
else:
self.generating_event.clear() | Set generation state.
Args:
is_generating: True to allow generation, False to block it
| set_generating | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_trainer_async.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_trainer_async.py | Apache-2.0 |
def set_update_weights(self, allow_updating):
"""Set weight update state.
Args:
is_updating: True to allow weight updates, False to block it
"""
if allow_updating:
self.update_weights_event.set()
else:
self.update_weights_event.clear() | Set weight update state.
Args:
is_updating: True to allow weight updates, False to block it
| set_update_weights | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_trainer_async.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_trainer_async.py | Apache-2.0 |
def to_device(self, device: torch.device):
"""Move all tensor fields to the specified device."""
for field, value in self.__dict__.items():
if isinstance(value, dict):
setattr(self, field, {key: to(val, device) for key, val in value.items()})
else:
... | Move all tensor fields to the specified device. | to_device | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/experience_maker.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/experience_maker.py | Apache-2.0 |
def pin_memory(self):
"""Pin memory for all tensor fields."""
for field, value in self.__dict__.items():
if isinstance(value, dict):
setattr(self, field, {key: pin_memory(val) for key, val in value.items()})
else:
setattr(self, field, pin_memory(va... | Pin memory for all tensor fields. | pin_memory | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/experience_maker.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/experience_maker.py | Apache-2.0 |
def select(experiences: List["Experience"], fields: List[str]) -> List["Experience"]:
"""Select specific fields from a list of Experience instances to create new Experience instances.
Args:
experiences: List of Experience instances
fields: List of field names to select
... | Select specific fields from a list of Experience instances to create new Experience instances.
Args:
experiences: List of Experience instances
fields: List of field names to select
Returns:
A list of new Experience instances containing only the selected fields
... | select | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/experience_maker.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/experience_maker.py | Apache-2.0 |
def _merge_item(items: List, pad_value: int = 0) -> Union[torch.Tensor, list, dict, Any]:
"""Merge a list of items into a single item.
Recursively merge tensors, lists and dicts.
For tensors, use zero_pad_sequences to merge sequences of different lengths.
Args:
items: List o... | Merge a list of items into a single item.
Recursively merge tensors, lists and dicts.
For tensors, use zero_pad_sequences to merge sequences of different lengths.
Args:
items: List of items to merge
pad_value: Value used for padding tensors
| _merge_item | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/experience_maker.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/experience_maker.py | Apache-2.0 |
def concat_experiences(experiences_list: List["Experience"], pad_token_id) -> "Experience":
"""Concatenate multiple experiences into one large experience.
Args:
experiences_list: List of Experience to concatenate
pad_token_id: Token id used for padding sequences
Returns... | Concatenate multiple experiences into one large experience.
Args:
experiences_list: List of Experience to concatenate
pad_token_id: Token id used for padding sequences
Returns:
A new Experience instance containing all the concatenated data
| concat_experiences | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/experience_maker.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/experience_maker.py | Apache-2.0 |
def update_samples_with_rewards(rewards_info, samples_list):
"""Process rewards info and update samples with rewards, scores and extra logs.
Args:
rewards_info: List of reward information dictionaries
samples_list: List of Experience objects to update
"""
# Process rewards and scores
... | Process rewards info and update samples with rewards, scores and extra logs.
Args:
rewards_info: List of reward information dictionaries
samples_list: List of Experience objects to update
| update_samples_with_rewards | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/experience_maker.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/experience_maker.py | Apache-2.0 |
def generate_samples(self, all_prompts: List[str], all_labels, **generate_kwargs) -> List[Experience]:
"""
Generate samples and return in batches.
When not using vllm, we will fallback to the default implementation,
in which actor will be used to generate samples.
"""
# ... |
Generate samples and return in batches.
When not using vllm, we will fallback to the default implementation,
in which actor will be used to generate samples.
| generate_samples | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/experience_maker.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/experience_maker.py | Apache-2.0 |
def _generate_vllm(self, all_prompts: List[str], all_labels, **kwargs) -> List[Experience]:
"""Generate samples using vLLM engine.
Args:
all_prompts: List of prompts to generate from
all_labels: List of labels corresponding to prompts
**kwargs: Additional arguments f... | Generate samples using vLLM engine.
Args:
all_prompts: List of prompts to generate from
all_labels: List of labels corresponding to prompts
**kwargs: Additional arguments for generation
Returns:
List of Experience objects containing generated samples
... | _generate_vllm | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/experience_maker.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/experience_maker.py | Apache-2.0 |
def make_experience_batch(self, rollout_samples) -> List[Experience]:
"""
Make a list of experience with the micro_rollout_batch_size.
This method will first calculate the response sequences and rewards for the given prompts.
Then, if we need certain processing for the rewards or do cer... |
Make a list of experience with the micro_rollout_batch_size.
This method will first calculate the response sequences and rewards for the given prompts.
Then, if we need certain processing for the rewards or do certain filtering, we can process the rollout as a whole.
After that, we wil... | make_experience_batch | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/experience_maker.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/experience_maker.py | Apache-2.0 |
def compute_advantages_and_returns(
self, experiences: List[Experience], **kwargs
) -> Tuple[List[Experience], List[torch.Tensor]]:
"""
Process experiences, this can be used to filter out some experiences or do some processing on the rewards.
Output:
- experiences: List of E... |
Process experiences, this can be used to filter out some experiences or do some processing on the rewards.
Output:
- experiences: List of Experience
- rewards: List of rewards
| compute_advantages_and_returns | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/experience_maker.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/experience_maker.py | Apache-2.0 |
def get_cumulative_returns(
self,
rewards: torch.Tensor,
action_mask: torch.Tensor,
gamma: float,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Function that computes advantages and returns from rewards using REINFORCE.
REINFORCE uses cumulative returns without ... |
Function that computes advantages and returns from rewards using REINFORCE.
REINFORCE uses cumulative returns without the GAE (Generalized Advantage Estimation).
Input:
- rewards: Tensor of shape (batch_size, response_size)
- action_mask: Tensor of shape (batch_size, response_s... | get_cumulative_returns | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/experience_maker.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/experience_maker.py | Apache-2.0 |
def split_experience_batch(experience: Experience) -> List[BufferItem]:
"""Split a batch of experiences into individual BufferItems."""
batch_size = len(experience.sequences)
# Get fields from BufferItem, excluding 'info'
keys = tuple(field.name for field in fields(BufferItem) if field.name != "info")
... | Split a batch of experiences into individual BufferItems. | split_experience_batch | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/replay_buffer.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/replay_buffer.py | Apache-2.0 |
def make_experience_batch(items: List[BufferItem], packing_samples=False) -> Experience:
"""Combine individual BufferItems into a batch of experiences."""
if not items:
raise ValueError("Empty items list")
# Get fields from BufferItem, excluding 'info'
keys = tuple(field.name for field in field... | Combine individual BufferItems into a batch of experiences. | make_experience_batch | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ppo_utils/replay_buffer.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ppo_utils/replay_buffer.py | Apache-2.0 |
def execute_batch(self, method_name: str, all_data, start_idx, end_idx):
"""Process input data by calling specified function for each item in the lists.
Args:
method_name (str): Name of the function to execute
kwargs: Reference to the chunk of data to process
Returns:
... | Process input data by calling specified function for each item in the lists.
Args:
method_name (str): Name of the function to execute
kwargs: Reference to the chunk of data to process
Returns:
List[Any]: List of results from function execution
| execute_batch | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ray/launcher.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ray/launcher.py | Apache-2.0 |
def async_init_model_from_pretrained(
self,
*args,
**kwargs,
):
"""Init model from pretrained checkpoint.
Returns:
List: list of remote object refs.
"""
return [actor.init_model_from_pretrained.remote(*args, **kwargs) for actor in self._actor_hand... | Init model from pretrained checkpoint.
Returns:
List: list of remote object refs.
| async_init_model_from_pretrained | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ray/launcher.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ray/launcher.py | Apache-2.0 |
def async_run_method_batch(self, method_name, **kwargs):
"""Run method on all actors with batched input data asynchronously using round-robin scheduling.
Each actor processes one chunk of data at a time. Actors in the same ring / tensor parallel group process the same chunk.
Args:
m... | Run method on all actors with batched input data asynchronously using round-robin scheduling.
Each actor processes one chunk of data at a time. Actors in the same ring / tensor parallel group process the same chunk.
Args:
method_name (str): Name of the method to run
**kwargs: Ke... | async_run_method_batch | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ray/launcher.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ray/launcher.py | Apache-2.0 |
def __init__(
self,
strategy,
actor: Actor,
ema_model: Actor,
actor_optim: Optimizer,
actor_scheduler,
ema_beta: float = 0.992,
micro_train_batch_size: int = 8,
buffer_limit: int = 0,
buffer_cpu_offload: bool = True,
eps_clip: float... | PPOTrainer for ray.
Args:
vllm_engines (List, optional): vllm engines for text generation, if not specified, generate text by actor model directly. Defaults to None.
| __init__ | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ray/ppo_actor.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ray/ppo_actor.py | Apache-2.0 |
def fit(self, kl_ctl: float = 0):
"""Train actor model with the replay buffer."""
torch.cuda.empty_cache()
self.actor.train()
status = self.trainer.ppo_train(kl_ctl)
self.trainer.replay_buffer.clear()
torch.cuda.empty_cache()
torch.cuda.synchronize()
retur... | Train actor model with the replay buffer. | fit | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ray/ppo_actor.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ray/ppo_actor.py | Apache-2.0 |
def fit(self):
"""Train critic model with the replay buffer."""
torch.cuda.empty_cache()
self.critic.train()
status = self.trainer.ppo_train()
self.trainer.replay_buffer.clear()
torch.cuda.empty_cache()
torch.cuda.synchronize()
return status | Train critic model with the replay buffer. | fit | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ray/ppo_critic.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ray/ppo_critic.py | Apache-2.0 |
def add_requests(self, sampling_params, prompt_token_ids):
"""
Process requests from rank0 and generate responses.
Since only rank0 will send requests, we don't need to track actor ranks.
"""
from vllm.inputs import TokensPrompt
requests = [TokensPrompt(prompt_token_ids=... |
Process requests from rank0 and generate responses.
Since only rank0 will send requests, we don't need to track actor ranks.
| add_requests | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ray/vllm_engine.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ray/vllm_engine.py | Apache-2.0 |
def batch_vllm_engine_call(engines: List[Any], method_name: str, *args, rank_0_only: bool = True, **kwargs):
"""
Batch call a method on multiple vLLM engines.
Args:
engines: List of vLLM engine instances
method_name: Name of the method to call
rank_0_only: Only execute on rank 0 if T... |
Batch call a method on multiple vLLM engines.
Args:
engines: List of vLLM engine instances
method_name: Name of the method to call
rank_0_only: Only execute on rank 0 if True
*args: Positional arguments to pass to the method
**kwargs: Keyword arguments to pass to the met... | batch_vllm_engine_call | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ray/vllm_engine.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ray/vllm_engine.py | Apache-2.0 |
async def add_requests(self, sampling_params, prompts, labels, max_length, hf_tokenizer=None, max_steps=10000):
"""
Process requests from rank0 and generate responses with multiple agent interactions.
Each prompt will go through multiple steps of interaction using the step function.
Resu... |
Process requests from rank0 and generate responses with multiple agent interactions.
Each prompt will go through multiple steps of interaction using the step function.
Results are streamed back as each agent completes its execution.
Args:
sampling_params: Parameters for sam... | add_requests | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ray/vllm_engine_async.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ray/vllm_engine_async.py | Apache-2.0 |
async def get_responses(self):
"""
Synchronously get all completed agent results from the queue.
Waits for all tasks to complete before returning results.
Returns: List of all completed agent results.
"""
# Get all results from the queue
results = []
while... |
Synchronously get all completed agent results from the queue.
Waits for all tasks to complete before returning results.
Returns: List of all completed agent results.
| get_responses | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ray/vllm_engine_async.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ray/vllm_engine_async.py | Apache-2.0 |
def init_process_group(
self, master_address, master_port, rank_offset, world_size, group_name, backend="nccl", use_ray=False
):
"""Init torch process group for model weights update"""
import torch
from openrlhf.utils.distributed_util import init_process_group
assert torch.d... | Init torch process group for model weights update | init_process_group | python | OpenRLHF/OpenRLHF | openrlhf/trainer/ray/vllm_worker_wrap.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/trainer/ray/vllm_worker_wrap.py | Apache-2.0 |
def set_epoch(self, epoch: int, consumed_samples=0) -> None:
r"""
Set the epoch for this sampler.
When :attr:`shuffle=True`, this ensures all replicas
use a different random ordering for each epoch. Otherwise, the next iteration of this
sampler will yield the same ordering.
... |
Set the epoch for this sampler.
When :attr:`shuffle=True`, this ensures all replicas
use a different random ordering for each epoch. Otherwise, the next iteration of this
sampler will yield the same ordering.
Args:
epoch (int): Epoch number.
| set_epoch | python | OpenRLHF/OpenRLHF | openrlhf/utils/distributed_sampler.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/utils/distributed_sampler.py | Apache-2.0 |
def remove_pad_token(input_ids: torch.Tensor, attention_mask: torch.Tensor):
"""Remove the pad token. Return tensors and not lists.
Args:
input_ids shape: [bs, seq_length]
attention_mask shape: [bs, seq_length]
Returns:
no_padding_batch(List[Tensor[int]]): contains the rmpad token i... | Remove the pad token. Return tensors and not lists.
Args:
input_ids shape: [bs, seq_length]
attention_mask shape: [bs, seq_length]
Returns:
no_padding_batch(List[Tensor[int]]): contains the rmpad token ids per query.
| remove_pad_token | python | OpenRLHF/OpenRLHF | openrlhf/utils/utils.py | https://github.com/OpenRLHF/OpenRLHF/blob/master/openrlhf/utils/utils.py | Apache-2.0 |
def validate_proxy(proxy_str: str) -> bool:
"""Do a simple validation of the http proxy string."""
parsed = urlparse(proxy_str)
if parsed.scheme not in ("http", "https"):
raise ValueError("Proxy scheme must be http or https")
if not (parsed.hostname and parsed.port):
raise ValueError("P... | Do a simple validation of the http proxy string. | validate_proxy | python | yihong0618/xiaogpt | xiaogpt/utils.py | https://github.com/yihong0618/xiaogpt/blob/master/xiaogpt/utils.py | MIT |
async def synthesize(self, lang: str, text_stream: AsyncIterator[str]) -> None:
"""Synthesize speech from a stream of text."""
raise NotImplementedError | Synthesize speech from a stream of text. | synthesize | python | yihong0618/xiaogpt | xiaogpt/tts/base.py | https://github.com/yihong0618/xiaogpt/blob/master/xiaogpt/tts/base.py | MIT |
def Sent2Word(sentence):
"""Turn a sentence into tokenized word list and remove stop-word
Using jieba to tokenize Chinese.
Args:
sentence: A string.
Returns:
words: A tokenized word list.
"""
global stop_words
words = jieba.cut(sentence)
words = [w for w in words if w... | Turn a sentence into tokenized word list and remove stop-word
Using jieba to tokenize Chinese.
Args:
sentence: A string.
Returns:
words: A tokenized word list.
| Sent2Word | python | HUANGZHIHAO1994/weibo-analysis-and-visualization | weibo-analysis-and-visualization/prepro.py | https://github.com/HUANGZHIHAO1994/weibo-analysis-and-visualization/blob/master/weibo-analysis-and-visualization/prepro.py | MIT |
def createDataset(outputPath, imagePathList, labelList, lexiconList=None, checkValid=True):
"""
ARGS:
outputPath : LMDB output path
imagePathList : list of image path
labelList : list of corresponding groundtruth texts
lexiconList : (optional) list of lexicon lists
... |
ARGS:
outputPath : LMDB output path
imagePathList : list of image path
labelList : list of corresponding groundtruth texts
lexiconList : (optional) list of lexicon lists
checkValid : if true, check the validity of every image
| createDataset | python | FudanVI/benchmarking-chinese-text-recognition | data/lmdbMaker.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/data/lmdbMaker.py | MIT |
def __init__(self, h, d_model, dropout=0.1, compress_attention=False):
"Take in model size and number of heads."
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
# We assume d_v always equals d_k
self.d_k = d_model // h
self.h = h
self.linears ... | Take in model size and number of heads. | __init__ | python | FudanVI/benchmarking-chinese-text-recognition | models/ASTER/model/radical_decoder.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/ASTER/model/radical_decoder.py | MIT |
def create(name, *args, **kwargs):
"""Create a model instance.
Parameters
----------
name: str
Model name. One of __factory
pretrained: bool, optional
If True, will use ImageNet pretrained model. Default: True
num_classes: int, optional
If positive, will change the original classifier the fit... | Create a model instance.
Parameters
----------
name: str
Model name. One of __factory
pretrained: bool, optional
If True, will use ImageNet pretrained model. Default: True
num_classes: int, optional
If positive, will change the original classifier the fit the new classifier with num_classes. De... | create | python | FudanVI/benchmarking-chinese-text-recognition | models/ASTER/model/__init__.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/ASTER/model/__init__.py | MIT |
def histo_summary(self, tag, values, step, bins=1000):
"""Log a histogram of the tensor of values."""
# Create a histogram using numpy
counts, bin_edges = np.histogram(values, bins=bins)
# Fill the fields of the histogram proto
hist = tf.HistogramProto()
hist.min = float(np.min(values))
hi... | Log a histogram of the tensor of values. | histo_summary | python | FudanVI/benchmarking-chinese-text-recognition | models/ASTER/utils/logging.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/ASTER/utils/logging.py | MIT |
def make_symlink_if_not_exists(real_path, link_path):
'''
param real_path: str the path linked
param link_path: str the path with only the symbol
'''
try:
os.makedirs(real_path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
cmd = 'ln -s {0} {1}'.format(real_path, link_path)
os.sy... |
param real_path: str the path linked
param link_path: str the path with only the symbol
| make_symlink_if_not_exists | python | FudanVI/benchmarking-chinese-text-recognition | models/ASTER/utils/osutils.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/ASTER/utils/osutils.py | MIT |
def encode(self, text, scanned=True):
"""Support batch or single str.
Args:
text (str or list of str): texts to convert.
Returns:
torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.
torch.IntTensor [n]: length of each text.
"""... | Support batch or single str.
Args:
text (str or list of str): texts to convert.
Returns:
torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.
torch.IntTensor [n]: length of each text.
| encode | python | FudanVI/benchmarking-chinese-text-recognition | models/MORAN/utils.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/MORAN/utils.py | MIT |
def decode(self, t, length):
"""Decode encoded texts back into strs.
Args:
torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.
torch.IntTensor [n]: length of each text.
Raises:
AssertionError: when the texts and its length does not mat... | Decode encoded texts back into strs.
Args:
torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.
torch.IntTensor [n]: length of each text.
Raises:
AssertionError: when the texts and its length does not match.
Returns:
text (... | decode | python | FudanVI/benchmarking-chinese-text-recognition | models/MORAN/utils.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/MORAN/utils.py | MIT |
def get_torch_version():
"""
Find pytorch version and return it as integers
for major and minor versions
"""
torch_version = str(torch.__version__).split(".")
return int(torch_version[0]), int(torch_version[1]) |
Find pytorch version and return it as integers
for major and minor versions
| get_torch_version | python | FudanVI/benchmarking-chinese-text-recognition | models/MORAN/utils.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/MORAN/utils.py | MIT |
def dictionary_generator(alphabet, END='END', PADDING='PAD', UNKNOWN='UNK'):
'''
END: end of sentence token
PADDING: padding token
UNKNOWN: unknown character token
'''
voc = list(alphabet)
# update the voc with 3 specifical chars
voc.append(END)
voc.append(PADDING)
voc.... |
END: end of sentence token
PADDING: padding token
UNKNOWN: unknown character token
| dictionary_generator | python | FudanVI/benchmarking-chinese-text-recognition | models/SAR/main.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/SAR/main.py | MIT |
def forward(self, h, feature_map):
'''
h: hidden state from decoder output, with size [batch, hidden_units]
feature_map: feature map from backbone network, with size [batch, channel, H, W]
'''
# reshape hidden state [batch, hidden_units] to [batch, hidden_units, 1, 1]
h =... |
h: hidden state from decoder output, with size [batch, hidden_units]
feature_map: feature map from backbone network, with size [batch, channel, H, W]
| forward | python | FudanVI/benchmarking-chinese-text-recognition | models/SAR/model/decoder.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/SAR/model/decoder.py | MIT |
def forward(self,hw,y,V):
'''
hw: embedded feature from encoder [batch, hidden_units]
y: ground truth label one hot encoder [batch, seq, output_classes]
V: feature map for backbone network [batch, D, H, W]
'''
outputs = []
attention_weights = []
batch_size... |
hw: embedded feature from encoder [batch, hidden_units]
y: ground truth label one hot encoder [batch, seq, output_classes]
V: feature map for backbone network [batch, D, H, W]
| forward | python | FudanVI/benchmarking-chinese-text-recognition | models/SAR/model/decoder.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/SAR/model/decoder.py | MIT |
def forward(self,x,y,length_radical=None,radical_input=None,test=False):
'''
x: input images [batch, channel, height, width]
y: output labels [batch, seq_len, output_classes]
'''
V = self.backbone(x) # (batch, feature_depth, feature_height, feature_width)
hw = self.encode... |
x: input images [batch, channel, height, width]
y: output labels [batch, seq_len, output_classes]
| forward | python | FudanVI/benchmarking-chinese-text-recognition | models/SAR/model/sar.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/SAR/model/sar.py | MIT |
def attention_map(predict_word, x, attention_weight):
'''
Input:
predict_word: string of predicted word
x: tensor of original image [C, H, W], channel in BGR order, normalized to [-1, 1]
attention_weight: tensor of attention weights [seq_len, 1, feature_H, feature_W] in [0, 1]
Output:
heatma... |
Input:
predict_word: string of predicted word
x: tensor of original image [C, H, W], channel in BGR order, normalized to [-1, 1]
attention_weight: tensor of attention weights [seq_len, 1, feature_H, feature_W] in [0, 1]
Output:
heatmaps: a list of heatmap [H, W, C=3]
overlaps: a list of ove... | attention_map | python | FudanVI/benchmarking-chinese-text-recognition | models/SAR/utils/attention_map.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/SAR/utils/attention_map.py | MIT |
def end_cut(indices, char2id, id2char):
'''
indices: numpy array or list of character indices
charid: char to id conversion
id2char: id to char conversion
'''
cut_indices = []
for id in indices:
if id != char2id['END']:
if id != char2id['UNK'] and id != char2id['PAD']:
... |
indices: numpy array or list of character indices
charid: char to id conversion
id2char: id to char conversion
| end_cut | python | FudanVI/benchmarking-chinese-text-recognition | models/SAR/utils/dataproc.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/SAR/utils/dataproc.py | MIT |
def performance_evaluate(pred_choice, target, voc, char2id, id2char, metrics_type):
'''
pred_choice: predicted numpy array of [batch_size, seq_len] with index in output_classes
target: true numpy array of [batch_size, seq_len] with index in output_classes
voc: vocabular dictionary
charid: char to id... |
pred_choice: predicted numpy array of [batch_size, seq_len] with index in output_classes
target: true numpy array of [batch_size, seq_len] with index in output_classes
voc: vocabular dictionary
charid: char to id conversion
id2char: id to char conversion
metrics_type: evaluation metric name
... | performance_evaluate | python | FudanVI/benchmarking-chinese-text-recognition | models/SAR/utils/dataproc.py | https://github.com/FudanVI/benchmarking-chinese-text-recognition/blob/master/models/SAR/utils/dataproc.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.