Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,9 @@ object HuggingFaceCodegenBase {
| def _resolve_providers(self, token):
| '''Query the HF Hub API for inference providers serving this model.
| Returns a list of dicts with 'name' and 'providerId' sorted
| cheapest-first. Falls back to hf-inference if anything goes wrong.
| cheapest-first. When the lookup fails or lists no live provider, text
| generation falls back to the router's own chat route ("auto") and
| every other task falls back to hf-inference.
| '''
| try:
| resp = requests.get(
Expand Down Expand Up @@ -190,6 +192,10 @@ object HuggingFaceCodegenBase {
| return live
| except Exception:
| pass
| # The Hub can return an empty mapping for a model that providers still
| # serve, and hf-inference no longer serves text-generation models.
| if self.TASK == "text-generation":
| return [{"name": "auto", "providerId": self.MODEL_ID}]
| return [{"name": "hf-inference", "providerId": self.MODEL_ID}]
|
| def _post_with_fallback(self, providers, json_headers, raw_binary_headers, pipeline_payload, use_raw_binary_body, prompt_value):
Expand All @@ -207,7 +213,11 @@ object HuggingFaceCodegenBase {
| prov_task = prov.get("task", "")
| try:
| if self.TASK in ("text-generation", "image-text-to-text"):
| if provider_name == "hf-inference":
| if provider_name == "auto":
| # The router's OpenAI-compatible route picks a live
| # provider for the Hub model ID itself.
| url = "https://router.huggingface.co/v1/chat/completions"
| elif provider_name == "hf-inference":
| # hf-inference expects the model in the URL path, like the
| # pipeline route below.
| url = f"https://router.huggingface.co/hf-inference/models/{self.MODEL_ID}/v1/chat/completions"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
"""Run the generated provider lookup and request loop against a stubbed HF API.

Reads {"source": <generated operator Python>, "model": <model id>,
"cases": [{"task": ..., "hub": {"status": <int>, "body": <json>} | {"raise": true}}, ...]}
on stdin and writes {"results": [{"posts": [{"url": ..., "model": ...}, ...]}, ...]}
on stdout.

`_resolve_providers`, `_post_with_fallback` and `_post_pipeline` are lifted out
of the source and run on their own (the generated module depends on the
pytexera runtime). Only `requests` is replaced: GET answers with the case's Hub
response, POST records the URL and model it was sent and answers 200, so no
request leaves the machine.
"""

import json
import sys

WANTED = ("_resolve_providers", "_post_with_fallback", "_post_pipeline")
CONSTANTS = ("PROVIDER_COST_PRIORITY", "CHAT_ROUTES")


def lift(source, name):
"""Return the text of a 4-space-indented method, or '' when absent."""
out, started = [], False
for line in source.split("\n"):
stripped = line.strip()
if stripped.startswith("def " + name + "("):
started = True
elif started and (
line.startswith(" def ") or (line and not line.startswith(" "))
):
break
if started:
out.append(line)
return "\n".join(out)


def lift_constant(source, name):
"""Return a multi-line class constant, up to its closing bracket."""
out, started = [], False
for line in source.split("\n"):
if line.startswith(" " + name + " = "):
started = True
if started:
out.append(line)
if line in (" ]", " }"):
break
return "\n".join(out)


class FakeResponse:
def __init__(self, status_code, body):
self.status_code = status_code
self._body = body
self.text = json.dumps(body)

def json(self):
return self._body


class FakeRequests:
def __init__(self, hub):
self.hub = hub
self.posts = []

def get(self, url, **kwargs):
if self.hub.get("raise"):
raise ConnectionError("hub unreachable")
return FakeResponse(self.hub["status"], self.hub.get("body", {}))

def post(self, url, json=None, **kwargs):
self.posts.append({"url": url, "model": (json or {}).get("model", "")})
return FakeResponse(200, {})


def main():
request = json.load(sys.stdin)
source = request["source"]
body = "\n".join(lift_constant(source, n) for n in CONSTANTS)
body += "\n" + "\n".join(lift(source, n) for n in WANTED)
module = "class Operator:\n%s\n" % body
model = request["model"]

results = []
for case in request["cases"]:
fake = FakeRequests(case["hub"])
namespace = {"requests": fake}
exec(compile(module, "<generated>", "exec"), namespace) # noqa: S102 - the point of the probe
op = namespace["Operator"]()
op.TASK = case["task"]
op.MODEL_ID = model
if case["task"] in ("text-generation", "image-text-to-text"):
payload = {"model": model, "messages": [{"role": "user", "content": "hi"}]}
else:
payload = {"inputs": "hi"}
providers = op._resolve_providers("token")
op._post_with_fallback(providers, {}, {}, payload, False, "hi")
results.append({"posts": fake.posts})
json.dump({"results": results}, sys.stdout)


if __name__ == "__main__":
main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.texera.amber.operator.huggingFace.codegen

import com.fasterxml.jackson.databind.ObjectMapper
import org.apache.texera.amber.operator.huggingFace.codegen.HuggingFaceCodegenFixtures.textContext
import org.apache.texera.amber.util.PythonTestSupport.{
configuredPython,
copyScriptResource,
withProbe
}
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import java.nio.file.Path
import scala.jdk.CollectionConverters._

/**
* Executes the *generated* provider lookup and request loop to check where each
* request goes when the Hub's provider mapping is or is not usable (#9723).
*
* The Hub now returns `"inferenceProviderMapping": {}` for models that are
* still served, and hf-inference no longer serves text-generation models, so
* falling back to hf-inference failed every text-generation row. The expected
* URL is the router's OpenAI-compatible route named in the issue, which picks a
* live provider itself and takes the Hub model ID. The probe stubs only
* `requests`, so nothing reaches the network.
*/
class HuggingFaceProviderRouteBehaviorSpec extends AnyFlatSpec with Matchers {

private val mapper = new ObjectMapper()

private val model = "openai/gpt-oss-20b"

private val routerChat = "https://router.huggingface.co/v1/chat/completions"

private lazy val probe: Path =
copyScriptResource(
getClass.getResourceAsStream("/python/hf_provider_route_probe.py"),
"hf_provider_route_probe"
)

/** Runs one row for `task` with the given Hub reply; returns the (url, model) posted. */
private def posts(task: String, hub: String): Seq[(String, String)] = {
val exe =
configuredPython().getOrElse(cancel("no python interpreter available to run the probe"))
val request = mapper.createObjectNode()
request.put(
"source",
HuggingFaceCodegenBase.render(textContext.copy(modelId = model), TextGenCodegen)
)
request.put("model", model)
val c = request.putArray("cases").addObject()
c.put("task", task)
c.set("hub", mapper.readTree(hub))

withProbe(exe, probe, "hf_provider_route_probe", 60, mapper.writeValueAsBytes(request)) {
(exitCode, out, err) =>
withClue(s"probe stderr: $err\nprobe stdout: $out\n") { exitCode shouldBe 0 }
mapper
.readTree(out)
.get("results")
.get(0)
.get("posts")
.elements()
.asScala
.map(p => (p.get("url").asText(), p.get("model").asText()))
.toSeq
}
}

// The exact Hub reply quoted in the issue.
private val emptyMapping = """{"status": 200, "body": {"inferenceProviderMapping": {}}}"""

"The generated request loop" should "send text generation to the router's chat route when the Hub lists no provider" in {
posts("text-generation", emptyMapping) shouldBe Seq((routerChat, model))
}

it should "send text generation to the router's chat route when the Hub lookup fails" in {
posts("text-generation", """{"status": 500}""") shouldBe Seq((routerChat, model))
posts("text-generation", """{"raise": true}""") shouldBe Seq((routerChat, model))
}

it should "keep a live provider from the Hub on its own route and model name" in {
val live =
"""{"status": 200, "body": {"inferenceProviderMapping":
|{"cerebras": {"status": "live", "providerId": "gpt-oss-20b"}}}}""".stripMargin
posts("text-generation", live) shouldBe
Seq(("https://router.huggingface.co/cerebras/v1/chat/completions", "gpt-oss-20b"))
}

it should "keep the hf-inference fallback for image-text-to-text" in {
// It shares the chat branch with text generation, but the fix for #9723 only
// moves text generation to the router's chat route.
posts("image-text-to-text", emptyMapping) shouldBe
Seq((s"https://router.huggingface.co/hf-inference/models/$model/v1/chat/completions", model))
}

it should "keep the hf-inference fallback for pipeline tasks" in {
// Only text generation moves to the router's chat route; pipeline tasks have
// no chat payload, so they still post to hf-inference with the model in the path.
posts("question-answering", emptyMapping) shouldBe
Seq((s"https://router.huggingface.co/hf-inference/models/$model", ""))
}
}