client_app.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from typing import Tuple
  2. from ray.util.client import ray
  3. ray.connect("localhost:50051")
  4. @ray.remote
  5. class HelloActor:
  6. def __init__(self):
  7. self.count = 0
  8. def say_hello(self, whom: str) -> Tuple[str, int]:
  9. self.count += 1
  10. return ("Hello " + whom, self.count)
  11. actor = HelloActor.remote()
  12. s, count = ray.get(actor.say_hello.remote("you"))
  13. print(s, count)
  14. assert s == "Hello you"
  15. assert count == 1
  16. s, count = ray.get(actor.say_hello.remote("world"))
  17. print(s, count)
  18. assert s == "Hello world"
  19. assert count == 2
  20. @ray.remote
  21. def plus2(x):
  22. return x + 2
  23. @ray.remote
  24. def fact(x):
  25. print(x, type(fact))
  26. if x <= 0:
  27. return 1
  28. # This hits the "nested tasks" issue
  29. # https://github.com/ray-project/ray/issues/3644
  30. # So we're on the right track!
  31. return ray.get(fact.remote(x - 1)) * x
  32. @ray.remote
  33. def get_nodes():
  34. return ray.nodes() # Can access the full Ray API in remote methods.
  35. print("Cluster nodes", ray.get(get_nodes.remote()))
  36. print(ray.nodes())
  37. objectref = ray.put("hello world")
  38. # `ClientObjectRef(...)`
  39. print(objectref)
  40. # `hello world`
  41. print(ray.get(objectref))
  42. ref2 = plus2.remote(234)
  43. # `ClientObjectRef(...)`
  44. print(ref2)
  45. # `236`
  46. print(ray.get(ref2))
  47. ref3 = fact.remote(20)
  48. # `ClientObjectRef(...)`
  49. print(ref3)
  50. # `2432902008176640000`
  51. print(ray.get(ref3))
  52. # Reuse the cached ClientRemoteFunc object
  53. ref4 = fact.remote(5)
  54. # `120`
  55. print(ray.get(ref4))
  56. ref5 = fact.remote(10)
  57. print([ref2, ref3, ref4, ref5])
  58. # should return ref2, ref3, ref4
  59. res = ray.wait([ref5, ref2, ref3, ref4], num_returns=3)
  60. print(res)
  61. assert [ref2, ref3, ref4] == res[0]
  62. assert [ref5] == res[1]
  63. # should return ref2, ref3, ref4, ref5
  64. res = ray.wait([ref2, ref3, ref4, ref5], num_returns=4)
  65. print(res)
  66. assert [ref2, ref3, ref4, ref5] == res[0]
  67. assert [] == res[1]