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 24 kB

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

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.