Download lib/forge/tournament/score.ex from Snapkitty/forge-code: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/datasets/Snapkitty/forge-code/resolve/main/lib/forge/tournament/score.ex
- Command line
-
hf download hf://datasets/Snapkitty/forge-code/lib/forge/tournament/score.ex
-
curl -L -o score.ex https://huggingface.co/datasets/Snapkitty/forge-code/resolve/main/lib/forge/tournament/score.ex
14 kB
| defmodule Forge.Score do | |
| @moduledoc """ | |
| Score - Multi-dimensional scoring engine for tournament submissions. | |
| This module implements the scoring system for Forge tournaments. It evaluates | |
| submissions across multiple dimensions including correctness, performance, | |
| and structural metrics, with configurable weights. | |
| ## Scoring Dimensions | |
| | Dimension | Weight | Description | | |
| |-----------|--------|-------------| | |
| | Correctness | 1.0 | Must pass all test vectors (gating) | | |
| | Execution Time | Variable | Cold/warm execution metrics | | |
| | Memory Usage | Variable | Process memory consumption | | |
| | Compile Time | Variable | Compilation duration | | |
| | Binary Size | Variable | BEAM file size | | |
| | Instruction Count | Variable | Number of BEAM instructions | | |
| | Function Count | Variable | Number of exported functions | | |
| ## Usage | |
| # Calculate score for a judge result | |
| Forge.Score.calculate(result, dimensions, weights) | |
| # Calculate all scores for tournament results | |
| Forge.Score.calculate_all(tournament_results) | |
| """ | |
| alias Forge.Judge | |
| alias Forge.Beam | |
| @type dimension_name :: :correctness | :execution_time | :memory | :compile_time | | |
| :binary_size | :instruction_count | :function_count | | |
| :constant_count | :complexity | atom() | |
| @type dimension :: %{ | |
| name: dimension_name(), | |
| value: number(), | |
| normalized: number(), | |
| weight: number(), | |
| unit: String.t(), | |
| description: String.t() | |
| } | |
| @type score_result :: %Forge.Score.ScoreResult{ | |
| contestant_id: String.t(), | |
| challenge_id: String.t(), | |
| dimensions: list(dimension()), | |
| total_score: number(), | |
| weight_total: number(), | |
| passed: boolean(), | |
| rank: integer() | nil | |
| } | |
| defstruct [ | |
| :contestant_id, | |
| :challenge_id, | |
| :dimensions, | |
| :total_score, | |
| :weight_total, | |
| :passed, | |
| :rank | |
| ] | |
| @default_weights %{ | |
| correctness: 1.0, | |
| execution_time: 0.3, | |
| memory: 0.2, | |
| compile_time: 0.1, | |
| binary_size: 0.1, | |
| instruction_count: 0.15, | |
| function_count: 0.05, | |
| constant_count: 0.05, | |
| complexity: 0.05 | |
| } | |
| @dimension_units %{ | |
| correctness: "pass/fail", | |
| execution_time: "ms", | |
| memory: "KB", | |
| compile_time: "ms", | |
| binary_size: "bytes", | |
| instruction_count: "instructions", | |
| function_count: "functions", | |
| constant_count: "constants", | |
| complexity: "cyclomatic" | |
| } | |
| @dimension_descriptions %{ | |
| correctness: "All test vectors pass", | |
| execution_time: "Average execution time", | |
| memory: "Peak memory usage", | |
| compile_time: "Compilation duration", | |
| binary_size: "BEAM file size", | |
| instruction_count: "Total BEAM instructions", | |
| function_count: "Number of exported functions", | |
| constant_count: "Number of literals/atoms", | |
| complexity: "Cyclomatic complexity" | |
| } | |
| @doc """ | |
| Calculates scores for all tournament results. | |
| ## Parameters | |
| - results: List of Judge.JudgeResult | |
| - weights: Custom weights (defaults to @default_weights) | |
| - beam_paths: Map of contestant_id to beam_path for binary metrics | |
| ## Returns | |
| - List of ScoreResult | |
| """ | |
| @spec calculate_all(list(Judge.JudgeResult), map(), map()) :: list(ScoreResult) | |
| def calculate_all(results, weights \ @default_weights, beam_paths \ %{}) do | |
| # Group results by contestant and challenge | |
| grouped = Enum.group_by(results, fn r -> {r.contestant_id, r.challenge_id} end) | |
| Enum.map(grouped, fn {_key, result_list} -> | |
| # Take the first result (should be one result per contestant per challenge) | |
| [result | _] = result_list | |
| # Get beam path for this contestant | |
| beam_path = beam_paths[result.contestant_id] | |
| # Calculate dimensions | |
| dimensions = calculate_dimensions(result, beam_path) | |
| # Apply weights | |
| weighted_dimensions = apply_weights(dimensions, weights) | |
| # Calculate total score | |
| {total_score, weight_total} = calculate_total_score(weighted_dimensions, result.passed) | |
| %Forge.Score.ScoreResult{ | |
| contestant_id: result.contestant_id, | |
| challenge_id: result.challenge_id, | |
| dimensions: weighted_dimensions, | |
| total_score: total_score, | |
| weight_total: weight_total, | |
| passed: result.passed, | |
| rank: nil | |
| } | |
| end) | |
| end | |
| @doc """ | |
| Calculates dimensions for a judge result. | |
| """ | |
| defp calculate_dimensions(result, beam_path) do | |
| dimensions = [] | |
| # Correctness (gating dimension - must pass to score well) | |
| correctness_value = if result.passed, do: 1.0, else: 0.0 | |
| dimensions = dimensions ++ [%{ | |
| name: :correctness, | |
| value: correctness_value, | |
| normalized: correctness_value, | |
| weight: 0, | |
| unit: @dimension_units[:correctness], | |
| description: @dimension_descriptions[:correctness] | |
| }] | |
| # Execution time (from result) | |
| if execution_time = result.execution_time do | |
| dimensions = dimensions ++ [%{ | |
| name: :execution_time, | |
| value: execution_time, | |
| normalized: normalize_execution_time(execution_time), | |
| weight: 0, | |
| unit: @dimension_units[:execution_time], | |
| description: @dimension_descriptions[:execution_time] | |
| }] | |
| end | |
| # Memory usage (from result) | |
| if memory = result.memory_used do | |
| dimensions = dimensions ++ [%{ | |
| name: :memory, | |
| value: memory, | |
| normalized: normalize_memory(memory), | |
| weight: 0, | |
| unit: @dimension_units[:memory], | |
| description: @dimension_descriptions[:memory] | |
| }] | |
| end | |
| # Binary metrics (from BEAM file) | |
| if beam_path do | |
| case Beam.read(beam_path) do | |
| {:ok, metadata} -> | |
| # Binary size | |
| dimensions = dimensions ++ [%{ | |
| name: :binary_size, | |
| value: metadata.raw_size, | |
| normalized: normalize_binary_size(metadata.raw_size), | |
| weight: 0, | |
| unit: @dimension_units[:binary_size], | |
| description: @dimension_descriptions[:binary_size] | |
| }] | |
| # Instruction count | |
| dimensions = dimensions ++ [%{ | |
| name: :instruction_count, | |
| value: Beam.instruction_count(beam_path), | |
| normalized: normalize_instruction_count(Beam.instruction_count(beam_path)), | |
| weight: 0, | |
| unit: @dimension_units[:instruction_count], | |
| description: @dimension_descriptions[:instruction_count] | |
| }] | |
| # Function count | |
| dimensions = dimensions ++ [%{ | |
| name: :function_count, | |
| value: Beam.function_count(beam_path), | |
| normalized: normalize_function_count(Beam.function_count(beam_path)), | |
| weight: 0, | |
| unit: @dimension_units[:function_count], | |
| description: @dimension_descriptions[:function_count] | |
| }] | |
| {:error, _} -> | |
| # If we can't read the BEAM file, skip binary metrics | |
| :ok | |
| end | |
| end | |
| dimensions | |
| end | |
| @doc """ | |
| Applies weights to dimensions. | |
| """ | |
| defp apply_weights(dimensions, weights) do | |
| Enum.map(dimensions, fn dim -> | |
| # Get weight, defaulting to 0 if not specified | |
| weight = Map.get(weights, dim.name, 0) | |
| %{dim | weight: weight} | |
| end) | |
| end | |
| @doc """ | |
| Calculates total score from weighted dimensions. | |
| Correctness is special: if it's 0 (failed), the total score is 0 | |
| regardless of other dimensions. | |
| """ | |
| defp calculate_total_score(dimensions, passed) do | |
| # If not passed, total score is 0 (correctness gates everything) | |
| if !passed do | |
| {0.0, 0.0} | |
| else | |
| # Calculate weighted sum | |
| {total, weight_total} = Enum.reduce(dimensions, {0.0, 0.0}, fn dim, {sum, total_weight} -> | |
| # For correctness, it's binary (1 or 0) | |
| if dim.name == :correctness do | |
| {sum + dim.normalized * dim.weight, total_weight + dim.weight} | |
| else | |
| # For other dimensions, smaller values are better (except correctness) | |
| # So we use (1.0 - normalized) for "cost" dimensions | |
| is_cost = dim.name != :correctness | |
| value = if is_cost, do: 1.0 - dim.normalized, else: dim.normalized | |
| {sum + value * dim.weight, total_weight + dim.weight} | |
| end | |
| end) | |
| # Normalize by weight total | |
| if weight_total > 0 do | |
| {total / weight_total, weight_total} | |
| else | |
| {0.0, 0.0} | |
| end | |
| end | |
| end | |
| @doc """ | |
| Normalizes execution time (lower is better). | |
| """ | |
| defp normalize_execution_time(time_ms) do | |
| # Normalize against a baseline (e.g., 100ms = 1.0) | |
| # Using logarithmic scale for better distribution | |
| max_time = 10_000 # 10 seconds | |
| min_time = 0.001 # 1 microsecond | |
| # Clamp the value | |
| clamped = max(min(time_ms, max_time), min_time) | |
| # Logarithmic normalization | |
| # log(clamped) / log(max_time) | |
| # This gives values where fast times get high scores | |
| log_val = :math.log(clamped + 1) # +1 to avoid log(0) | |
| log_max = :math.log(max_time + 1) | |
| # Invert so that smaller values get higher scores | |
| 1.0 - (log_val / log_max) | |
| end | |
| @doc """ | |
| Normalizes memory usage (lower is better). | |
| """ | |
| defp normalize_memory(bytes) do | |
| # Normalize memory in KB | |
| kb = bytes / 1024 | |
| max_memory = 1024 * 1024 # 1 GB | |
| min_memory = 1 # 1 KB | |
| clamped = max(min(kb, max_memory), min_memory) | |
| # Linear normalization | |
| 1.0 - (clamped / max_memory) | |
| end | |
| @doc """ | |
| Normalizes binary size (lower is better). | |
| """ | |
| defp normalize_binary_size(bytes) do | |
| max_size = 10 * 1024 * 1024 # 10 MB | |
| min_size = 1 # 1 byte | |
| clamped = max(min(bytes, max_size), min_size) | |
| # Logarithmic normalization | |
| log_val = :math.log(clamped) | |
| log_max = :math.log(max_size) | |
| 1.0 - (log_val / log_max) | |
| end | |
| @doc """ | |
| Normalizes instruction count (lower is better). | |
| """ | |
| defp normalize_instruction_count(count) do | |
| max_instructions = 100_000 # 100k instructions | |
| min_instructions = 1 | |
| clamped = max(min(count, max_instructions), min_instructions) | |
| # Logarithmic normalization | |
| log_val = :math.log(clamped) | |
| log_max = :math.log(max_instructions) | |
| 1.0 - (log_val / log_max) | |
| end | |
| @doc """ | |
| Normalizes function count (lower is better). | |
| """ | |
| defp normalize_function_count(count) do | |
| max_functions = 1000 | |
| min_functions = 1 | |
| clamped = max(min(count, max_functions), min_functions) | |
| # Linear normalization | |
| 1.0 - (clamped / max_functions) | |
| end | |
| @doc """ | |
| Calculates a single score. | |
| This is a convenience function for calculating a single dimension score. | |
| """ | |
| @spec calculate_single(dimension_name(), number(), number()) :: dimension() | |
| def calculate_single(name, value, weight) do | |
| normalized = normalize_value(name, value) | |
| %{ | |
| name: name, | |
| value: value, | |
| normalized: normalized, | |
| weight: weight, | |
| unit: Map.get(@dimension_units, name, "unknown"), | |
| description: Map.get(@dimension_descriptions, name, "") | |
| } | |
| end | |
| @doc """ | |
| Normalizes a value based on its dimension. | |
| """ | |
| defp normalize_value(name, value) do | |
| case name do | |
| :correctness -> value | |
| :execution_time -> normalize_execution_time(value) | |
| :memory -> normalize_memory(value) | |
| :compile_time -> normalize_execution_time(value) | |
| :binary_size -> normalize_binary_size(value) | |
| :instruction_count -> normalize_instruction_count(value) | |
| :function_count -> normalize_function_count(value) | |
| :constant_count -> normalize_function_count(value) # Similar to function count | |
| :complexity -> normalize_complexity(value) | |
| _ -> 0.5 # Default to middle if unknown | |
| end | |
| end | |
| @doc """ | |
| Normalizes cyclomatic complexity (lower is better). | |
| """ | |
| defp normalize_complexity(value) do | |
| max_complexity = 100 | |
| min_complexity = 1 | |
| clamped = max(min(value, max_complexity), min_complexity) | |
| # Linear normalization | |
| 1.0 - (clamped / max_complexity) | |
| end | |
| @doc """ | |
| Ranks score results (higher score = better rank). | |
| """ | |
| @spec rank_results(list(ScoreResult)) :: list(ScoreResult) | |
| def rank_results(results) do | |
| # Sort by total score descending | |
| sorted = Enum.sort_by(results, &(-&1.total_score)) | |
| # Assign ranks | |
| Enum.map_with_index(sorted, fn result, index -> | |
| %{result | rank: index + 1} | |
| end) | |
| end | |
| @doc """ | |
| Gets the best score for a challenge. | |
| """ | |
| @spec best_for_challenge(list(ScoreResult), String.t()) :: ScoreResult | nil | |
| def best_for_challenge(results, challenge_id) do | |
| Enum.max_by(results, fn | |
| r -> if r.challenge_id == challenge_id && r.passed, do: r.total_score, else: -1.0 | |
| end) | |
| end | |
| @doc """ | |
| Gets the average score across all challenges for a contestant. | |
| """ | |
| @spec average_for_contestant(list(ScoreResult), String.t()) :: number() | nil | |
| def average_for_contestant(results, contestant_id) do | |
| contestant_scores = Enum.filter(results, &(&1.contestant_id == contestant_id && &1.passed)) | |
| if length(contestant_scores) == 0 do | |
| nil | |
| else | |
| total = Enum.reduce(contestant_scores, 0.0, &(&1.total_score + &2)) | |
| total / length(contestant_scores) | |
| end | |
| end | |
| @doc """ | |
| Creates a score summary for display. | |
| """ | |
| @spec summary(ScoreResult) :: String.t() | |
| def summary(score) do | |
| lines = [ | |
| "Score: #{score.contestant_id} / #{score.challenge_id}", | |
| " Passed: #{if score.passed, do: "YES", else: "NO"}", | |
| " Total Score: #{Float.round(score.total_score, 4)}" | |
| ] | |
| Enum.each(score.dimensions, fn dim -> | |
| lines = lines ++ [ | |
| " #{Atom.to_string(dim.name)}: #{Float.round(dim.normalized, 4)} " <> | |
| "(weight: #{dim.weight}, value: #{dim.value} #{dim.unit})" | |
| ] | |
| end) | |
| Enum.join(lines, "\n") | |
| end | |
| end | |