You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

modelarts.go 26 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. /*
  2. Copyright (c) [2023] [pcm]
  3. [pcm-coordinator] is licensed under Mulan PSL v2.
  4. You can use this software according to the terms and conditions of the Mulan PSL v2.
  5. You may obtain a copy of Mulan PSL v2 at:
  6. http://license.coscl.org.cn/MulanPSL2
  7. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
  8. EITHER EXPaRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
  9. MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
  10. See the Mulan PSL v2 for more details.
  11. */
  12. package storeLink
  13. import (
  14. "context"
  15. "fmt"
  16. "github.com/pkg/errors"
  17. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/schedulers/option"
  18. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/service/collector"
  19. "gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/service/inference"
  20. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
  21. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
  22. "gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils/timeutils"
  23. "gitlink.org.cn/JointCloud/pcm-modelarts/client/imagesservice"
  24. "gitlink.org.cn/JointCloud/pcm-modelarts/client/modelartsservice"
  25. "gitlink.org.cn/JointCloud/pcm-modelarts/modelarts"
  26. modelartsclient "gitlink.org.cn/JointCloud/pcm-modelarts/modelarts"
  27. "log"
  28. "mime/multipart"
  29. "strconv"
  30. "strings"
  31. "sync"
  32. "time"
  33. )
  34. const (
  35. Ascend = "Ascend"
  36. Npu = "npu"
  37. ImageNetResnet50Cmd = "cd /home/ma-user & python ./inference_ascend.py"
  38. ChatGLM6BCmd = "cd /home/ma-user && python ./download_model.py && python ./inference_chatGLM.py"
  39. )
  40. type ModelArtsLink struct {
  41. modelArtsRpc modelartsservice.ModelArtsService
  42. modelArtsImgRpc imagesservice.ImagesService
  43. platform string
  44. participantId int64
  45. pageIndex int32
  46. pageSize int32
  47. SourceLocation string
  48. Version string
  49. ModelId string
  50. ModelType string
  51. }
  52. type MoUsage struct {
  53. CpuSize int64
  54. NpuSize int64
  55. CpuAvailable int64
  56. NpuAvailable int64
  57. }
  58. // Version 结构体表示版本号
  59. type Version struct {
  60. Major, Minor, Patch int
  61. }
  62. // ParseVersion 从字符串解析版本号
  63. func ParseVersion(versionStr string) (*Version, error) {
  64. parts := strings.Split(versionStr, ".")
  65. if len(parts) != 3 {
  66. return nil, fmt.Errorf("invalid version format: %s", versionStr)
  67. }
  68. major, err := strconv.Atoi(parts[0])
  69. if err != nil {
  70. return nil, err
  71. }
  72. minor, err := strconv.Atoi(parts[1])
  73. if err != nil {
  74. return nil, err
  75. }
  76. patch, err := strconv.Atoi(parts[2])
  77. if err != nil {
  78. return nil, err
  79. }
  80. return &Version{Major: major, Minor: minor, Patch: patch}, nil
  81. }
  82. // Increment 根据给定规则递增版本号
  83. func (v *Version) Increment() {
  84. if v.Patch < 9 {
  85. v.Patch++
  86. } else {
  87. v.Patch = 0
  88. if v.Minor < 9 {
  89. v.Minor++
  90. } else {
  91. v.Minor = 0
  92. v.Major++
  93. }
  94. }
  95. }
  96. // String 将版本号转换回字符串格式
  97. func (v *Version) String() string {
  98. return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
  99. }
  100. func NewModelArtsLink(modelArtsRpc modelartsservice.ModelArtsService, modelArtsImgRpc imagesservice.ImagesService, name string, id int64, nickname string) *ModelArtsLink {
  101. return &ModelArtsLink{modelArtsRpc: modelArtsRpc, modelArtsImgRpc: modelArtsImgRpc, platform: nickname, participantId: id, pageIndex: 0, pageSize: 50}
  102. }
  103. func (m *ModelArtsLink) UploadImage(ctx context.Context, path string) (interface{}, error) {
  104. //TODO modelArts上传镜像
  105. return nil, nil
  106. }
  107. func (m *ModelArtsLink) DeleteImage(ctx context.Context, imageId string) (interface{}, error) {
  108. // TODO modelArts删除镜像
  109. return nil, nil
  110. }
  111. func (m *ModelArtsLink) QueryImageList(ctx context.Context) (interface{}, error) {
  112. // modelArts获取镜像列表
  113. req := &modelarts.ListRepoReq{
  114. Offset: "0",
  115. Limit: strconv.Itoa(int(m.pageSize)),
  116. Platform: m.platform,
  117. }
  118. resp, err := m.modelArtsImgRpc.ListReposDetails(ctx, req)
  119. if err != nil {
  120. return nil, err
  121. }
  122. return resp, nil
  123. }
  124. func (m *ModelArtsLink) SubmitTask(ctx context.Context, imageId string, cmd string, envs []string, params []string, resourceId string, datasetsId string, algorithmId string, aiType string) (interface{}, error) {
  125. // modelArts提交任务
  126. environments := make(map[string]string)
  127. parameters := make([]*modelarts.ParametersTrainJob, 0)
  128. for _, env := range envs {
  129. s := strings.Split(env, COMMA)
  130. environments[s[0]] = s[1]
  131. }
  132. for _, param := range params {
  133. s := strings.Split(param, COMMA)
  134. parameters = append(parameters, &modelarts.ParametersTrainJob{
  135. Name: s[0],
  136. Value: s[1],
  137. })
  138. }
  139. req := &modelarts.CreateTrainingJobReq{
  140. Kind: "job",
  141. Metadata: &modelarts.MetadataS{
  142. Name: TASK_NAME_PREFIX + utils.RandomString(10),
  143. WorkspaceId: "0",
  144. },
  145. Algorithm: &modelarts.Algorithms{
  146. Id: algorithmId,
  147. Engine: &modelarts.EngineCreateTraining{
  148. ImageUrl: imageId,
  149. },
  150. Command: cmd,
  151. Environments: environments,
  152. Parameters: parameters,
  153. },
  154. Spec: &modelarts.SpecsC{
  155. Resource: &modelarts.ResourceCreateTraining{
  156. FlavorId: resourceId,
  157. NodeCount: 1,
  158. },
  159. },
  160. Platform: m.platform,
  161. }
  162. resp, err := m.modelArtsRpc.CreateTrainingJob(ctx, req)
  163. if err != nil {
  164. return nil, err
  165. }
  166. return resp, nil
  167. }
  168. func (m *ModelArtsLink) QueryTask(ctx context.Context, taskId string) (interface{}, error) {
  169. // 获取任务
  170. req := &modelarts.DetailTrainingJobsReq{
  171. TrainingJobId: taskId,
  172. Platform: m.platform,
  173. }
  174. resp, err := m.modelArtsRpc.GetTrainingJobs(ctx, req)
  175. if err != nil {
  176. return nil, err
  177. }
  178. return resp, nil
  179. }
  180. func (m *ModelArtsLink) DeleteTask(ctx context.Context, taskId string) (interface{}, error) {
  181. // 删除任务
  182. req := &modelarts.DeleteTrainingJobReq{
  183. TrainingJobId: taskId,
  184. Platform: m.platform,
  185. }
  186. resp, err := m.modelArtsRpc.DeleteTrainingJob(ctx, req)
  187. if err != nil {
  188. return nil, err
  189. }
  190. return resp, nil
  191. }
  192. func (m *ModelArtsLink) QuerySpecs(ctx context.Context) (interface{}, error) {
  193. // octopus查询资源规格
  194. req := &modelarts.TrainingJobFlavorsReq{
  195. Platform: m.platform,
  196. }
  197. resp, err := m.modelArtsRpc.GetTrainingJobFlavors(ctx, req)
  198. if err != nil {
  199. return nil, err
  200. }
  201. return resp, nil
  202. }
  203. func (m *ModelArtsLink) GetResourceStats(ctx context.Context) (*collector.ResourceStats, error) {
  204. req := &modelarts.GetPoolsRuntimeMetricsReq{}
  205. resp, err := m.modelArtsRpc.GetPoolsRuntimeMetrics(ctx, req)
  206. if err != nil {
  207. return nil, err
  208. }
  209. if resp.ErrorMsg != "" {
  210. return nil, errors.New("failed to get algorithms")
  211. }
  212. resourceStats := &collector.ResourceStats{}
  213. CpuCoreTotalSum := int64(0)
  214. CpuCoreAvailSum := int64(0)
  215. MemTotalSum := float64(0)
  216. MemAvailSum := float64(0)
  217. var CpuCoreTotal int64
  218. var CpuCoreAvail int64
  219. var MemTotal float64
  220. var MemAvail float64
  221. for _, items := range resp.Items {
  222. //TODO The value of taskType is temporarily fixed to "pytorch"
  223. CpuCoreTotal, err = strconv.ParseInt(items.Table.Capacity.Value.Cpu, 10, 64)
  224. CpuCoreTotalSum += CpuCoreTotal
  225. CpuCoreAvail, err = strconv.ParseInt(items.Table.Allocated.Value.Cpu, 10, 64)
  226. CpuCoreAvailSum += CpuCoreAvail
  227. MemTotal, err = strconv.ParseFloat(items.Table.Capacity.Value.Memory, 64)
  228. MemTotalSum += MemTotal
  229. MemAvail, err = strconv.ParseFloat(items.Table.Allocated.Value.Memory, 64)
  230. MemAvailSum += MemAvail
  231. }
  232. resourceStats.CpuCoreTotal = CpuCoreTotalSum
  233. resourceStats.CpuCoreAvail = CpuCoreAvailSum
  234. resourceStats.MemTotal = MemTotalSum
  235. resourceStats.MemAvail = MemAvailSum
  236. req1 := &modelarts.GetResourceFlavorsReq{}
  237. resp1, err := m.modelArtsRpc.GetResourceFlavors(ctx, req1)
  238. num32, _ := strconv.Atoi(resp1.Items[0].Spec.Npu.Size)
  239. var cards []*collector.Card
  240. card := &collector.Card{
  241. Platform: MODELARTS,
  242. Type: CARD,
  243. Name: Npu,
  244. CardNum: int32(num32),
  245. TOpsAtFp16: float64(num32 * 320),
  246. }
  247. cards = append(cards, card)
  248. resourceStats.CardsAvail = cards
  249. return resourceStats, nil
  250. }
  251. func (m *ModelArtsLink) GetDatasetsSpecs(ctx context.Context) ([]*collector.DatasetsSpecs, error) {
  252. return nil, nil
  253. }
  254. func (m *ModelArtsLink) GetAlgorithms(ctx context.Context) ([]*collector.Algorithm, error) {
  255. var algorithms []*collector.Algorithm
  256. req := &modelarts.ListAlgorithmsReq{
  257. Platform: m.platform,
  258. Offset: m.pageIndex,
  259. Limit: m.pageSize,
  260. }
  261. resp, err := m.modelArtsRpc.ListAlgorithms(ctx, req)
  262. if err != nil {
  263. return nil, err
  264. }
  265. if resp.ErrorMsg != "" {
  266. return nil, errors.New("failed to get algorithms")
  267. }
  268. for _, a := range resp.Items {
  269. //TODO The value of taskType is temporarily fixed to "pytorch"
  270. algorithm := &collector.Algorithm{Name: a.Metadata.Name, Platform: MODELARTS, TaskType: "pytorch"}
  271. algorithms = append(algorithms, algorithm)
  272. }
  273. return algorithms, nil
  274. }
  275. func (m *ModelArtsLink) GetComputeCards(ctx context.Context) ([]string, error) {
  276. var cards []string
  277. cards = append(cards, Ascend)
  278. return cards, nil
  279. }
  280. func (m *ModelArtsLink) GetUserBalance(ctx context.Context) (float64, error) {
  281. return 0, nil
  282. }
  283. func (m *ModelArtsLink) DownloadAlgorithmCode(ctx context.Context, resourceType string, card string, taskType string, dataset string, algorithm string) (string, error) {
  284. algoName := dataset + DASH + algorithm
  285. req := &modelarts.GetFileReq{
  286. Path: algoName + FORWARD_SLASH + TRAIN_FILE,
  287. }
  288. resp, err := m.modelArtsRpc.GetFile(ctx, req)
  289. if err != nil {
  290. return "", err
  291. }
  292. return string(resp.Content), nil
  293. }
  294. func (m *ModelArtsLink) UploadAlgorithmCode(ctx context.Context, resourceType string, card string, taskType string, dataset string, algorithm string, code string) error {
  295. return nil
  296. }
  297. // Determine whether there is a necessary image in image management and query the image name based on the image name
  298. func (m *ModelArtsLink) getSourceLocationFromImages(ctx context.Context, option *option.InferOption) error {
  299. req := &modelarts.ListImagesReq{
  300. //Platform: m.platform,
  301. Limit: 50,
  302. Offset: 0,
  303. }
  304. ListImagesResp, err := m.modelArtsRpc.ListImages(ctx, req)
  305. if err != nil {
  306. return err
  307. }
  308. if ListImagesResp.Code != 200 {
  309. return errors.New("failed to get ListImages")
  310. }
  311. for _, ListImages := range ListImagesResp.Data {
  312. if option.ModelName == "ChatGLM-6B" {
  313. if ListImages.Name == "chatglm-6b" {
  314. m.SourceLocation = ListImages.SwrPath
  315. return nil
  316. }
  317. } else {
  318. if ListImages.Name == option.ModelName {
  319. m.SourceLocation = ListImages.SwrPath
  320. return nil
  321. }
  322. }
  323. }
  324. return errors.New("SourceLocation not set")
  325. }
  326. // Get AI Application List
  327. func (m *ModelArtsLink) GetModelId(ctx context.Context, option *option.InferOption) error {
  328. req := &modelarts.ListModelReq{
  329. Platform: m.platform,
  330. ModelName: option.ModelName,
  331. //ModelType: "Image",
  332. Limit: int64(m.pageIndex),
  333. Offset: int64(m.pageSize),
  334. }
  335. ListModelResp, err := m.modelArtsRpc.ListModels(ctx, req)
  336. if err != nil {
  337. return err
  338. }
  339. if ListModelResp.Code == 200 {
  340. //return errors.New("failed to get ModelId")
  341. for _, ListModel := range ListModelResp.Models {
  342. if ListModel.ModelName == option.ModelName {
  343. option.ModelId = ListModel.ModelId
  344. m.Version = ListModel.ModelVersion
  345. return nil
  346. }
  347. }
  348. }
  349. err = m.CreateModel(ctx, option)
  350. if err != nil {
  351. return err
  352. }
  353. return nil
  354. }
  355. func (m *ModelArtsLink) GetModel(ctx context.Context, option *option.InferOption) string {
  356. req := &modelarts.ShowModelReq{
  357. Platform: m.platform,
  358. ModelId: option.ModelId,
  359. }
  360. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
  361. defer cancel()
  362. ShowModelsResp, err := m.modelArtsRpc.ShowModels(ctx, req)
  363. if err != nil {
  364. if err == context.DeadlineExceeded {
  365. log.Println("Request timed out")
  366. // 重试请求或其他处理
  367. } else {
  368. log.Fatalf("could not call method: %v", err)
  369. }
  370. }
  371. if ShowModelsResp.Code != 200 {
  372. errors.New("failed to get findModelsStatus")
  373. }
  374. m.ModelType = ShowModelsResp.ShowModelDetail.ModelAlgorithm
  375. return ShowModelsResp.ShowModelDetail.ModelStatus
  376. }
  377. // Get AI Application List
  378. func (m *ModelArtsLink) GetModelStatus(ctx context.Context, option *option.InferOption) error {
  379. var wg sync.WaitGroup
  380. wg.Add(1)
  381. // 使用goroutine进行轮询
  382. //defer wg.Done()
  383. for {
  384. status := m.GetModel(ctx, option)
  385. if status == "published" {
  386. fmt.Println("Model is now published.")
  387. break // 一旦状态变为published,就退出循环
  388. }
  389. fmt.Println("Waiting for model to be published...")
  390. time.Sleep(5 * time.Second) // 等待一段时间后再次检查
  391. }
  392. // 在这里执行模型状态为published后需要进行的操作
  393. fmt.Println("Continuing with the program...")
  394. return nil
  395. }
  396. // Create an AI application
  397. func (m *ModelArtsLink) CreateModel(ctx context.Context, option *option.InferOption) error {
  398. //Before creating an AI application, check if there are any images that can be created
  399. err := m.getSourceLocationFromImages(ctx, option)
  400. if err != nil { //
  401. return errors.New("No image available for creationd")
  402. }
  403. //
  404. var CMD string
  405. if option.ModelName == "imagenet_resnet50" {
  406. CMD = ImageNetResnet50Cmd
  407. } else if option.ModelName == "ChatGLM-6B" {
  408. CMD = ChatGLM6BCmd
  409. }
  410. if m.Version == "" {
  411. m.Version = "0.0.1"
  412. }
  413. version, err := ParseVersion(m.Version)
  414. version.Increment()
  415. req := &modelarts.CreateModelReq{
  416. Platform: m.platform,
  417. ModelName: option.ModelName,
  418. ModelType: "Image",
  419. ModelVersion: version.String(),
  420. SourceLocation: m.SourceLocation,
  421. InstallType: []string{"real-time"},
  422. Cmd: CMD,
  423. ModelAlgorithm: option.ModelType,
  424. }
  425. ModelResp, err := m.modelArtsRpc.CreateModel(ctx, req)
  426. if err != nil {
  427. return err
  428. }
  429. if ModelResp.Code != 200 {
  430. return errors.New("failed to get ModelId")
  431. }
  432. option.ModelId = ModelResp.ModelId
  433. return nil
  434. }
  435. func (m *ModelArtsLink) GetSpecifications(ctx context.Context, option *option.AiOption, ifoption *option.InferOption) error {
  436. req := &modelarts.ListSpecificationsReq{
  437. //Platform: m.platform,
  438. IsPersonalCluster: false,
  439. InferType: "real-time",
  440. Limit: m.pageIndex,
  441. OffSet: m.pageSize,
  442. }
  443. ListSpecificationsResp, err := m.modelArtsRpc.ListSpecifications(ctx, req)
  444. if err != nil {
  445. return err
  446. }
  447. for _, ListSpecifications := range ListSpecificationsResp.Specifications {
  448. if ListSpecifications.Specification == "modelarts.kat1.xlarge" {
  449. ifoption.Specification = ListSpecifications.Specification
  450. return nil
  451. }
  452. }
  453. return nil
  454. }
  455. func (m *ModelArtsLink) GetTrainingTaskLog(ctx context.Context, taskId string, instanceNum string) (string, error) {
  456. req := &modelartsservice.GetTrainingJobLogsPreviewReq{
  457. Platform: m.platform,
  458. TaskId: "worker-0",
  459. TrainingJobId: taskId,
  460. }
  461. resp, err := m.modelArtsRpc.GetTrainingJobLogsPreview(ctx, req)
  462. if err != nil {
  463. return "", err
  464. }
  465. if strings.Contains(resp.Content, "404 Not Found") {
  466. resp.Content = "waiting for logs..."
  467. }
  468. return resp.Content, nil
  469. }
  470. func (m *ModelArtsLink) GetTrainingTask(ctx context.Context, taskId string) (*collector.Task, error) {
  471. resp, err := m.QueryTask(ctx, taskId)
  472. if err != nil {
  473. return nil, err
  474. }
  475. jobresp, ok := (resp).(*modelartsservice.JobResponse)
  476. if jobresp.ErrorMsg != "" || !ok {
  477. if jobresp.ErrorMsg != "" {
  478. return nil, errors.New(jobresp.ErrorMsg)
  479. } else {
  480. return nil, errors.New("get training task failed, empty error returned")
  481. }
  482. }
  483. var task collector.Task
  484. task.Id = jobresp.Metadata.Id
  485. switch strings.ToLower(jobresp.Status.Phase) {
  486. case "completed":
  487. milliTimestamp := int64(jobresp.Status.StartTime)
  488. task.Start = timeutils.MillisecondsToUTCString(milliTimestamp, time.DateTime)
  489. duration := int64(jobresp.Status.Duration)
  490. task.End = timeutils.MillisecondsToAddDurationToUTCString(milliTimestamp, duration, time.DateTime)
  491. task.Status = constants.Completed
  492. case "failed":
  493. milliTimestamp := int64(jobresp.Status.StartTime)
  494. task.Start = timeutils.MillisecondsToUTCString(milliTimestamp, time.DateTime)
  495. duration := int64(jobresp.Status.Duration)
  496. task.End = timeutils.MillisecondsToAddDurationToUTCString(milliTimestamp, duration, time.DateTime)
  497. task.Status = constants.Failed
  498. case "running":
  499. milliTimestamp := int64(jobresp.Status.StartTime)
  500. task.Start = timeutils.MillisecondsToUTCString(milliTimestamp, time.DateTime)
  501. task.Status = constants.Running
  502. case "stopped":
  503. task.Status = constants.Stopped
  504. case "pending":
  505. task.Status = constants.Pending
  506. case "terminated":
  507. //TODO Failed
  508. task.Status = constants.Failed
  509. default:
  510. task.Status = "undefined"
  511. }
  512. return &task, nil
  513. }
  514. func (m *ModelArtsLink) Execute(ctx context.Context, option *option.AiOption) (interface{}, error) {
  515. err := m.GenerateSubmitParams(ctx, option)
  516. if err != nil {
  517. return nil, err
  518. }
  519. task, err := m.SubmitTask(ctx, option.ImageId, option.Cmd, option.Envs, option.Params, option.ResourceId, option.DatasetsId, option.AlgorithmId, option.TaskType)
  520. if err != nil {
  521. return nil, err
  522. }
  523. return task, nil
  524. }
  525. func (m *ModelArtsLink) GenerateSubmitParams(ctx context.Context, option *option.AiOption) error {
  526. err := m.generateResourceId(ctx, option, nil)
  527. if err != nil {
  528. return err
  529. }
  530. err = m.generateAlgorithmId(ctx, option)
  531. if err != nil {
  532. return err
  533. }
  534. err = m.generateImageId(option)
  535. if err != nil {
  536. return err
  537. }
  538. err = m.generateCmd(option)
  539. if err != nil {
  540. return err
  541. }
  542. err = m.generateEnv(option)
  543. if err != nil {
  544. return err
  545. }
  546. err = m.generateParams(option)
  547. if err != nil {
  548. return err
  549. }
  550. return nil
  551. }
  552. func (m *ModelArtsLink) generateResourceId(ctx context.Context, option *option.AiOption, ifoption *option.InferOption) error {
  553. option.ResourceId = "modelarts.kat1.xlarge"
  554. return nil
  555. }
  556. func (m *ModelArtsLink) generateImageId(option *option.AiOption) error {
  557. return nil
  558. }
  559. func (m *ModelArtsLink) generateCmd(option *option.AiOption) error {
  560. return nil
  561. }
  562. func (m *ModelArtsLink) generateEnv(option *option.AiOption) error {
  563. return nil
  564. }
  565. func (m *ModelArtsLink) generateParams(option *option.AiOption) error {
  566. return nil
  567. }
  568. func (m *ModelArtsLink) generateAlgorithmId(ctx context.Context, option *option.AiOption) error {
  569. req := &modelarts.ListAlgorithmsReq{
  570. Platform: m.platform,
  571. Offset: m.pageIndex,
  572. Limit: m.pageSize,
  573. }
  574. resp, err := m.modelArtsRpc.ListAlgorithms(ctx, req)
  575. if err != nil {
  576. return err
  577. }
  578. if resp.ErrorMsg != "" {
  579. return errors.New("failed to get algorithmId")
  580. }
  581. for _, algorithm := range resp.Items {
  582. engVersion := algorithm.JobConfig.Engine.EngineVersion
  583. if strings.Contains(engVersion, option.TaskType) {
  584. ns := strings.Split(algorithm.Metadata.Name, DASH)
  585. if ns[0] != option.TaskType {
  586. continue
  587. }
  588. if ns[1] != option.DatasetsName {
  589. continue
  590. }
  591. if ns[2] != option.AlgorithmName {
  592. continue
  593. }
  594. option.AlgorithmId = algorithm.Metadata.Id
  595. return nil
  596. }
  597. }
  598. if option.AlgorithmId == "" {
  599. return errors.New("Algorithm does not exist")
  600. }
  601. return errors.New("failed to get AlgorithmId")
  602. }
  603. func (m *ModelArtsLink) GetClusterInferUrl(ctx context.Context, option *option.InferOption) (*inference.ClusterInferUrl, error) {
  604. var imageUrls []*inference.InferUrl
  605. urlReq := &modelartsclient.ImageReasoningUrlReq{
  606. ServiceName: option.ModelName,
  607. Type: option.ModelType,
  608. Card: "npu",
  609. }
  610. urlResp, err := m.modelArtsRpc.ImageReasoningUrl(ctx, urlReq)
  611. if err != nil {
  612. return nil, err
  613. }
  614. imageUrl := &inference.InferUrl{
  615. Url: urlResp.Url,
  616. Card: "npu",
  617. }
  618. imageUrls = append(imageUrls, imageUrl)
  619. clusterWithUrl := &inference.ClusterInferUrl{
  620. ClusterName: m.platform,
  621. ClusterType: TYPE_MODELARTS,
  622. InferUrls: imageUrls,
  623. }
  624. return clusterWithUrl, nil
  625. }
  626. func (m *ModelArtsLink) GetInferDeployInstanceList(ctx context.Context) ([]*inference.DeployInstance, error) {
  627. var insList []*inference.DeployInstance
  628. req := &modelarts.ListServicesReq{
  629. Platform: m.platform,
  630. OffSet: m.pageIndex,
  631. Limit: m.pageSize,
  632. }
  633. //list, err := m.modelArtsRpc.ListServices(ctx, req)
  634. resp, err := m.modelArtsRpc.ListServices(ctx, req)
  635. if err != nil {
  636. return nil, err
  637. }
  638. if resp.ErrorMsg != "" {
  639. return nil, errors.New(resp.Msg)
  640. }
  641. for _, services := range resp.Services {
  642. ins := &inference.DeployInstance{}
  643. ins.InstanceName = services.ServiceName
  644. ins.InstanceId = services.ServiceId
  645. ins.Status = services.Status
  646. ins.InferCard = "NPU"
  647. ins.ClusterName = m.platform
  648. ins.CreatedTime = string(services.StartTime)
  649. ins.ClusterType = TYPE_MODELARTS
  650. insList = append(insList, ins)
  651. }
  652. return insList, nil
  653. }
  654. func (m *ModelArtsLink) StartInferDeployInstance(ctx context.Context, id string) bool {
  655. req := &modelartsclient.UpdateServiceReq{
  656. ServiceId: id,
  657. Status: "running",
  658. }
  659. resp, err := m.modelArtsRpc.UpdateService(ctx, req)
  660. if err != nil || resp.Code != 0 {
  661. return false
  662. }
  663. if resp.Code == 0 {
  664. return true
  665. }
  666. return false
  667. }
  668. func (m *ModelArtsLink) StopInferDeployInstance(ctx context.Context, id string) bool {
  669. req := &modelartsclient.UpdateServiceReq{
  670. ServiceId: id,
  671. Status: "stopped",
  672. }
  673. resp, err := m.modelArtsRpc.UpdateService(ctx, req)
  674. if err != nil || resp.Code != 0 {
  675. return false
  676. }
  677. if resp.Code == 0 {
  678. return true
  679. }
  680. return false
  681. }
  682. func (m *ModelArtsLink) GetInferDeployInstance(ctx context.Context, id string) (*inference.DeployInstance, error) {
  683. req := &modelarts.ShowServiceReq{
  684. ServiceId: id,
  685. }
  686. resp, err := m.modelArtsRpc.ShowService(ctx, req)
  687. if err != nil {
  688. return nil, err
  689. }
  690. if resp.ErrorMsg != "" {
  691. return nil, errors.New(resp.Msg)
  692. }
  693. ins := &inference.DeployInstance{}
  694. ins.InstanceName = resp.ServiceName
  695. ins.InstanceId = resp.ServiceId
  696. ins.Status = resp.Status
  697. ins.InferCard = "NPU"
  698. ins.ClusterName = m.platform
  699. ins.CreatedTime = string(resp.StartTime)
  700. ins.ClusterType = TYPE_MODELARTS
  701. ins.ModelName = resp.Config[0].ModelName
  702. ins.ModelType = m.ModelType
  703. ins.InferUrl = resp.AccessAddress
  704. return ins, nil
  705. }
  706. func (m *ModelArtsLink) GetImageInferResult(ctx context.Context, url string, file multipart.File, fileName string) (string, error) {
  707. return "", nil
  708. }
  709. func (m *ModelArtsLink) CreateInferDeployInstance(ctx context.Context, option *option.InferOption) (string, error) {
  710. err := m.GetModelId(ctx, option)
  711. if err != nil {
  712. return "", err
  713. }
  714. err = m.GetModelStatus(ctx, option)
  715. if err != nil {
  716. return "", err
  717. }
  718. configParam := &modelarts.ServiceConfig{
  719. Specification: "modelarts.kat1.xlarge",
  720. Weight: 100,
  721. ModelId: option.ModelId,
  722. InstanceCount: 1,
  723. }
  724. var configItems []*modelarts.ServiceConfig
  725. configItems = append(configItems, configParam)
  726. now := time.Now()
  727. timestampSec := now.Unix()
  728. str := strconv.FormatInt(timestampSec, 10)
  729. req := &modelarts.CreateServiceReq{
  730. Platform: m.platform,
  731. Config: configItems,
  732. InferType: "real-time",
  733. ServiceName: option.ModelName + "_" + option.ModelType + "_" + Npu + "_" + str,
  734. }
  735. ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
  736. defer cancel()
  737. resp, err := m.modelArtsRpc.CreateService(ctx, req)
  738. if err != nil {
  739. return "", err
  740. }
  741. return resp.ServiceId, nil
  742. }
  743. func (m *ModelArtsLink) CheckModelExistence(ctx context.Context, name string, mtype string) bool {
  744. ifoption := &option.InferOption{
  745. ModelName: name,
  746. ModelType: mtype,
  747. }
  748. err := m.CheckImageExist(ctx, ifoption)
  749. if err != nil {
  750. return false
  751. }
  752. return true
  753. }
  754. func (m *ModelArtsLink) CheckImageExist(ctx context.Context, option *option.InferOption) error {
  755. req := &modelarts.ListImagesReq{
  756. Limit: m.pageSize,
  757. Offset: m.pageIndex,
  758. }
  759. ListImageResp, err := m.modelArtsRpc.ListImages(ctx, req)
  760. if err != nil {
  761. return err
  762. }
  763. var modelName string
  764. if ListImageResp.Code == 200 {
  765. //return errors.New("failed to get ModelId")
  766. for _, ListImage := range ListImageResp.Data {
  767. if option.ModelName == "ChatGLM-6B" {
  768. modelName = "chatglm-6b"
  769. } else {
  770. modelName = option.ModelName
  771. }
  772. if ListImage.Name == modelName {
  773. return nil
  774. }
  775. }
  776. }
  777. return errors.New("failed to find Image ")
  778. }
  779. func (m *ModelArtsLink) GetResourceSpecs(ctx context.Context) (*collector.ResourceSpec, error) {
  780. var wg sync.WaitGroup
  781. req := &modelarts.GetResourceFlavorsReq{}
  782. resp, err := m.modelArtsRpc.GetResourceFlavors(ctx, req)
  783. if err != nil {
  784. return nil, err
  785. }
  786. if resp.Msg != "" {
  787. return nil, errors.New(resp.Msg)
  788. }
  789. MoUsage := MoUsage{}
  790. var cpusum int64 = 0
  791. var npusum int64 = 0
  792. for _, Flavors := range resp.Items {
  793. MoUsage.CpuSize, err = strconv.ParseInt(Flavors.Spec.Cpu, 10, 64) //CPU的值
  794. if err != nil {
  795. // 如果转换失败,处理错误
  796. fmt.Println("转换错误:", err)
  797. }
  798. cpusum += MoUsage.CpuSize
  799. MoUsage.NpuSize, err = strconv.ParseInt(Flavors.Spec.Npu.Size, 10, 64) //NPU的值
  800. if err != nil {
  801. // 如果转换失败,处理错误
  802. fmt.Println("转换错误:", err)
  803. }
  804. npusum += MoUsage.NpuSize
  805. }
  806. reqTraining := &modelarts.ListTrainingJobsreq{
  807. Platform: m.platform,
  808. }
  809. //查询作业列表
  810. respList, err := m.modelArtsRpc.GetListTrainingJobs(ctx, reqTraining)
  811. if err != nil {
  812. wg.Done()
  813. }
  814. var CoreNum int32 = 0
  815. var NpuNum int32 = 0
  816. for _, TrainLists := range respList.Items {
  817. if len(respList.Items) == 0 {
  818. wg.Done()
  819. }
  820. if TrainLists.Status.Phase == "Running" {
  821. CoreNum += TrainLists.Spec.Resource.FlavorDetail.FlavorInfo.Cpu.CoreNum
  822. NpuNum += TrainLists.Spec.Resource.FlavorDetail.FlavorInfo.Npu.UnitNum
  823. }
  824. }
  825. MoUsage.CpuAvailable = cpusum - int64(CoreNum)
  826. MoUsage.NpuAvailable = npusum - int64(NpuNum)
  827. UsageCPU := &collector.Usage{Type: strings.ToUpper(CPU), Total: cpusum, Available: MoUsage.CpuAvailable}
  828. UsageNPU := &collector.Usage{Type: strings.ToUpper(NPU), Total: npusum, Available: MoUsage.NpuAvailable}
  829. resUsage := &collector.ResourceSpec{
  830. ClusterId: m.participantId,
  831. }
  832. resUsage.Resources = append(resUsage.Resources, UsageCPU)
  833. resUsage.Resources = append(resUsage.Resources, UsageNPU)
  834. return resUsage, nil
  835. }

PCM is positioned as Software stack over Cloud, aiming to build the standards and ecology of heterogeneous cloud collaboration for JCC in a non intrusive and autonomous peer-to-peer manner.