-
Notifications
You must be signed in to change notification settings - Fork 5
added ai2thor enviroment with a method that proposes steps and uses C… #280
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Vman11
wants to merge
4
commits into
main
Choose a base branch
from
ai2thor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from align_system.algorithms.abstracts import ADMComponent | ||
| from align_system.utils import logging | ||
|
|
||
| log = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class ArgmaxAlignmentADMComponent(ADMComponent): | ||
| """ | ||
| Alignment step that picks the choice with the highest predicted | ||
| KDMA score, averaged across all attributes and samples. | ||
|
|
||
| Replaces the ADEPT random effects model for domains (like AI2Thor) | ||
| where no calibrated statistical model exists. For single-attribute | ||
| pipelines this reduces to a plain argmax over the LLM's scores. | ||
| """ | ||
|
|
||
| def __init__(self, attributes=None): | ||
| self.attributes = attributes or {} | ||
|
|
||
| def run_returns(self): | ||
| return ("chosen_choice", "best_sample_idx", "alignment_info") | ||
|
|
||
| def run(self, attribute_prediction_scores, alignment_target=None): | ||
| """ | ||
| attribute_prediction_scores: dict[choice_str, dict[kdma, list[float]]] | ||
| """ | ||
| choice_totals: dict[str, float] = {} | ||
|
|
||
| for choice, attr_scores in attribute_prediction_scores.items(): | ||
| total = 0.0 | ||
| count = 0 | ||
| for kdma, scores in attr_scores.items(): | ||
| vals = scores if isinstance(scores, list) else [scores] | ||
| if vals: | ||
| total += sum(vals) / len(vals) | ||
| count += 1 | ||
| choice_totals[choice] = total / count if count else 0.0 | ||
|
|
||
| best_choice = max(choice_totals, key=choice_totals.get) | ||
|
|
||
| log.info(f"[ArgmaxAlignment] scores: {choice_totals}") | ||
| log.info(f"[ArgmaxAlignment] chosen: {best_choice}") | ||
|
|
||
| alignment_info = { | ||
| "source": type(self).__name__, | ||
| "choice_scores": choice_totals, | ||
| } | ||
|
|
||
| return best_choice, 0, alignment_info |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
|
|
||
| import ollama | ||
|
|
||
| from align_system.algorithms.abstracts import StructuredInferenceEngine | ||
| from align_system.utils import logging | ||
|
|
||
| log = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class OllamaInferenceEngine(StructuredInferenceEngine): | ||
| """ | ||
| StructuredInferenceEngine backed by a local Ollama model. | ||
|
|
||
| Uses Ollama's native structured output support | ||
| (https://ollama.com/blog/structured-outputs): the JSON schema is | ||
| passed as the `format` parameter so the server constrains the | ||
| output to match the schema. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| model: str = "gemma4:12b", | ||
| temperature: float = 0.0, | ||
| num_ctx: int = 8192, | ||
| num_predict: int = 4096, | ||
| max_retries: int = 2, | ||
| ): | ||
| self.model = model | ||
| self.temperature = temperature | ||
| self.num_ctx = num_ctx | ||
| self.num_predict = num_predict | ||
| self.max_retries = max_retries | ||
|
|
||
| def dialog_to_prompt(self, dialog) -> str: | ||
| """ | ||
| Flatten a dialog list into a plain-text prompt for Ollama. | ||
|
|
||
| System messages are prepended as an unlabelled block so they | ||
| land at the top; user/assistant turns follow with role labels. | ||
| """ | ||
| system_parts = [] | ||
| turn_parts = [] | ||
|
|
||
| for elem in dialog: | ||
| role = elem.role if hasattr(elem, "role") else elem["role"] | ||
| content = elem.content if hasattr(elem, "content") else elem["content"] | ||
|
|
||
| if role == "system": | ||
| system_parts.append(content) | ||
| else: | ||
| turn_parts.append(f"[{role.upper()}]\n{content}") | ||
|
|
||
| parts = [] | ||
| if system_parts: | ||
| parts.append("\n\n".join(system_parts)) | ||
| parts.extend(turn_parts) | ||
| return "\n\n".join(parts) | ||
|
|
||
| def run_inference(self, prompts, schema: str, temperature: float = None): | ||
| """ | ||
| Run inference for each prompt string and return parsed JSON dicts. | ||
|
|
||
| `schema` is a JSON Schema string passed to Ollama's `format` | ||
| parameter for server-side constrained generation. | ||
| """ | ||
| format_schema = json.loads(schema) | ||
| effective_temperature = self.temperature if temperature is None else temperature | ||
|
|
||
| if single_prompt := isinstance(prompts, str): | ||
| prompts = [prompts] | ||
|
|
||
| results = [] | ||
| for prompt in prompts: | ||
| for attempt in range(self.max_retries + 1): | ||
| # On retries, sample with some temperature so a greedy | ||
| # engine doesn't just reproduce the same bad output | ||
| retry_temperature = (effective_temperature if attempt == 0 | ||
| else max(effective_temperature, 0.2)) | ||
| resp = ollama.generate( | ||
| model=self.model, | ||
| prompt=prompt, | ||
| format=format_schema, | ||
| options={"temperature": retry_temperature, | ||
| "num_ctx": self.num_ctx, | ||
| "num_predict": self.num_predict}, | ||
| ) | ||
| text = resp["response"] | ||
| log.debug(f"[OllamaInferenceEngine] raw response:\n{text}") | ||
|
|
||
| try: | ||
| results.append(self._parse_json_response(text)) | ||
| break | ||
| except (json.JSONDecodeError, RuntimeError) as e: | ||
| if attempt == self.max_retries: | ||
| raise | ||
| log.warning(f"[OllamaInferenceEngine] failed to parse " | ||
| f"response (attempt {attempt + 1} of " | ||
| f"{self.max_retries + 1}): {e}; retrying") | ||
|
|
||
| return results[0] if single_prompt else results | ||
|
|
||
| @staticmethod | ||
| def _parse_json_response(text: str): | ||
| """ | ||
| Parse the first JSON value in the response, tolerating trailing | ||
| garbage (some models emit extra text after the schema-constrained | ||
| JSON despite the `format` parameter). | ||
| """ | ||
| stripped = text.strip() | ||
| if not stripped: | ||
| raise RuntimeError( | ||
| "Ollama returned an empty response; the model may not " | ||
| "support structured output via the `format` parameter") | ||
|
|
||
| obj, end = json.JSONDecoder().raw_decode(stripped) | ||
| trailing = stripped[end:].strip() | ||
| if trailing: | ||
| log.warning(f"[OllamaInferenceEngine] ignoring trailing data " | ||
| f"after JSON response: {trailing[:100]!r}") | ||
| return obj | ||
|
|
||
| def cache_repr(self) -> str: | ||
| return ( | ||
| f"OllamaInferenceEngine(model={self.model}, " | ||
| f"temperature={self.temperature}, num_ctx={self.num_ctx})" | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it's fine to have the history tracking as you have it in here for now, but I'm more inclined to merge Yoni's approach on this: https://github.com/ITM-Kitware/align-system/pull/277/changes#diff-ea512e45fac46d4935ce85a4837bdbcd27b5891a09c1ac5f6aad038076f4d497
As it maintains the full working_output history.