Spaces:
Build error
Build error
github-actions[bot] commited on
Commit ·
0134a08
1
Parent(s): b3226d1
Auto-sync from demo at Mon Dec 22 08:12:07 UTC 2025
Browse filesFiles changed (4)
3 unmodified lines4567891063 unmodified lines74757677787980818245 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511523 unmodified linesimport rayfrom graphgen.bases import BaseLLMWrapperfrom graphgen.common.init_storage import get_actor_handlefrom graphgen.models import Tokenizer63 unmodified linesA proxy class to interact with the LLMServiceActor for distributed LLM operations."""def __init__(self, actor_name: str):super().__init__()self.actor_handle = get_actor_handle(actor_name)self._create_local_tokenizer()async def generate_answer(45 unmodified linesactor_name = f"Actor_LLM_{model_type}"try:ray.get_actor(actor_name)except ValueError:print(f"Creating Ray actor for LLM {model_type} with backend {backend}.")num_gpus = float(config.pop("num_gpus", 0))actor = (ray.remote(LLMServiceActor).options(name=actor_name,num_gpus=num_gpus,lifetime="detached",get_if_exists=True,).remote(backend, config))# wait for actor to be readyray.get(actor.ready.remote())return LLMServiceProxy(actor_name)def _load_env_group(prefix: str) -> Dict[str, Any]:3 unmodified lines45678963 unmodified lines73747576777879808145 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501513 unmodified linesimport rayfrom graphgen.bases import BaseLLMWrapperfrom graphgen.models import Tokenizer63 unmodified linesA proxy class to interact with the LLMServiceActor for distributed LLM operations."""def __init__(self, actor_handle: ray.actor.ActorHandle):super().__init__()self.actor_handle = actor_handleself._create_local_tokenizer()async def generate_answer(45 unmodified linesactor_name = f"Actor_LLM_{model_type}"try:actor_handle = ray.get_actor(actor_name)print(f"Using existing Ray actor: {actor_name}")except ValueError:print(f"Creating Ray actor for LLM {model_type} with backend {backend}.")num_gpus = float(config.pop("num_gpus", 0))actor_handle = (ray.remote(LLMServiceActor).options(name=actor_name,num_gpus=num_gpus,get_if_exists=True,).remote(backend, config))# wait for actor to be readyray.get(actor_handle.ready.remote())return LLMServiceProxy(actor_handle)def _load_env_group(prefix: str) -> Dict[str, Any]:
47 unmodified lines48495051525360 unmodified lines11411511611711811912012112212312412512612712812913013113213313413527 unmodified lines16316416516616716816917017117217361 unmodified lines23523623723823924024124224324424524624724824925025125225325425525625725825926026147 unmodified linesdef reload(self):return self.kv.reload()class GraphStorageActor:def __init__(self, backend: str, working_dir: str, namespace: str):60 unmodified linesdef reload(self):return self.graph.reload()def get_actor_handle(name: str):try:return ray.get_actor(name)except ValueError as exc:raise RuntimeError(f"Actor {name} not found. Make sure it is created before accessing.") from excclass RemoteKVStorageProxy(BaseKVStorage):def __init__(self, namespace: str):super().__init__()self.namespace = namespaceself.actor_name = f"Actor_KV_{namespace}"self.actor = get_actor_handle(self.actor_name)def data(self) -> Dict[str, Any]:return ray.get(self.actor.data.remote())27 unmodified linesclass RemoteGraphStorageProxy(BaseGraphStorage):def __init__(self, namespace: str):super().__init__()self.namespace = namespaceself.actor_name = f"Actor_Graph_{namespace}"self.actor = get_actor_handle(self.actor_name)def index_done_callback(self):return ray.get(self.actor.index_done_callback.remote())61 unmodified linesdef create_storage(backend: str, working_dir: str, namespace: str):if backend in ["json_kv", "rocksdb"]:actor_name = f"Actor_KV_{namespace}"try:ray.get_actor(actor_name)except ValueError:ray.remote(KVStorageActor).options(name=actor_name,lifetime="detached",get_if_exists=True,).remote(backend, working_dir, namespace)return RemoteKVStorageProxy(namespace)if backend in ["networkx", "kuzu"]:actor_name = f"Actor_Graph_{namespace}"try:ray.get_actor(actor_name)except ValueError:ray.remote(GraphStorageActor).options(name=actor_name,lifetime="detached",get_if_exists=True,).remote(backend, working_dir, namespace)return RemoteGraphStorageProxy(namespace)raise ValueError(f"Unknown storage backend: {backend}")def init_storage(backend: str, working_dir: str, namespace: str):47 unmodified lines48495051525354555660 unmodified lines11711811912012112212312412512612712812913027 unmodified lines15815916016116216316416516661 unmodified lines22822923023123223323423523623723823924024124224324424524624724824925047 unmodified linesdef reload(self):return self.kv.reload()def ready(self) -> bool:return Trueclass GraphStorageActor:def __init__(self, backend: str, working_dir: str, namespace: str):60 unmodified linesdef reload(self):return self.graph.reload()def ready(self) -> bool:return Trueclass RemoteKVStorageProxy(BaseKVStorage):def __init__(self, actor_handle: ray.actor.ActorHandle):super().__init__()self.actor = actor_handledef data(self) -> Dict[str, Any]:return ray.get(self.actor.data.remote())27 unmodified linesclass RemoteGraphStorageProxy(BaseGraphStorage):def __init__(self, actor_handle: ray.actor.ActorHandle):super().__init__()self.actor = actor_handledef index_done_callback(self):return ray.get(self.actor.index_done_callback.remote())61 unmodified linesdef create_storage(backend: str, working_dir: str, namespace: str):if backend in ["json_kv", "rocksdb"]:actor_name = f"Actor_KV_{namespace}"actor_class = KVStorageActorproxy_class = RemoteKVStorageProxyelif backend in ["networkx", "kuzu"]:actor_name = f"Actor_Graph_{namespace}"actor_class = GraphStorageActorproxy_class = RemoteGraphStorageProxyelse:raise ValueError(f"Unknown storage backend: {backend}")try:actor_handle = ray.get_actor(actor_name)except ValueError:actor_handle = ray.remote(actor_class).options(name=actor_name,get_if_exists=True,).remote(backend, working_dir, namespace)ray.get(actor_handle.ready.remote())return proxy_class(actor_handle)def init_storage(backend: str, working_dir: str, namespace: str):
123456781 unmodified line101112131415163 unmodified lines2021222324253 unmodified lines2930313233343 unmodified lines383940414243import inspectimport loggingfrom collections import defaultdict, dequefrom functools import wrapsfrom typing import Any, Callable, Dict, List, Setimport rayimport ray.data1 unmodified linefrom graphgen.bases import Config, Nodefrom graphgen.utils import loggerclass Engine:def __init__(3 unmodified linesself.global_params = self.config.global_paramsself.functions = functionsself.datasets: Dict[str, ray.data.Dataset] = {}ctx = DataContext.get_current()ctx.enable_rich_progress_bars = False3 unmodified linesctx.enable_tensor_extension_casting = Falsectx._metrics_export_port = 0 # Disable metrics exporter to avoid RpcErrorif not ray.is_initialized():context = ray.init(ignore_reinit_error=True,3 unmodified lines)logger.info("Ray Dashboard URL: %s", context.dashboard_url)@staticmethoddef _topo_sort(nodes: List[Node]) -> List[Node]:id_to_node: Dict[str, Node] = {}123456789101 unmodified line1213141516171819203 unmodified lines24252627282930313 unmodified lines353637383940414243444546474849503 unmodified lines54555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112import osimport inspectimport loggingfrom collections import defaultdict, dequefrom functools import wrapsfrom typing import Any, Callable, Dict, List, Setfrom dotenv import load_dotenvimport rayimport ray.data1 unmodified linefrom graphgen.bases import Config, Nodefrom graphgen.utils import loggerfrom graphgen.common import init_llm, init_storageload_dotenv()class Engine:def __init__(3 unmodified linesself.global_params = self.config.global_paramsself.functions = functionsself.datasets: Dict[str, ray.data.Dataset] = {}self.llm_actors = {}self.storage_actors = {}ctx = DataContext.get_current()ctx.enable_rich_progress_bars = False3 unmodified linesctx.enable_tensor_extension_casting = Falsectx._metrics_export_port = 0 # Disable metrics exporter to avoid RpcErrorall_env_vars = os.environ.copy()if "runtime_env" not in ray_init_kwargs:ray_init_kwargs["runtime_env"] = {}existing_env_vars = ray_init_kwargs["runtime_env"].get("env_vars", {})ray_init_kwargs["runtime_env"]["env_vars"] = {**all_env_vars,**existing_env_vars}if not ray.is_initialized():context = ray.init(ignore_reinit_error=True,3 unmodified lines)logger.info("Ray Dashboard URL: %s", context.dashboard_url)self._init_llms()self._init_storage()def _init_llms(self):self.llm_actors["synthesizer"] = init_llm("synthesizer")self.llm_actors["trainee"] = init_llm("trainee")def _init_storage(self):kv_namespaces, graph_namespaces = self._scan_storage_requirements()working_dir = self.global_params["working_dir"]for node_id in kv_namespaces:proxy = init_storage(self.global_params["kv_backend"], working_dir, node_id)self.storage_actors[f"kv_{node_id}"] = proxylogger.info("Create KV Storage Actor: namespace=%s", node_id)for ns in graph_namespaces:proxy = init_storage(self.global_params["graph_backend"], working_dir, ns)self.storage_actors[f"graph_{ns}"] = proxylogger.info("Create Graph Storage Actor: namespace=%s", ns)def _scan_storage_requirements(self) -> tuple[set[str], set[str]]:kv_namespaces = set()graph_namespaces = set()# TODO: Temporarily hard-coded; node storage will be centrally managed later.for node in self.config.nodes:op_name = node.op_nameif self._function_needs_param(op_name, "kv_backend"):kv_namespaces.add(op_name)if self._function_needs_param(op_name, "graph_backend"):graph_namespaces.add("graph")return kv_namespaces, graph_namespacesdef _function_needs_param(self, op_name: str, param_name: str) -> bool:if op_name not in self.functions:return Falsefunc = self.functions[op_name]if inspect.isclass(func):try:sig = inspect.signature(func.__init__)return param_name in sig.parametersexcept (ValueError, TypeError):return Falsetry:sig = inspect.signature(func)return param_name in sig.parametersexcept (ValueError, TypeError):return False@staticmethoddef _topo_sort(nodes: List[Node]) -> List[Node]:id_to_node: Dict[str, Node] = {}
5 unmodified lines67891011123 unmodified lines16171819202122235 unmodified linesimport rayimport yamlfrom dotenv import load_dotenvfrom ray.data.block import Blockfrom ray.data.datasource.filename_provider import FilenameProvider3 unmodified linessys_path = os.path.abspath(os.path.dirname(__file__))load_dotenv()def set_working_dir(folder):os.makedirs(folder, exist_ok=True)5 unmodified lines678910113 unmodified lines1516171819205 unmodified linesimport rayimport yamlfrom ray.data.block import Blockfrom ray.data.datasource.filename_provider import FilenameProvider3 unmodified linessys_path = os.path.abspath(os.path.dirname(__file__))def set_working_dir(folder):os.makedirs(folder, exist_ok=True)
graphgen/common/init_llm.py+7-8
graphgen/common/init_storage.py+25-36
graphgen/engine.py+69
graphgen/run.py-3