Skip to content

Remote LLM engine - #423

Open
Enkidu93 wants to merge 3 commits into
mainfrom
remote-llm-engine
Open

Enkidu93 wants to merge 3 commits into
mainfrom
remote-llm-engine

Conversation

@Enkidu93

@Enkidu93 Enkidu93 commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Resolves #400.

(If you're seeing this and wondering why I haven't asked for your review, I'll let Claude review and then request human review, but feel free to review now - I just don't want to waste human time since I know there are still things to fix but was hoping for some high-level feedback from Claude 👍).


This change is Reviewable

@codecov-commenter

codecov-commenter commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.86691% with 88 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.74%. Comparing base (e063f28) to head (b464ab9).

Files with missing lines Patch % Lines
machine/jobs/build_remote_llm_engine.py 48.97% 50 Missing ⚠️
machine/translation/llm/remote_llm_engine.py 93.22% 17 Missing ⚠️
machine/jobs/remote_llm_model_factory.py 85.71% 6 Missing ⚠️
machine/jobs/hugging_face_nmt_engine_build_job.py 93.42% 5 Missing ⚠️
machine/jobs/remote_llm_engine_build_job.py 92.95% 5 Missing ⚠️
machine/jobs/nmt_engine_build_job_base.py 96.61% 2 Missing ⚠️
machine/jobs/build_clearml_helper.py 85.71% 1 Missing ⚠️
...jobs/huggingface/hugging_face_nmt_model_factory.py 50.00% 1 Missing ⚠️
tests/translation/llm/test_remote_llm_engine.py 99.54% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #423      +/-   ##
==========================================
+ Coverage   92.64%   92.74%   +0.09%     
==========================================
  Files         424      432       +8     
  Lines       27014    28001     +987     
==========================================
+ Hits        25028    25970     +942     
- Misses       1986     2031      +45     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread machine/jobs/build_remote_llm_engine.py Resolved
Comment thread machine/jobs/build_remote_llm_engine.py Resolved
Comment thread machine/jobs/build_remote_llm_engine.py Resolved
@claude

This comment has been minimized.

@Enkidu93 Enkidu93 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Enkidu93 made 10 comments and resolved 4 discussions.
Reviewable status: 0 of 18 files reviewed, 6 unresolved discussions.

Comment thread machine/jobs/build_remote_llm_engine.py Resolved
Comment thread machine/jobs/build_remote_llm_engine.py Resolved
Comment thread machine/jobs/build_remote_llm_engine.py Resolved
@claude

This comment has been minimized.

@Enkidu93 Enkidu93 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Enkidu93 made 5 comments.
Reviewable status: 0 of 18 files reviewed, 1 unresolved discussion.

Comment thread machine/jobs/build_remote_llm_engine.py Resolved
Comment thread machine/jobs/build_remote_llm_engine.py Resolved
Comment thread machine/jobs/__init__.py Resolved
Comment thread machine/jobs/nmt_model_factory.py Resolved
@claude

This comment has been minimized.

@Enkidu93 Enkidu93 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Enkidu93 made 5 comments and resolved 1 discussion.
Reviewable status: 0 of 26 files reviewed, 3 unresolved discussions.

Comment thread machine/jobs/__init__.py Resolved
Comment thread machine/jobs/nmt_model_factory.py Resolved
@claude

This comment has been minimized.

@claude

This comment has been minimized.

@Enkidu93 Enkidu93 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Enkidu93 made 1 comment.
Reviewable status: 0 of 26 files reviewed, 1 unresolved discussion.

@claude

This comment has been minimized.

@benjaminking benjaminking left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still need to take a more complete look, but I wanted to get some comments in before I was done for the week.

@benjaminking partially reviewed 7 files and all commit messages, and made 7 comments.
Reviewable status: 7 of 26 files reviewed, 5 unresolved discussions (waiting on Enkidu93, mshannon-sil, and pmachapman).


machine/jobs/remote_llm_engine_build_job.py line 112 at r6 (raw file):

            source_segments = [join_surrogate_pairs_if_needed(pt_info["translation"]) for pt_info in pt_batch]
            results = engine.translate_batch(source_segments)
            failed_indices = set(engine.failed_segment_indices)

Not a huge deal and more of a philosophical point, but getting the list of failures via mutable state feels like it introduces the possibility for bugs. _translate() is relying on a sort of unwritten contract with RemoteLlmEngine, but it doesn't control the lifecycle of the engine, meaning that we don't know what else some other part of the code might be doing with it that could invalidate the contract. There's not a bug here currently, but it would be easy to introduce one accidentally.


machine/translation/llm/remote_llm_engine.py line 67 at r6 (raw file):

        }
        self.usage_totals = usage_totals if usage_totals is not None else LlmUsageTotals()
        self.failed_segment_indices: List[int] = []

Could we modify TranslationResult to allow it to carry information about what failed?


machine/translation/llm/remote_llm_engine.py line 75 at r6 (raw file):

        return self.translate_n_batch(n, [segment])[0]

    def translate_batch(self, segments: Sequence[Union[str, Sequence[str]]]) -> Sequence[TranslationResult]:

We don't necessarily need it for the MVP, but it could potentially speed things up substantially if we didn't wait for all the threads to complete before we started the next batch. But as I'm thinking about what the chapter-by-chapter requirements might be, I could see some major benefits from an architecture that has a shared pool of workers that can each be reallocated as soon as it's idle.


machine/translation/llm/remote_llm_engine.py line 184 at r6 (raw file):

                        "role": "user",
                        "content": (
                            f"Reply with only the {self._target_language} translation of the source passage. "

How much extra work would it add to allow for configurable prompts? SILNLP currently allows config.yml to specify what the prompt will be. The big issue I can see is that you'd potentially need to use a different parser for the output if the requested format changes.

If it's too much work, we should instead use SILNLP's default prompt, which has been tested more thoroughly.


machine/translation/llm/remote_llm_engine.py line 226 at r6 (raw file):

            }
        ]
        for example in self._example_retriever.rank(query, self._num_examples):

I believe that the example retriever returns the most relevant examples first. We should reverse that order so that the most relevant examples are last in the prompt. This is what's done in SILNLP, and we've seen improved performance from it.


machine/translation/llm/remote_llm_engine.py line 227 at r6 (raw file):

        ]
        for example in self._example_retriever.rank(query, self._num_examples):
            messages.append({"role": "user", "content": example.source})

I don't think we've ever tested how providing examples via conversation turns works. We probably should stick to the implementation we've tested, which is an "examples" section in the prompt.

@Enkidu93 Enkidu93 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Enkidu93 made 6 comments.
Reviewable status: 6 of 28 files reviewed, 5 unresolved discussions (waiting on benjaminking, mshannon-sil, and pmachapman).


machine/jobs/remote_llm_engine_build_job.py line 112 at r6 (raw file):

Previously, benjaminking (Ben King) wrote…

Not a huge deal and more of a philosophical point, but getting the list of failures via mutable state feels like it introduces the possibility for bugs. _translate() is relying on a sort of unwritten contract with RemoteLlmEngine, but it doesn't control the lifecycle of the engine, meaning that we don't know what else some other part of the code might be doing with it that could invalidate the contract. There's not a bug here currently, but it would be easy to introduce one accidentally.

That's a good idea. I've gone ahead and added an error field to the TranslationResult.


machine/translation/llm/remote_llm_engine.py line 67 at r6 (raw file):

Previously, benjaminking (Ben King) wrote…

Could we modify TranslationResult to allow it to carry information about what failed?

Yep, done.


machine/translation/llm/remote_llm_engine.py line 75 at r6 (raw file):

Previously, benjaminking (Ben King) wrote…

We don't necessarily need it for the MVP, but it could potentially speed things up substantially if we didn't wait for all the threads to complete before we started the next batch. But as I'm thinking about what the chapter-by-chapter requirements might be, I could see some major benefits from an architecture that has a shared pool of workers that can each be reallocated as soon as it's idle.

Yeah, that is a good point. For the chapter-by-chapter, we may need an implementation in Serval itself at which point this becomes much more straightforward. For now, since the outer inference batch size is 1024, I think this may not be as big of a problem as you'd think. We could always increase the batch size to an even larger number for remote LLMs as a workaround for batch drafting since there's really no need I don't think to constrain the batching for LLM inferencing 🤔.


machine/translation/llm/remote_llm_engine.py line 184 at r6 (raw file):

Previously, benjaminking (Ben King) wrote…

How much extra work would it add to allow for configurable prompts? SILNLP currently allows config.yml to specify what the prompt will be. The big issue I can see is that you'd potentially need to use a different parser for the output if the requested format changes.

If it's too much work, we should instead use SILNLP's default prompt, which has been tested more thoroughly.

I've added the ability to configure the prompt matching silnlp. I apologize for the mismatch. I tried to have an agent move the prompt code over to machine.py thinking it would be more reliable at strictly copy-pasting and save me some time and apparently it was not. The places I checked were fine, but clearly many others did not maintain parity. That's on me. Let me know if you see any mismatches still. I added some tests that should ensure parity.


machine/translation/llm/remote_llm_engine.py line 226 at r6 (raw file):

Previously, benjaminking (Ben King) wrote…

I believe that the example retriever returns the most relevant examples first. We should reverse that order so that the most relevant examples are last in the prompt. This is what's done in SILNLP, and we've seen improved performance from it.

Done.


machine/translation/llm/remote_llm_engine.py line 227 at r6 (raw file):

Previously, benjaminking (Ben King) wrote…

I don't think we've ever tested how providing examples via conversation turns works. We probably should stick to the implementation we've tested, which is an "examples" section in the prompt.

See above. It should match silnlp now. There are a few tests that seem to confirm this.

mshannon-sil and others added 2 commits November 25, 2026 10:39
fix justification language

rebase on main; distinguish between content block and general refusal; return unchanged draft if all attempts fail

address claude review comments

First draft of remote LLM drafting; update settings to use uv environment in VS code

Address configuration problems

Address failing test

Refactor engines; address Claude comments

Address reviewer comments

Fix import sorting

Fix misplaced import

Respond to reviewer comments; ensure parity with silnlp
@claude

This comment has been minimized.

check_canceled()
phase_progress(ProgressStatus.from_step(completed + status.step, count))

edited = editor.post_edit_batch(segments, max_workers=4, consecutive=False, progress=report_progress)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: F21. If one post-edit request fails with an unexpected error, the whole build fails and writes no pretranslations, even though training and drafting already finished. post_edit_batch raises PostEditBatchError when any segment fails, and nothing catches it here, so the if not result.succeeded warning below never runs for these errors. Repro: three drafts, with the mock client raising ConnectionError("429 Too Many Requests") on the second, raised PostEditBatchError: 1 of 3 segments failed to post-edit and wrote "". To keep the drafts, catch it and use error.results, which holds the draft for each failed segment. If failing the build is intended, say so.

@claude

claude Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Approve with fixes. F17–F20 from the rebase round are fixed. The new post-edit step has one Important finding, and CI has not finished on this head.

  1. Verdict: approve with fixes, once F21 is answered and CI is green.
  2. Most important: F21 at machine/jobs/nmt_engine_build_job_base.py:139. If any post-edit request fails with an unexpected error, such as a 429 left after retries, the build fails with PostEditBatchError and writes no pretranslations, so the training and drafting work is lost.
  3. Counts: 1 Important (F21), new. No Critical finding is open.
  4. Ran: gh api .../compare/99053b8...b464ab9 returned ahead, so I reviewed only git diff 99053b8 b464ab9. pytest tests/jobs tests/translation/llm: 205 passed. git diff e063f28 b464ab9 -- tests/translation/llm/test_post_edit_segment.py is empty (F19). For F21, I drove HuggingFaceNmtEngineBuildJob with post_edit_model set and a mock client that raised on the second of three segments. It raised PostEditBatchError, and the output was empty. CI (gh pr checks 423): all 15 Build on ... jobs, claude-review and Reviewable are pending. Comment hygiene passed, but it is advisory only.
  5. Not verified: pyright, which CI has not reached on this head, so I cannot confirm F17's type errors are gone. I also did not check that Serval reads the new postEditedTranslation field, or that it expects translationTokens and alignment to describe the post-edited text while translation stays the draft, which is what test_post_edit_before_alignment asserts.

Changed surface: machine.translation.llm no longer exports LlmUsageTotals, which this PR had added. LlmCompletionClient gains usage_summary, and RemoteLlmEngine.__init__ drops usage_totals. NmtBuildOptions and RemoteLlmBuildOptions gain post_edit_model. The pretranslation output gains postEditedTranslation. The accepted breaks (F9, F12, F13) still stand. Parity with sillsdev/machine: none verified, since there is no C# counterpart.

Findings: F1 addressed, F2 addressed, F3 addressed, F4 accepted (silnlp parity unverified), F5 accepted (silnlp parity unverified), F6 accepted (deferred to human reviewers), F7 accepted (deferred to human reviewers), F8 withdrawn, F9 accepted, F10 addressed, F11 addressed (no test for the empty-corpus path), F12 accepted, F13 accepted, F14 addressed, F15 addressed, F16 addressed, F17 addressed (pyright unverified), F18 addressed, F19 addressed, F20 addressed, F21 new.

Reviewed at b464ab9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement RemoteLlmNmtTranslationEngine

4 participants