rewards

package
v0.8.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 20, 2024 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CalcTopicRewards

func CalcTopicRewards(args CalcTopicRewardsArgs) (
	topicRewards map[uint64]*alloraMath.Dec,
	err error,
)

Calculates the rewards for each topic.

Calculates rewards per-block based on their weights vs all active topics. Rewards are then calculated per epoch, so topic's epochLength is used to calculate epoch rewards. Uses the current total amount rewardable in treasury as the max reward available to check against. If rewards treasury does not cover the computed rewards for the topics, the distribution is recalculated by distributing the rewards treasury fairly among all topics based on their weight and epoch length. Assumes SumTopicWeights to be nonzero

func CalculateReputerRewardFractions

func CalculateReputerRewardFractions(
	stakes []alloraMath.Dec,
	scores []alloraMath.Dec,
	preward alloraMath.Dec,
) ([]alloraMath.Dec, error)

CalculateReputerRewardFractions calculates the reward fractions for each reputer based on their stakes, scores, and preward parameter. W_im

func CalculateTopicInitialEmaScore

func CalculateTopicInitialEmaScore(
	ctx context.Context,
	keeper keeper.Keeper,
	activeScores []types.Score,
) (alloraMath.Dec, error)

CalculateTopicInitialEmaScore calculates the initial EMA score for new participants in the next epoch using the current active set statistics. The initial score is set below the active set threshold by using the formula: lowestEmaScore - lambda * standardDeviationOfEmaScores

func EmitRewards

func EmitRewards(args EmitRewardsArgs) error

func EnsureAllWorkersPresent

func EnsureAllWorkersPresent(
	values []*types.WorkerAttributedValue,
	allWorkers map[string]struct{},
) []*types.WorkerAttributedValue

ensureAllWorkersPresent checks and adds missing workers with NaN values for a given slice of WorkerAttributedValue

func EnsureAllWorkersPresentWithheld

func EnsureAllWorkersPresentWithheld(
	values []*types.WithheldWorkerAttributedValue,
	allWorkers map[string]struct{},
) []*types.WithheldWorkerAttributedValue

ensureAllWorkersPresentWithheld checks and adds missing workers with NaN values for a given slice of WithheldWorkerAttributedValue

func EnsureWorkerPresence

func EnsureWorkerPresence(reportedLosses types.ReputerValueBundles) types.ReputerValueBundles

Check if all workers are present in the reported losses and add NaN values for missing workers Returns the reported losses adding NaN values for missing workers in uncompleted reported losses

func Entropy

func Entropy(
	rewardFractionsPerActor []alloraMath.Dec,
	numberRatio alloraMath.Dec,
	numParticipants alloraMath.Dec,
	beta alloraMath.Dec,
) (alloraMath.Dec, error)

We define a modified entropy for each class ({F_i, G_i, H_i} for the inference, forecasting, and reputer tasks, respectively Fi = - ∑_j( f_ij * ln(f_ij) * (N_{i,eff} / N_i)^β ) Gi = - ∑_k( f_ik * ln(f_ik) * (N_{f,eff} / N_f)^β ) Hi = - ∑_m( f_im * ln(f_im) * (N_{r,eff} / N_r)^β ) we use beta = 0.25 as a fiducial value

func EntropyForSingleParticipant

func EntropyForSingleParticipant() (alloraMath.Dec, error)

If there's only one worker, entropy should be the default number of 0.173286795139986

func ExtractValues

func ExtractValues(bundle *types.ValueBundle) []alloraMath.Dec

ExtractValues extracts all alloraMath.Dec values from a ValueBundle.

func ForecastingPerformanceScore

func ForecastingPerformanceScore(
	naiveNetworkInferenceLoss,
	networkInferenceLoss alloraMath.Dec,
) (alloraMath.Dec, error)

The performance score of the entire forecasting task T_i is positive if the removal of the forecasting task would increase the network loss, and is negative if its removal would decrease the network loss We subtract the log-loss of the complete network inference (L_i) from that of the naive network (L_i^-), which is obtained by omitting all forecast-implied inferences T_i = log L_i^- - log L_i However we store the log based forms in the keeper so we do not need to take the logs again

func ForecastingUtility

func ForecastingUtility(
	forecastingTaskUtilityScore alloraMath.Dec,
	infererScores []types.Score,
	previousForecasterScoreRatio alloraMath.Dec,
	alpha alloraMath.Dec,
) (alloraMath.Dec, alloraMath.Dec, error)

Implements the utility function for forecasting performance score with the new specification: χ = 0.1 for score < 0, χ = 0.5 for score > 1, χ = 0.4 * score + 0.1 in between

func GenerateForecastScores

func GenerateForecastScores(
	ctx sdk.Context,
	keeper keeper.Keeper,
	topicId uint64,
	block int64,
	networkLosses types.ValueBundle,
) ([]types.Score, error)

GenerateForecastScores calculates and persists scores for workers based on their forecast task performance.

func GenerateInferenceScores

func GenerateInferenceScores(
	ctx sdk.Context,
	keeper keeper.Keeper,
	topicId uint64,
	block int64,
	networkLosses types.ValueBundle,
) ([]types.Score, error)

GenerateInferenceScores calculates and persists scores for workers based on their inference task performance.

func GenerateReputerScores

func GenerateReputerScores(
	ctx sdk.Context,
	keeper keeper.Keeper,
	topicId uint64,
	block int64,
	reportedLosses types.ReputerValueBundles,
) ([]types.Score, error)

GenerateReputerScores calculates and persists scores for reputers based on their reported losses.

func GenerateRewardsDistributionByTopicParticipant

func GenerateRewardsDistributionByTopicParticipant(
	args GenerateRewardsDistributionByTopicParticipantArgs) (
	totalRewardsDistribution []types.TaskReward,
	taskReputerReward alloraMath.Dec,
	err error,
)

Calculates distribution of rewards to topic participants. Retrieves the reputer and network loss bundles. It then calculates and sets the reputer, inferer, and forecaster scores, then returning reward distributions

func GetAdjustedStake

func GetAdjustedStake(
	stake alloraMath.Dec,
	allStakes []alloraMath.Dec,
	listeningCoefficient alloraMath.Dec,
	allListeningCoefficients []alloraMath.Dec,
	numReputers alloraMath.Dec,
) (alloraMath.Dec, error)

Adjusted stake for calculating consensus S hat ^S_im = min((N_r * a_im * S_im)/(Σ_m(a_im * S_im)), 1) INPUTS: This function expects that allStakes (S_im) and allListeningCoefficients are slices of the same length (a_im) and the index to each slice corresponds to the same reputer

func GetAllConsensusScores

func GetAllConsensusScores(
	allLosses [][]alloraMath.Dec,
	stakes []alloraMath.Dec,
	allListeningCoefficients []alloraMath.Dec,
	numReputers int64,
	epsilonReputer alloraMath.Dec,
	epsilon alloraMath.Dec,
) ([]alloraMath.Dec, error)

GetAllConsensusScores calculates the proximity to consensus score for all reputers. calculates: T_i - stake weighted total consensus returns: T_im - reputer score (proximity to consensus)

func GetAllReputersOutput

func GetAllReputersOutput(
	allLosses [][]alloraMath.Dec,
	stakes []alloraMath.Dec,
	initialCoefficients []alloraMath.Dec,
	numReputers int64,
	params types.Params,
) ([]alloraMath.Dec, []alloraMath.Dec, error)

GetAllReputersOutput calculates the final scores and adjusted listening coefficients for all reputers. This function iteratively adjusts the listening coefficients based on a gradient descent method to minimize the difference between each reputer's losses and the consensus losses, taking into account each reputer's stake. returns: T_im - reputer score (proximity to consensus) a_im - listening coefficients

func GetAndUpdateActiveTopicWeights

func GetAndUpdateActiveTopicWeights(
	ctx sdk.Context,
	k keeper.Keeper,
	block BlockHeight,
) (
	weights map[TopicId]*alloraMath.Dec,
	sumWeight alloraMath.Dec,
	totalRevenue cosmosMath.Int,
	err error,
)

Iterates through every active topic, computes its target weight, then exponential moving average to get weight. Returns the total sum of weight, topic revenue, map of all of the weights by topic. Note that the outputted weights are not normalized => not dependent on pan-topic data.

func GetChiAndGamma

func GetChiAndGamma(
	naiveNetworkInferenceLoss,
	networkInferenceLoss,
	entropyInference,
	entropyForecasting alloraMath.Dec,
	infererScores []types.Score,
	previousForecasterScoreRatio alloraMath.Dec,
	alpha alloraMath.Dec,
) (alloraMath.Dec, alloraMath.Dec, alloraMath.Dec, alloraMath.Dec, error)

helper function to get chi and gamma

func GetConsensusScore

func GetConsensusScore(
	reputerLosses,
	consensusLosses,
	mostDistantValues []alloraMath.Dec,
	epsilonReputer alloraMath.Dec,
	epsilon alloraMath.Dec,
) (alloraMath.Dec, error)

GetConsensusScore calculates the proximity to consensus score for a reputer. T_im

func GetFinalWorkerPerformanceScore

func GetFinalWorkerPerformanceScore(
	scoreOneIn,
	scoreOneOut,
	fUniqueAgg alloraMath.Dec,
) (alloraMath.Dec, error)

GetFinalWorkerPerformanceScore calculates the worker performance score. T_ik

func GetForecastTaskEntropy

func GetForecastTaskEntropy(
	ctx sdk.Context,
	k keeper.Keeper,
	topicId uint64,
	emaAlpha alloraMath.Dec,
	betaEntropy alloraMath.Dec,
	workers []string,
	workersFractions []alloraMath.Dec,
) (
	entropy alloraMath.Dec,
	err error,
)

func GetForecastingTaskRewardFractions

func GetForecastingTaskRewardFractions(
	ctx sdk.Context,
	k keeper.Keeper,
	topicId uint64,
	blockHeight int64,
	pReward alloraMath.Dec,
	cReward alloraMath.Dec,
	latestScores []types.Score,
) ([]string, []alloraMath.Dec, error)

func GetInferenceTaskEntropy

func GetInferenceTaskEntropy(
	ctx sdk.Context,
	k keeper.Keeper,
	topicId uint64,
	emaAlpha alloraMath.Dec,
	betaEntropy alloraMath.Dec,
	workers []string,
	workersFractions []alloraMath.Dec,
) (
	entropy alloraMath.Dec,
	err error,
)

func GetInferenceTaskRewardFractions

func GetInferenceTaskRewardFractions(
	ctx sdk.Context,
	k keeper.Keeper,
	topicId uint64,
	blockHeight int64,
	pReward alloraMath.Dec,
	cReward alloraMath.Dec,
	latestScores []types.Score,
) ([]string, []alloraMath.Dec, error)

func GetMappingFunctionValues

func GetMappingFunctionValues(
	latestWorkerScores []alloraMath.Dec,
	latestTimeStepsScores []alloraMath.Dec,
	pReward alloraMath.Dec,
	cReward alloraMath.Dec,
	epsilon alloraMath.Dec,
) ([]alloraMath.Dec, error)

Mapping function used by score fraction calculation M(T) = φ_p (T / (σ(T) + ɛ)) phi is the phi function sigma is NOT the sigma function but rather represents standard deviation

func GetReputerTaskEntropy

func GetReputerTaskEntropy(
	ctx sdk.Context,
	k keeper.Keeper,
	topicId uint64,
	emaAlpha alloraMath.Dec,
	betaEntropy alloraMath.Dec,
	reputers []string,
	reputerFractions []alloraMath.Dec,
) (
	entropy alloraMath.Dec,
	err error,
)

func GetReputersRewardFractions

func GetReputersRewardFractions(
	ctx sdk.Context,
	k keeper.Keeper,
	topicId uint64,
	pReward alloraMath.Dec,
	scoresAtBlock []types.Score,
) ([]string, []alloraMath.Dec, error)

func GetRewardForForecastingTaskInTopic

func GetRewardForForecastingTaskInTopic(
	entropyInference alloraMath.Dec,
	entropyForecasting alloraMath.Dec,
	entropyReputer alloraMath.Dec,
	totalReward *alloraMath.Dec,
	chi alloraMath.Dec,
	gamma alloraMath.Dec,
) (alloraMath.Dec, error)

forecaster rewards calculation V_i = (χ * γ * G_i * E_i) / (F_i + G_i + H_i)

func GetRewardForInferenceTaskInTopic

func GetRewardForInferenceTaskInTopic(
	entropyInference alloraMath.Dec,
	entropyForecasting alloraMath.Dec,
	entropyReputer alloraMath.Dec,
	totalReward *alloraMath.Dec,
	chi alloraMath.Dec,
	gamma alloraMath.Dec,
) (alloraMath.Dec, error)

inference rewards calculation U_i = ((1 - χ) * γ * F_i * E_i ) / (F_i + G_i + H_i)

func GetRewardForReputerFromTotalReward

func GetRewardForReputerFromTotalReward(
	ctx sdk.Context,
	keeper keeper.Keeper,
	topicId uint64,
	reputerDelegatorRewards []types.TaskReward,
) ([]types.TaskReward, error)

Send total reward for delegator to PENDING_ACCOUNT and return remain reward for reputer

func GetRewardForReputerTaskInTopic

func GetRewardForReputerTaskInTopic(
	entropyInference alloraMath.Dec,
	entropyForecasting alloraMath.Dec,
	entropyReputer alloraMath.Dec,
	topicReward *alloraMath.Dec,
) (alloraMath.Dec, error)

Get the reward allocated to the reputing task in this topic, W_i W_i = (H_i * E_i) / (F_i + G_i + H_i)

func GetRewardPerReputer

func GetRewardPerReputer(
	ctx sdk.Context,
	keeper keeper.Keeper,
	topicId uint64,
	totalReputerRewards alloraMath.Dec,
	reputerAddresses []string,
	reputersFractions []alloraMath.Dec,
) ([]types.TaskReward, error)

Get reward per reputer based on total reputer rewards and reputer fractions W_im = w_ij * W_i

func GetRewardPerWorker

func GetRewardPerWorker(
	topicId uint64,
	taskRewardType types.TaskRewardType,
	totalRewards alloraMath.Dec,
	workerAddresses []string,
	workerFractions []alloraMath.Dec,
) ([]types.TaskReward, error)

GetRewardPerWorker calculates the reward for workers for forecast and inference tasks U_ij = u_ij * Ui, V_ik = v_ik * Vi

func GetScoreFractions

func GetScoreFractions(
	latestWorkerScores []alloraMath.Dec,
	latestTimeStepsScores []alloraMath.Dec,
	pReward alloraMath.Dec,
	cReward alloraMath.Dec,
	epsilon alloraMath.Dec,
) ([]alloraMath.Dec, error)

RewardFractions without multiplication against total rewards are used to calculate entropy note the use of lowercase u as opposed to capital u_ij = M(Tij) / ∑_j M(T_ij) v_ik = M(Tik) / ∑_k M(T_ik)

func GetStakeWeightedLoss

func GetStakeWeightedLoss(reputersStakes, reputersReportedLosses []alloraMath.Dec) (alloraMath.Dec, error)

GetStakeWeightedLoss calculates the stake-weighted average loss. Consider the losses and the stake of each reputer to calculate the stake-weighted loss. The stake weighted loss is used to calculate the network-wide losses. L_i / L_ij / L_ik / L^-_i / L^-_il / L^+_ik

func GetStakeWeightedLossMatrix

func GetStakeWeightedLossMatrix(
	reputersAdjustedStakes []alloraMath.Dec,
	reputersReportedLosses [][]alloraMath.Dec,
) ([]alloraMath.Dec, []alloraMath.Dec, error)

GetStakeWeightedLossMatrix calculates the stake-weighted geometric mean of the losses to generate the consensus vector. L_i - consensus loss vector

func GetTopicReward

func GetTopicReward(
	topicRewardFraction alloraMath.Dec,
	totalReward alloraMath.Dec,
) (alloraMath.Dec, error)

The amount of emission rewards to be distributed to a topic E_{t,i} = f_{t,i}*E_i f_{t,i} is the reward fraction for that topic E_i is the reward emission total for that epoch

func GetTopicRewardFraction

func GetTopicRewardFraction(

	topicWeight *alloraMath.Dec,
	totalWeight alloraMath.Dec,
) (alloraMath.Dec, error)

The reward fraction for a topic normalize the topic reward weight f{t,i} = (1 - f_v) * (w_{t,i}) / (∑_t w_{t,i}) where f_v is a global parameter set that controls the fraction of total reward emissions for cosmos network validators we don't use f_v here, because by the time the emissions module runs the validator rewards have already been distributed to the fee_collector account (this is done in the mint and then distribution module) w_{t,i} is the weight of topic t and the sum is naturally the total of all the weights for all topics

func GetfUniqueAgg

func GetfUniqueAgg(numForecasters alloraMath.Dec) (alloraMath.Dec, error)

GetfUniqueAgg calculates the unique value or impact of each forecaster. ƒ^+

func Logger

func Logger(ctx sdk.Context) log.Logger

func ModifiedRewardFractions

func ModifiedRewardFractions(rewardFractions []alloraMath.Dec) ([]alloraMath.Dec, error)

f_ij, f_ik, and f_im are all reward fractions that require computing the ratio of one participant to all participants yes this is extremely simple math yes we write a separate function for it anyway. The compiler can inline it if necessary normalizeToArray = value / sum(allValues) this covers equations f_ij = (̃U_ij) / ∑_j(̃Uij) f_ik = (̃Vik) / ∑_k(̃Vik) f_im = (̃Wim) / ∑_m(̃Wim)

func NormalizationFactor

func NormalizationFactor(
	entropyInference alloraMath.Dec,
	entropyForecasting alloraMath.Dec,
	forecastingUtility alloraMath.Dec,
) (alloraMath.Dec, error)

renormalize with a factor γ to ensure that the total reward allocated to workers (Ui + Vi) remains constant (otherwise, this would go at the expense of reputers) γ = (F_i + G_i) / ( (1 − χ)*F_i + χ*G_i)

func NumberRatio

func NumberRatio(rewardFractions []alloraMath.Dec) (alloraMath.Dec, error)

The number ratio term captures the number of participants in the network to prevent sybil attacks in the rewards distribution This function captures N_{i,eff} = 1 / ∑_j( f_ij^2 ) N_{f,eff} = 1 / ∑_k( f_ik^2 ) N_{r,eff} = 1 / ∑_m( f_im^2 )

func PruneReputerAndWorkerNonces

func PruneReputerAndWorkerNonces(ctx sdk.Context, k keeper.Keeper, topic types.Topic, block BlockHeight) error

Prune reputer and worker nonces

func Sigmoid

func Sigmoid(x alloraMath.Dec) (alloraMath.Dec, error)

sigmoid function σ(x) = 1/(1+e^{-x}) = e^x/(1+e^x)

func UpdateNoncesOfActiveTopics

func UpdateNoncesOfActiveTopics(
	ctx sdk.Context,
	k keeper.Keeper,
	block BlockHeight,
	weights map[TopicId]*alloraMath.Dec,
) error

At the end of epoch, we should update nonce status of active topics, skim the top N by weight. Update worker/reputer nonces, also add reward topic nonce to get reward for this nonce.

func UpdateReputerNonce

func UpdateReputerNonce(ctx sdk.Context, k keeper.Keeper, topic types.Topic, block BlockHeight) error

Update unfullfilled reputer nonces for topic

Types

type BlockHeight

type BlockHeight = int64

type CalcTopicRewardsArgs

type CalcTopicRewardsArgs struct {
	Ctx                             sdk.Context
	Weights                         map[uint64]*alloraMath.Dec // weights of all active topics in this block
	SortedTopics                    []uint64                   // topics sorted by weight in descending order
	SumTopicWeights                 alloraMath.Dec             // sum of all active topic weights
	TotalAvailableInRewardsTreasury alloraMath.Dec             // Maximum amount of rewards available in treasury
	EpochLengths                    map[uint64]int64           // epoch lengths for each topic
	CurrentRewardsEmissionPerBlock  alloraMath.Dec             // Rewards emission per block
}

type EmitRewardsArgs

type EmitRewardsArgs struct {
	Ctx          sdk.Context
	K            keeper.Keeper
	ModuleParams types.Params
	BlockHeight  BlockHeight
	Weights      map[uint64]*alloraMath.Dec
	SumWeight    alloraMath.Dec
	TotalRevenue cosmosMath.Int
}

type GenerateRewardsDistributionByTopicParticipantArgs

type GenerateRewardsDistributionByTopicParticipantArgs struct {
	Ctx          sdk.Context
	K            keeper.Keeper
	TopicId      uint64
	TopicReward  *alloraMath.Dec
	BlockHeight  int64
	ModuleParams types.Params
}

type GetDistributionAndPayoutRewardsToTopicActorsArgs

type GetDistributionAndPayoutRewardsToTopicActorsArgs struct {
	Ctx              sdk.Context
	K                keeper.Keeper
	TopicId          uint64
	TopicRewardNonce int64
	TopicReward      *alloraMath.Dec
	ModuleParams     types.Params
}

type SortableTopicId

type SortableTopicId struct {
	Value      TopicId
	Weight     *alloraMath.Dec
	Tiebreaker uint32
}

A structure to hold the original value and a random tiebreaker

type TopicId

type TopicId = uint64

func SkimTopTopicsByWeightDesc

func SkimTopTopicsByWeightDesc(ctx sdk.Context, weights map[TopicId]*alloraMath.Dec, N uint64, block BlockHeight) (map[TopicId]*alloraMath.Dec, []TopicId, error)

Returns a map of topicId to weights of the top N topics by weight in descending order It is assumed that topicIds is of a reasonable size, throttled by perhaps MaxTopicsPerBlock global param

func SortTopicsByWeightDescWithRandomTiebreaker

func SortTopicsByWeightDescWithRandomTiebreaker(topicIds []TopicId, weights map[TopicId]*alloraMath.Dec, randSeed BlockHeight) ([]TopicId, error)

Sorts the given slice of topics in descending order according to their corresponding return, using pseudorandom tiebreaker e.g. ([]uint64{1, 2, 3}, map[uint64]uint64{1: 2, 2: 2, 3: 3}, 0) -> [3, 1, 2] or [3, 2, 1]

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL