rewards

package
v0.1.0-dev.a53b6d4 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var TASK_FORECAST = true
View Source
var TASK_INFERENCE = false

Functions

func CalcTopicRewards

func CalcTopicRewards(
	ctx sdk.Context,
	k keeper.Keeper,
	weights map[uint64]*alloraMath.Dec,
	sumWeight alloraMath.Dec,
	totalReward alloraMath.Dec,
) (
	map[uint64]*alloraMath.Dec,
	error,
)

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 EmitRewards

func EmitRewards(ctx sdk.Context, k keeper.Keeper, blockHeight BlockHeight, weights map[uint64]*alloraMath.Dec, sumWeight math.Dec, totalRevenue cosmosMath.Int) 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 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.17328679513998632 ln(2)/4

func ExtractValues

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

ExtractValues extracts all alloraMath.Dec values from a ValueBundle.

func FilterAndInactivateTopicsUpdatingSums

func FilterAndInactivateTopicsUpdatingSums(
	ctx sdk.Context,
	k keeper.Keeper,
	weights map[uint64]*alloraMath.Dec,
	sumWeight alloraMath.Dec,
	sumRevenue cosmosMath.Int,
	totalReward alloraMath.Dec,
	blockHeight BlockHeight,
) (
	map[uint64]*alloraMath.Dec,
	alloraMath.Dec,
	cosmosMath.Int,
	error,
)

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,
	a,
	b alloraMath.Dec,
) (alloraMath.Dec, error)

we apply a utility function to the forecasting performance score to let the forecasting task utility range from the interval [0.1, 0.5] χ = 0.1 + 0.4σ(a*T_i − b) sigma is the sigmoid function a has fiduciary value of 8 b has fiduciary value of 0.5

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 GenerateRewardsDistributionByTopic

func GenerateRewardsDistributionByTopic(
	ctx sdk.Context,
	k keeper.Keeper,
	maxTopicsPerBlock uint64,
	blockHeight BlockHeight,
	totalReward alloraMath.Dec,
	weights map[uint64]*math.Dec,
	sumWeight math.Dec,
	totalRevenue cosmosMath.Int,
) (map[uint64]*alloraMath.Dec, error)

func GetAdjustedStake

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

Adjusted stake for calculating consensus S hat ^S_im = 1 - ϕ_1^−1(η) * ϕ1[ −η * (((N_r * a_im * S_im) / (Σ_m(a_im * S_im))) − 1 )] we use eta = 20 as the fiducial value decided in the paper phi_1 refers to the phi function with p = 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,
	sharpness 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,
	learningRate alloraMath.Dec,
	sharpness alloraMath.Dec,
	gradientDescentMaxIters uint64,
) ([]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 GetAndOptionallyUpdateActiveTopicWeights

func GetAndOptionallyUpdateActiveTopicWeights(
	ctx context.Context,
	k keeper.Keeper,
	block BlockHeight,
	updatePreviousWeights bool,
) (
	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. updatePrevious is a flag to perform update of previous weight of the topic

func GetConsensusScore

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

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

func GetFinalWorkerScoreForecastTask added in v0.2.6

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

GetFinalWorkerScoreForecastTask calculates the worker score in forecast task. T_ik

func GetForecastingTaskEntropy added in v0.2.6

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

func GetForecastingTaskRewardFractions

func GetForecastingTaskRewardFractions(
	ctx sdk.Context,
	k keeper.Keeper,
	topicId uint64,
	blockHeight int64,
	pRewardSpread alloraMath.Dec,
	actualNetworkLoss *types.ValueBundle,
) ([]sdk.AccAddress, []alloraMath.Dec, error)

func GetInferenceTaskEntropy

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

func GetInferenceTaskRewardFractions

func GetInferenceTaskRewardFractions(
	ctx sdk.Context,
	k keeper.Keeper,
	topicId uint64,
	blockHeight int64,
	pRewardSpread alloraMath.Dec,
	actualNetworkLoss *types.ValueBundle,
) ([]sdk.AccAddress, []alloraMath.Dec, error)

func GetMappingFunctionValues

func GetMappingFunctionValues(
	latestWorkerScores []alloraMath.Dec,
	latestTimeStepsScores []alloraMath.Dec,
	pReward 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 []sdk.AccAddress,
	reputerFractions []alloraMath.Dec,
) (
	entropy alloraMath.Dec,
	err error,
)

func GetReputersRewardFractions

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

func GetRewardForForecastingTaskInTopic

func GetRewardForForecastingTaskInTopic(
	niaveNetworkInferenceLoss alloraMath.Dec,
	networkInferenceLoss alloraMath.Dec,
	entropyInference alloraMath.Dec,
	entropyForecasting alloraMath.Dec,
	entropyReputer alloraMath.Dec,
	totalReward *alloraMath.Dec,
	sigmoidA alloraMath.Dec,
	sigmoidB alloraMath.Dec,
) (alloraMath.Dec, error)

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

func GetRewardForInferenceTaskInTopic

func GetRewardForInferenceTaskInTopic(
	naiveNetworkInferenceLoss alloraMath.Dec,
	networkInferenceLoss alloraMath.Dec,
	entropyInference alloraMath.Dec,
	entropyForecasting alloraMath.Dec,
	entropyReputer alloraMath.Dec,
	totalReward *alloraMath.Dec,
	a alloraMath.Dec,
	b alloraMath.Dec,
) (alloraMath.Dec, error)

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

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 GetScoreFractions

func GetScoreFractions(
	latestWorkerScores []alloraMath.Dec,
	latestTimeStepsScores []alloraMath.Dec,
	pReward 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 GetWorkerScore

func GetWorkerScore(losses, lossesOneOut alloraMath.Dec) (alloraMath.Dec, error)

GetWorkerScore calculates the worker score based on the losses and lossesCut. Consider the staked weighted inference loss and one-out loss to calculate the worker score. T_ij / T^-_ik / T^+_ik

func GetWorkersRewardFractions added in v0.2.6

func GetWorkersRewardFractions(
	ctx sdk.Context,
	k keeper.Keeper,
	topicId uint64,
	blockHeight int64,
	which bool,
	pRewardSpread alloraMath.Dec,
	actualNetworkLoss *types.ValueBundle,
) ([]sdk.AccAddress, []alloraMath.Dec, error)

func GetfUniqueAgg

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

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

func IdentifyChurnableAmongActiveTopicsAndApplyFn added in v0.2.6

func IdentifyChurnableAmongActiveTopicsAndApplyFn(
	ctx context.Context,
	k keeper.Keeper,
	block BlockHeight,
	fn func(ctx context.Context, topic *types.Topic) error,
	weights map[TopicId]*alloraMath.Dec,
) error

"Churn-ready topic" is active, has an epoch that ended, and is in top N by weights, has non-zero weight. We iterate through active topics, fetch their weight, skim the top N by weight (these are the churnable topics) then finally apply a function on each of these churnable topics.

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 Phi

func Phi(p, x alloraMath.Dec) (alloraMath.Dec, error)

Implements the potential function phi for the module this is equation 6 from the litepaper: ϕ_p(x) = (ln(1 + e^x))^p

func SafeApplyFuncOnAllActiveTopics

func SafeApplyFuncOnAllActiveTopics(
	ctx context.Context,
	k keeper.Keeper,
	block BlockHeight,
	fn func(ctx context.Context, topic *types.Topic) error,
	topicPageLimit uint64,
	maxTopicPages uint64,
) error

Active topics have more than a globally-set minimum weight, a function of revenue and stake "Safe" because bounded by max number of pages and apply running, online operations

func Sigmoid

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

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

func SkimTopTopicsByWeightDesc

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

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 StdDev

func StdDev(data []alloraMath.Dec) (alloraMath.Dec, error)

StdDev calculates the standard deviation of a slice of `alloraMath.Dec` stdDev = sqrt((Σ(x - μ))^2/ N) where μ is mean and N is number of elements

Types

type BlockHeight

type BlockHeight = int64

type SortableTopicId

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

A structure to hold the original value and a random tiebreaker

type TaskRewardType

type TaskRewardType int
const (
	ReputerRewardType TaskRewardType = iota // iota resets to 0 for the first constant in the block.
	WorkerInferenceRewardType
	WorkerForecastRewardType
)

type TaskRewards

type TaskRewards struct {
	Address sdk.AccAddress
	Reward  alloraMath.Dec
	TopicId TopicId
	Type    TaskRewardType
}

func GenerateRewardsDistributionByTopicParticipant

func GenerateRewardsDistributionByTopicParticipant(
	ctx sdk.Context,
	k keeper.Keeper,
	topicId uint64,
	topicReward *alloraMath.Dec,
	blockHeight int64,
	moduleParams types.Params,
) (
	[]TaskRewards, error,
)

func GetRewardForReputerFromTotalReward

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

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

func GetRewardPerReputer

func GetRewardPerReputer(
	ctx sdk.Context,
	keeper keeper.Keeper,
	topicId uint64,
	totalReputerRewards alloraMath.Dec,
	reputerAddresses []sdk.AccAddress,
	reputersFractions []alloraMath.Dec,
) ([]TaskRewards, 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 TaskRewardType,
	totalRewards alloraMath.Dec,
	workerAddresses []sdk.AccAddress,
	workerFractions []alloraMath.Dec,
) ([]TaskRewards, error)

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

type TopicId

type TopicId = uint64

func SortTopicsByWeightDescWithRandomTiebreaker

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

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