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.

grampus.go 38 kB

3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. package repo
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "path"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/services/cloudbrain/cloudbrainTask"
  14. "code.gitea.io/gitea/modules/dataset"
  15. "code.gitea.io/gitea/services/cloudbrain/resource"
  16. "code.gitea.io/gitea/services/reward/point/account"
  17. "code.gitea.io/gitea/modules/auth"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/grampus"
  20. "code.gitea.io/gitea/modules/modelarts"
  21. "code.gitea.io/gitea/modules/notification"
  22. "code.gitea.io/gitea/modules/redis/redis_key"
  23. "code.gitea.io/gitea/modules/redis/redis_lock"
  24. "code.gitea.io/gitea/modules/timeutil"
  25. "code.gitea.io/gitea/modules/util"
  26. "github.com/unknwon/com"
  27. "code.gitea.io/gitea/models"
  28. "code.gitea.io/gitea/modules/base"
  29. "code.gitea.io/gitea/modules/cloudbrain"
  30. "code.gitea.io/gitea/modules/context"
  31. "code.gitea.io/gitea/modules/log"
  32. "code.gitea.io/gitea/modules/setting"
  33. cloudbrainService "code.gitea.io/gitea/services/cloudbrain"
  34. )
  35. const (
  36. tplGrampusTrainJobShow base.TplName = "repo/grampus/trainjob/show"
  37. //GPU
  38. tplGrampusTrainJobGPUNew base.TplName = "repo/grampus/trainjob/gpu/new"
  39. //NPU
  40. tplGrampusTrainJobNPUNew base.TplName = "repo/grampus/trainjob/npu/new"
  41. )
  42. func GrampusTrainJobGPUNew(ctx *context.Context) {
  43. ctx.Data["IsCreate"] = true
  44. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  45. if err != nil {
  46. ctx.ServerError("get new train-job info failed", err)
  47. return
  48. }
  49. ctx.HTML(http.StatusOK, tplGrampusTrainJobGPUNew)
  50. }
  51. func GrampusTrainJobNPUNew(ctx *context.Context) {
  52. ctx.Data["IsCreate"] = true
  53. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  54. if err != nil {
  55. ctx.ServerError("get new train-job info failed", err)
  56. return
  57. }
  58. ctx.HTML(200, tplGrampusTrainJobNPUNew)
  59. }
  60. func grampusTrainJobNewDataPrepare(ctx *context.Context, processType string) error {
  61. ctx.Data["PageIsCloudBrain"] = true
  62. t := time.Now()
  63. var displayJobName = jobNamePrefixValid(cutString(ctx.User.Name, 5)) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  64. ctx.Data["display_job_name"] = displayJobName
  65. //get valid images
  66. images, err := grampus.GetImages(processType)
  67. if err != nil {
  68. log.Error("GetImages failed:", err.Error())
  69. } else {
  70. ctx.Data["images"] = images.Infos
  71. }
  72. grampus.InitSpecialPool()
  73. ctx.Data["GPUEnabled"] = true
  74. ctx.Data["NPUEnabled"] = true
  75. includeCenters := make(map[string]struct{})
  76. excludeCenters := make(map[string]struct{})
  77. if grampus.SpecialPools != nil {
  78. for _, pool := range grampus.SpecialPools.Pools {
  79. if pool.IsExclusive {
  80. if !IsUserInOrgPool(ctx.User.ID, pool) {
  81. ctx.Data[pool.Type+"Enabled"] = false
  82. }
  83. } else {
  84. if strings.Contains(strings.ToLower(processType), strings.ToLower(pool.Type)) {
  85. if IsUserInOrgPool(ctx.User.ID, pool) {
  86. for _, center := range pool.Pool {
  87. includeCenters[center.Queue] = struct{}{}
  88. }
  89. } else {
  90. for _, center := range pool.Pool {
  91. excludeCenters[center.Queue] = struct{}{}
  92. }
  93. }
  94. }
  95. }
  96. }
  97. }
  98. //prepare available specs
  99. if processType == grampus.ProcessorTypeNPU {
  100. prepareGrampusTrainSpecs(ctx, models.NPU)
  101. } else if processType == grampus.ProcessorTypeGPU {
  102. prepareGrampusTrainSpecs(ctx, models.GPU)
  103. }
  104. //get branches
  105. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  106. if err != nil {
  107. log.Error("GetBranches error:", err.Error())
  108. } else {
  109. ctx.Data["branches"] = branches
  110. }
  111. ctx.Data["branchName"] = ctx.Repo.BranchName
  112. if processType == grampus.ProcessorTypeGPU {
  113. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  114. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, models.GPUResource, models.JobTypeTrain)
  115. ctx.Data["WaitCount"] = waitCount
  116. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.GPUResource)
  117. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  118. } else if processType == grampus.ProcessorTypeNPU {
  119. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  120. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, models.NPUResource, models.JobTypeTrain)
  121. ctx.Data["WaitCount"] = waitCount
  122. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.NPUResource)
  123. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  124. }
  125. if ctx.Cloudbrain != nil {
  126. uuids, datasetNames := dataset.GetFilterDeletedAttachments(ctx.Cloudbrain.Uuid)
  127. ctx.Data["attachment"] = uuids
  128. ctx.Data["boot_file"] = ctx.Cloudbrain.BootFile
  129. ctx.Data["image_id"] = ctx.Cloudbrain.ImageID
  130. ctx.Data["run_para_list"] = ctx.Cloudbrain.Parameters
  131. ctx.Data["description"] = ctx.Cloudbrain.Description
  132. ctx.Data["branch_name"] = ctx.Cloudbrain.BranchName
  133. ctx.Data["engine_name"] = ctx.Cloudbrain.EngineName
  134. ctx.Data["work_server_number"] = ctx.Cloudbrain.WorkServerNumber
  135. if ctx.Cloudbrain.Image != "" {
  136. ctx.Data["image"] = ctx.Cloudbrain.Image
  137. } else {
  138. ctx.Data["image"] = ctx.Cloudbrain.EngineName
  139. }
  140. ctx.Data["dataset_name"] = datasetNames
  141. ctx.Data["model_name"] = ctx.Cloudbrain.ModelName
  142. ctx.Data["model_version"] = ctx.Cloudbrain.ModelVersion
  143. ctx.Data["ckpt_name"] = ctx.Cloudbrain.CkptName
  144. ctx.Data["label_names"] = ctx.Cloudbrain.LabelName
  145. ctx.Data["pre_train_model_url"] = ctx.Cloudbrain.PreTrainModelUrl
  146. spec, _ := resource.GetCloudbrainSpec(ctx.Cloudbrain.ID)
  147. if spec != nil {
  148. ctx.Data["spec_id"] = spec.ID
  149. }
  150. }
  151. return nil
  152. }
  153. func GrampusTrainJobVersionNew(ctx *context.Context) {
  154. task := ctx.Cloudbrain
  155. ctx.Data["IsCreate"] = false
  156. if task.ComputeResource == models.GPUResource {
  157. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  158. if err != nil {
  159. ctx.ServerError("get new train-job version info failed", err)
  160. return
  161. }
  162. ctx.HTML(http.StatusOK, tplGrampusTrainJobGPUNew)
  163. } else if task.ComputeResource == models.NPUResource {
  164. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  165. if err != nil {
  166. ctx.ServerError("get new train-job version info failed", err)
  167. return
  168. }
  169. ctx.HTML(200, tplGrampusTrainJobNPUNew)
  170. }
  171. }
  172. func prepareGrampusTrainSpecs(ctx *context.Context, computeResource string) {
  173. noteBookSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  174. JobType: models.JobTypeTrain,
  175. ComputeResource: computeResource,
  176. Cluster: models.C2NetCluster,
  177. })
  178. ctx.Data["Specs"] = noteBookSpecs
  179. }
  180. func getFilterSpecBySpecialPool(specs *models.GetGrampusResourceSpecsResult, includeCenters map[string]struct{}, excludeCenters map[string]struct{}) []models.GrampusSpec {
  181. if len(includeCenters) == 0 && len(excludeCenters) == 0 {
  182. return specs.Infos
  183. }
  184. var grampusSpecs []models.GrampusSpec
  185. for _, info := range specs.Infos {
  186. if isInIncludeCenters(info, includeCenters) || (len(excludeCenters) != 0 && isNotAllInExcludeCenters(info, excludeCenters)) {
  187. grampusSpecs = append(grampusSpecs, info)
  188. }
  189. }
  190. return grampusSpecs
  191. }
  192. func isInIncludeCenters(grampusSpec models.GrampusSpec, centers map[string]struct{}) bool {
  193. for _, center := range grampusSpec.Centers {
  194. if _, ok := centers[center.ID]; ok {
  195. return true
  196. }
  197. }
  198. return false
  199. }
  200. func isNotAllInExcludeCenters(grampusSpec models.GrampusSpec, centers map[string]struct{}) bool {
  201. for _, center := range grampusSpec.Centers {
  202. if _, ok := centers[center.ID]; !ok {
  203. return true
  204. }
  205. }
  206. return false
  207. }
  208. func IsUserInOrgPool(userId int64, pool *models.SpecialPool) bool {
  209. org, _ := models.GetOrgByName(pool.Org)
  210. if org != nil {
  211. isOrgMember, _ := models.IsOrganizationMember(org.ID, userId)
  212. return isOrgMember
  213. }
  214. return false
  215. }
  216. func grampusParamCheckCreateTrainJob(form auth.CreateGrampusTrainJobForm) error {
  217. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  218. log.Error("the boot file(%s) must be a python file", form.BootFile)
  219. return errors.New("启动文件必须是python文件")
  220. }
  221. if form.BranchName == "" {
  222. log.Error("the branch must not be null!", form.BranchName)
  223. return errors.New("代码分支不能为空!")
  224. }
  225. return nil
  226. }
  227. func GrampusTrainJobGpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  228. ctx.Data["IsCreate"] = true
  229. grampusTrainJobGpuCreate(ctx, form)
  230. }
  231. func grampusTrainJobGpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  232. displayJobName := form.DisplayJobName
  233. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  234. uuid := form.Attachment
  235. description := form.Description
  236. bootFile := strings.TrimSpace(form.BootFile)
  237. params := form.Params
  238. repo := ctx.Repo.Repository
  239. codeLocalPath := setting.JobPath + jobName + cloudbrain.CodeMountPath + "/"
  240. codeMinioPath := setting.CBCodePathPrefix + jobName + cloudbrain.CodeMountPath + "/"
  241. branchName := form.BranchName
  242. image := strings.TrimSpace(form.Image)
  243. tpl := tplGrampusTrainJobGPUNew
  244. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName))
  245. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  246. if !isOk {
  247. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  248. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  249. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplGrampusTrainJobGPUNew, &form)
  250. return
  251. }
  252. defer lock.UnLock()
  253. if !jobNamePattern.MatchString(displayJobName) {
  254. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  255. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  256. return
  257. }
  258. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  259. if err != nil || !bootFileExist {
  260. log.Error("Get bootfile error:", err, ctx.Data["MsgID"])
  261. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  262. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tpl, &form)
  263. return
  264. }
  265. //check count limit
  266. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.GPUResource)
  267. if err != nil {
  268. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  269. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  270. ctx.RenderWithErr("system error", tpl, &form)
  271. return
  272. } else {
  273. if count >= 1 {
  274. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  275. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  276. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  277. return
  278. }
  279. }
  280. //check param
  281. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  282. log.Error("paramCheckCreateTrainJob failed:(%v)", err, ctx.Data["MsgID"])
  283. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  284. ctx.RenderWithErr(err.Error(), tpl, &form)
  285. return
  286. }
  287. //check whether the task name in the project is duplicated
  288. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  289. if err == nil {
  290. if len(tasks) != 0 {
  291. log.Error("the job name did already exist", ctx.Data["MsgID"])
  292. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  293. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  294. return
  295. }
  296. } else {
  297. if !models.IsErrJobNotExist(err) {
  298. log.Error("system error, %v", err, ctx.Data["MsgID"])
  299. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  300. ctx.RenderWithErr("system error", tpl, &form)
  301. return
  302. }
  303. }
  304. //check specification
  305. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  306. JobType: models.JobTypeTrain,
  307. ComputeResource: models.GPU,
  308. Cluster: models.C2NetCluster,
  309. })
  310. if err != nil || spec == nil {
  311. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  312. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  313. return
  314. }
  315. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  316. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  317. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  318. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplGrampusTrainJobGPUNew, &form)
  319. return
  320. }
  321. //check dataset
  322. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid, models.GPU)
  323. if err != nil {
  324. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  325. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  326. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  327. return
  328. }
  329. //prepare code and out path
  330. _, err = ioutil.ReadDir(codeLocalPath)
  331. if err == nil {
  332. os.RemoveAll(codeLocalPath)
  333. }
  334. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  335. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  336. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  337. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  338. return
  339. }
  340. //todo: upload code (send to file_server todo this work?)
  341. //upload code
  342. if err := uploadCodeToMinio(codeLocalPath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  343. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  344. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  345. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  346. return
  347. }
  348. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  349. if err := mkModelPath(modelPath); err != nil {
  350. log.Error("Failed to mkModelPath: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  351. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  352. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  353. return
  354. }
  355. //init model readme
  356. if err := uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/"); err != nil {
  357. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  358. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  359. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  360. return
  361. }
  362. var datasetRemotePath, allFileName string
  363. for _, datasetInfo := range datasetInfos {
  364. if datasetRemotePath == "" {
  365. datasetRemotePath = datasetInfo.DataLocalPath
  366. allFileName = datasetInfo.FullName
  367. } else {
  368. datasetRemotePath = datasetRemotePath + ";" + datasetInfo.DataLocalPath
  369. allFileName = allFileName + ";" + datasetInfo.FullName
  370. }
  371. }
  372. //prepare command
  373. preTrainModelPath := getPreTrainModelPath(form.PreTrainModelUrl, form.CkptName)
  374. command, err := generateCommand(repo.Name, grampus.ProcessorTypeGPU, codeMinioPath+cloudbrain.DefaultBranchName+".zip", datasetRemotePath, bootFile, params, setting.CBCodePathPrefix+jobName+cloudbrain.ModelMountPath+"/", allFileName, preTrainModelPath, form.CkptName)
  375. if err != nil {
  376. log.Error("Failed to generateCommand: %s (%v)", displayJobName, err, ctx.Data["MsgID"])
  377. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  378. ctx.RenderWithErr("Create task failed, internal error", tpl, &form)
  379. return
  380. }
  381. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  382. req := &grampus.GenerateTrainJobReq{
  383. JobName: jobName,
  384. DisplayJobName: displayJobName,
  385. ComputeResource: models.GPUResource,
  386. ProcessType: grampus.ProcessorTypeGPU,
  387. Command: command,
  388. ImageUrl: image,
  389. Description: description,
  390. BootFile: bootFile,
  391. Uuid: uuid,
  392. CommitID: commitID,
  393. BranchName: branchName,
  394. Params: form.Params,
  395. EngineName: image,
  396. DatasetNames: datasetNames,
  397. DatasetInfos: datasetInfos,
  398. IsLatestVersion: modelarts.IsLatestVersion,
  399. VersionCount: modelarts.VersionCountOne,
  400. WorkServerNumber: 1,
  401. Spec: spec,
  402. }
  403. if form.ModelName != "" { //使用预训练模型训练
  404. req.ModelName = form.ModelName
  405. req.LabelName = form.LabelName
  406. req.CkptName = form.CkptName
  407. req.ModelVersion = form.ModelVersion
  408. req.PreTrainModelUrl = form.PreTrainModelUrl
  409. }
  410. err = grampus.GenerateTrainJob(ctx, req)
  411. if err != nil {
  412. log.Error("GenerateTrainJob failed:%v", err.Error(), ctx.Data["MsgID"])
  413. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  414. ctx.RenderWithErr(err.Error(), tpl, &form)
  415. return
  416. }
  417. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  418. }
  419. func getPreTrainModelPath(pretrainModelDir string, fileName string) string {
  420. index := strings.Index(pretrainModelDir, "/")
  421. if index > 0 {
  422. filterBucket := pretrainModelDir[index+1:]
  423. return filterBucket + fileName
  424. } else {
  425. return ""
  426. }
  427. }
  428. func GrampusTrainJobVersionCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  429. ctx.Data["IsCreate"] = false
  430. computeResource := ctx.Query("compute_resource")
  431. if computeResource == models.GPUResource {
  432. grampusTrainJobGpuCreate(ctx, form)
  433. } else if computeResource == models.NPUResource {
  434. grampusTrainJobNpuCreate(ctx, form)
  435. } else {
  436. ctx.ServerError("resource error", errors.New("compute resource is not support"))
  437. return
  438. }
  439. }
  440. func checkSpecialPool(ctx *context.Context, resourceType string) string {
  441. grampus.InitSpecialPool()
  442. if grampus.SpecialPools != nil {
  443. for _, pool := range grampus.SpecialPools.Pools {
  444. if pool.IsExclusive && pool.Type == resourceType {
  445. org, _ := models.GetOrgByName(pool.Org)
  446. if org != nil {
  447. isOrgMember, _ := models.IsOrganizationMember(org.ID, ctx.User.ID)
  448. if !isOrgMember {
  449. return ctx.Tr("repo.grampus.no_operate_right")
  450. }
  451. }
  452. }
  453. }
  454. }
  455. return ""
  456. }
  457. func GrampusTrainJobNpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  458. ctx.Data["IsCreate"] = true
  459. grampusTrainJobNpuCreate(ctx, form)
  460. }
  461. func grampusTrainJobNpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  462. displayJobName := form.DisplayJobName
  463. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  464. uuid := form.Attachment
  465. description := form.Description
  466. bootFile := strings.TrimSpace(form.BootFile)
  467. params := form.Params
  468. repo := ctx.Repo.Repository
  469. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  470. codeObsPath := grampus.JobPath + jobName + modelarts.CodePath
  471. //dataObsPath := setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + "/"
  472. branchName := form.BranchName
  473. isLatestVersion := modelarts.IsLatestVersion
  474. versionCount := modelarts.VersionCountOne
  475. engineName := form.EngineName
  476. tpl := tplGrampusTrainJobNPUNew
  477. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName))
  478. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  479. if !isOk {
  480. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  481. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  482. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplGrampusTrainJobNPUNew, &form)
  483. return
  484. }
  485. defer lock.UnLock()
  486. if !jobNamePattern.MatchString(displayJobName) {
  487. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  488. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  489. return
  490. }
  491. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  492. if err != nil || !bootFileExist {
  493. log.Error("Get bootfile error:", err, ctx.Data["MsgID"])
  494. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  495. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tpl, &form)
  496. return
  497. }
  498. //check count limit
  499. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.NPUResource)
  500. if err != nil {
  501. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  502. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  503. ctx.RenderWithErr("system error", tpl, &form)
  504. return
  505. } else {
  506. if count >= 1 {
  507. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  508. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  509. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  510. return
  511. }
  512. }
  513. //check param
  514. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  515. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  516. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  517. ctx.RenderWithErr(err.Error(), tpl, &form)
  518. return
  519. }
  520. //check whether the task name in the project is duplicated
  521. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  522. if err == nil {
  523. if len(tasks) != 0 {
  524. log.Error("the job name did already exist", ctx.Data["MsgID"])
  525. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  526. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  527. return
  528. }
  529. } else {
  530. if !models.IsErrJobNotExist(err) {
  531. log.Error("system error, %v", err, ctx.Data["MsgID"])
  532. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  533. ctx.RenderWithErr("system error", tpl, &form)
  534. return
  535. }
  536. }
  537. //check specification
  538. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  539. JobType: models.JobTypeTrain,
  540. ComputeResource: models.NPU,
  541. Cluster: models.C2NetCluster,
  542. })
  543. if err != nil || spec == nil {
  544. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  545. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  546. return
  547. }
  548. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  549. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  550. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  551. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplGrampusTrainJobNPUNew, &form)
  552. return
  553. }
  554. //check dataset
  555. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid, models.NPU)
  556. if err != nil {
  557. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  558. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  559. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  560. return
  561. }
  562. //prepare code and out path
  563. _, err = ioutil.ReadDir(codeLocalPath)
  564. if err == nil {
  565. os.RemoveAll(codeLocalPath)
  566. }
  567. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  568. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err)
  569. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  570. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  571. return
  572. }
  573. //todo: upload code (send to file_server todo this work?)
  574. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath); err != nil {
  575. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  576. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  577. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  578. return
  579. }
  580. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  581. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  582. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  583. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  584. return
  585. }
  586. var datasetRemotePath, allFileName string
  587. for _, datasetInfo := range datasetInfos {
  588. if datasetRemotePath == "" {
  589. datasetRemotePath = datasetInfo.DataLocalPath + "'" + datasetInfo.FullName + "'"
  590. allFileName = datasetInfo.FullName
  591. } else {
  592. datasetRemotePath = datasetRemotePath + ";" + datasetInfo.DataLocalPath + "'" + datasetInfo.FullName + "'"
  593. allFileName = allFileName + ";" + datasetInfo.FullName
  594. }
  595. }
  596. //prepare command
  597. preTrainModelPath := getPreTrainModelPath(form.PreTrainModelUrl, form.CkptName)
  598. command, err := generateCommand(repo.Name, grampus.ProcessorTypeNPU, codeObsPath+cloudbrain.DefaultBranchName+".zip", datasetRemotePath, bootFile, params, setting.CodePathPrefix+jobName+modelarts.OutputPath, allFileName, preTrainModelPath, form.CkptName)
  599. if err != nil {
  600. log.Error("Failed to generateCommand: %s (%v)", displayJobName, err, ctx.Data["MsgID"])
  601. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  602. ctx.RenderWithErr("Create task failed, internal error", tpl, &form)
  603. return
  604. }
  605. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  606. req := &grampus.GenerateTrainJobReq{
  607. JobName: jobName,
  608. DisplayJobName: displayJobName,
  609. ComputeResource: models.NPUResource,
  610. ProcessType: grampus.ProcessorTypeNPU,
  611. Command: command,
  612. ImageId: form.ImageID,
  613. Description: description,
  614. CodeObsPath: codeObsPath,
  615. BootFileUrl: codeObsPath + bootFile,
  616. BootFile: bootFile,
  617. WorkServerNumber: form.WorkServerNumber,
  618. Uuid: uuid,
  619. CommitID: commitID,
  620. IsLatestVersion: isLatestVersion,
  621. BranchName: branchName,
  622. Params: form.Params,
  623. EngineName: engineName,
  624. VersionCount: versionCount,
  625. TotalVersionCount: modelarts.TotalVersionCount,
  626. DatasetNames: datasetNames,
  627. DatasetInfos: datasetInfos,
  628. Spec: spec,
  629. CodeName: strings.ToLower(repo.Name),
  630. }
  631. if form.ModelName != "" { //使用预训练模型训练
  632. req.ModelName = form.ModelName
  633. req.LabelName = form.LabelName
  634. req.CkptName = form.CkptName
  635. req.ModelVersion = form.ModelVersion
  636. req.PreTrainModelUrl = form.PreTrainModelUrl
  637. req.PreTrainModelPath = preTrainModelPath
  638. }
  639. err = grampus.GenerateTrainJob(ctx, req)
  640. if err != nil {
  641. log.Error("GenerateTrainJob failed:%v", err.Error())
  642. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  643. ctx.RenderWithErr(err.Error(), tpl, &form)
  644. return
  645. }
  646. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  647. }
  648. func GrampusStopJob(ctx *context.Context) {
  649. var ID = ctx.Params(":jobid")
  650. var resultCode = "0"
  651. var errorMsg = ""
  652. var status = ""
  653. task := ctx.Cloudbrain
  654. for {
  655. if task.Status == string(models.GrampusStatusStopped) || task.Status == string(models.GrampusStatusFailed) || task.Status == string(models.GrampusStatusSucceeded) {
  656. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  657. resultCode = "-1"
  658. errorMsg = "system error"
  659. break
  660. }
  661. res, err := grampus.StopJob(task.JobID)
  662. if err != nil {
  663. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  664. resultCode = strconv.Itoa(res.ErrorCode)
  665. errorMsg = res.ErrorMsg
  666. break
  667. }
  668. oldStatus := task.Status
  669. task.Status = string(models.GrampusStatusStopped)
  670. if task.EndTime == 0 {
  671. task.EndTime = timeutil.TimeStampNow()
  672. }
  673. task.ComputeAndSetDuration()
  674. if oldStatus != task.Status {
  675. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  676. }
  677. err = models.UpdateJob(task)
  678. if err != nil {
  679. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  680. resultCode = "-1"
  681. errorMsg = "system error"
  682. break
  683. }
  684. status = task.Status
  685. break
  686. }
  687. ctx.JSON(200, map[string]interface{}{
  688. "result_code": resultCode,
  689. "error_msg": errorMsg,
  690. "status": status,
  691. "id": ID,
  692. "StatusOK": 0,
  693. })
  694. }
  695. func GrampusTrainJobDel(ctx *context.Context) {
  696. var listType = ctx.Query("listType")
  697. if err := deleteGrampusJob(ctx); err != nil {
  698. log.Error("deleteGrampusJob failed: %v", err, ctx.Data["msgID"])
  699. ctx.ServerError(err.Error(), err)
  700. return
  701. }
  702. var isAdminPage = ctx.Query("isadminpage")
  703. var isHomePage = ctx.Query("ishomepage")
  704. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  705. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  706. } else if isHomePage == "true" {
  707. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  708. } else {
  709. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  710. }
  711. }
  712. func deleteGrampusJob(ctx *context.Context) error {
  713. task := ctx.Cloudbrain
  714. if task.Status != string(models.GrampusStatusStopped) && task.Status != string(models.GrampusStatusSucceeded) && task.Status != string(models.GrampusStatusFailed) {
  715. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  716. return errors.New("the job has not been stopped")
  717. }
  718. err := models.DeleteJob(task)
  719. if err != nil {
  720. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  721. return err
  722. }
  723. storageType := models.TypeCloudBrainOne
  724. if task.ComputeResource == models.NPUResource {
  725. storageType = models.TypeCloudBrainTwo
  726. }
  727. DeleteCloudbrainJobStorage(task.JobName, storageType)
  728. return nil
  729. }
  730. func GrampusTrainJobShow(ctx *context.Context) {
  731. ctx.Data["PageIsCloudBrain"] = true
  732. var task *models.Cloudbrain
  733. task, err := models.GetCloudbrainByJobIDWithDeleted(ctx.Params(":jobid"))
  734. if err != nil {
  735. log.Error("GetCloudbrainByJobID failed:" + err.Error())
  736. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  737. return
  738. }
  739. task.ContainerIp = ""
  740. if task.DeletedAt.IsZero() { //normal record
  741. result, err := grampus.GetJob(task.JobID)
  742. if err != nil {
  743. log.Error("GetJob failed:" + err.Error())
  744. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  745. return
  746. }
  747. if result != nil {
  748. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  749. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  750. }
  751. oldStatus := task.Status
  752. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  753. if task.Status != result.JobInfo.Status || result.JobInfo.Status == models.GrampusStatusRunning {
  754. task.Duration = result.JobInfo.RunSec
  755. if task.Duration < 0 {
  756. task.Duration = 0
  757. }
  758. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  759. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  760. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  761. }
  762. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  763. task.EndTime = task.StartTime.Add(task.Duration)
  764. }
  765. task.CorrectCreateUnix()
  766. if oldStatus != task.Status {
  767. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  768. }
  769. err = models.UpdateJob(task)
  770. if err != nil {
  771. log.Error("UpdateJob failed:" + err.Error())
  772. }
  773. }
  774. }
  775. }
  776. if len(task.Parameters) > 0 {
  777. var parameters models.Parameters
  778. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  779. if err != nil {
  780. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  781. ctx.ServerError("system error", err)
  782. return
  783. }
  784. if len(parameters.Parameter) > 0 {
  785. paramTemp := ""
  786. for _, Parameter := range parameters.Parameter {
  787. param := Parameter.Label + " = " + Parameter.Value + "; "
  788. paramTemp = paramTemp + param
  789. }
  790. task.Parameters = paramTemp[:len(paramTemp)-2]
  791. } else {
  792. task.Parameters = ""
  793. }
  794. }
  795. taskList := make([]*models.Cloudbrain, 0)
  796. taskList = append(taskList, task)
  797. prepareSpec4Show(ctx, task)
  798. ctx.Data["version_list_task"] = taskList
  799. ctx.Data["datasetDownload"] = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false)
  800. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  801. ctx.Data["displayJobName"] = task.DisplayJobName
  802. ctx.Data["ai_center"] = cloudbrainService.GetAiCenterShow(task.AiCenter,ctx)
  803. ctx.HTML(http.StatusOK, tplGrampusTrainJobShow)
  804. }
  805. func GrampusDownloadLog(ctx *context.Context) {
  806. jobID := ctx.Params(":jobid")
  807. job, err := models.GetCloudbrainByJobID(jobID)
  808. if err != nil {
  809. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  810. ctx.ServerError(err.Error(), err)
  811. return
  812. }
  813. content, err := grampus.GetTrainJobLog(job.JobID)
  814. if err != nil {
  815. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  816. content = ""
  817. }
  818. fileName := job.JobName + "-log.txt"
  819. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  820. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  821. var b []byte = []byte(content)
  822. ctx.Resp.Write(b)
  823. }
  824. func GrampusGetLog(ctx *context.Context) {
  825. jobID := ctx.Params(":jobid")
  826. job, err := models.GetCloudbrainByJobID(jobID)
  827. if err != nil {
  828. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  829. ctx.ServerError(err.Error(), err)
  830. return
  831. }
  832. content, err := grampus.GetTrainJobLog(job.JobID)
  833. if err != nil {
  834. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  835. ctx.ServerError(err.Error(), err)
  836. return
  837. }
  838. var canLogDownload bool
  839. if err != nil {
  840. canLogDownload = false
  841. } else {
  842. canLogDownload = true
  843. }
  844. ctx.JSON(http.StatusOK, map[string]interface{}{
  845. "JobName": job.JobName,
  846. "Content": content,
  847. "CanLogDownload": canLogDownload,
  848. })
  849. return
  850. }
  851. func generateCommand(repoName, processorType, codeRemotePath, dataRemotePath, bootFile, paramSrc, outputRemotePath, datasetName, pretrainModelPath, pretrainModelFileName string) (string, error) {
  852. var command string
  853. workDir := grampus.NpuWorkDir
  854. if processorType == grampus.ProcessorTypeGPU {
  855. workDir = grampus.GpuWorkDir
  856. }
  857. command += "pwd;cd " + workDir + fmt.Sprintf(grampus.CommandPrepareScript, setting.Grampus.SyncScriptProject, setting.Grampus.SyncScriptProject)
  858. //download code & dataset
  859. if processorType == grampus.ProcessorTypeNPU {
  860. //no need to download code & dataset by internet
  861. } else if processorType == grampus.ProcessorTypeGPU {
  862. commandDownload := "./downloader_for_minio " + setting.Grampus.Env + " " + codeRemotePath + " " + grampus.CodeArchiveName + " '" + dataRemotePath + "' '" + datasetName + "'"
  863. commandDownload = processPretrainModelParameter(pretrainModelPath, pretrainModelFileName, commandDownload)
  864. command += commandDownload
  865. }
  866. //unzip code & dataset
  867. if processorType == grampus.ProcessorTypeNPU {
  868. //no need to process
  869. } else if processorType == grampus.ProcessorTypeGPU {
  870. unZipDatasetCommand := generateDatasetUnzipCommand(datasetName)
  871. commandUnzip := "cd " + workDir + "code;unzip -q master.zip;echo \"start to unzip dataset\";cd " + workDir + "dataset;" + unZipDatasetCommand
  872. command += commandUnzip
  873. }
  874. command += "echo \"unzip finished;start to exec code;\";"
  875. // set export
  876. var commandExport string
  877. if processorType == grampus.ProcessorTypeNPU {
  878. commandExport = "export bucket=" + setting.Bucket + " && export remote_path=" + outputRemotePath + ";"
  879. } else if processorType == grampus.ProcessorTypeGPU {
  880. commandExport = "export env=" + setting.Grampus.Env + " && export remote_path=" + outputRemotePath + ";"
  881. }
  882. command += commandExport
  883. //exec code
  884. var parameters models.Parameters
  885. var paramCode string
  886. if len(paramSrc) != 0 {
  887. err := json.Unmarshal([]byte(paramSrc), &parameters)
  888. if err != nil {
  889. log.Error("Failed to Unmarshal params: %s (%v)", paramSrc, err)
  890. return command, err
  891. }
  892. for _, parameter := range parameters.Parameter {
  893. paramCode += " --" + parameter.Label + "=" + parameter.Value
  894. }
  895. }
  896. var commandCode string
  897. if processorType == grampus.ProcessorTypeNPU {
  898. commandCode = "/bin/bash /home/work/run_train_for_openi.sh /home/work/openi.py /tmp/log/train.log" + paramCode + ";"
  899. } else if processorType == grampus.ProcessorTypeGPU {
  900. if pretrainModelFileName != "" {
  901. paramCode += " --ckpt_url" + "=" + workDir + "pretrainmodel/" + pretrainModelFileName
  902. }
  903. commandCode = "cd " + workDir + "code/" + strings.ToLower(repoName) + ";python " + bootFile + paramCode + ";"
  904. }
  905. command += commandCode
  906. //get exec result
  907. commandGetRes := "result=$?;"
  908. command += commandGetRes
  909. //upload models
  910. if processorType == grampus.ProcessorTypeNPU {
  911. commandUpload := "cd " + workDir + setting.Grampus.SyncScriptProject + "/;./uploader_for_npu " + setting.Bucket + " " + outputRemotePath + " " + workDir + "output/;"
  912. command += commandUpload
  913. } else if processorType == grampus.ProcessorTypeGPU {
  914. commandUpload := "cd " + workDir + setting.Grampus.SyncScriptProject + "/;./uploader_for_gpu " + setting.Grampus.Env + " " + outputRemotePath + " " + workDir + "output/;"
  915. command += commandUpload
  916. }
  917. //check exec result
  918. commandCheckRes := "bash -c \"[[ $result -eq 0 ]] && exit 0 || exit -1\""
  919. command += commandCheckRes
  920. return command, nil
  921. }
  922. func processPretrainModelParameter(pretrainModelPath string, pretrainModelFileName string, commandDownload string) string {
  923. commandDownloadTemp := commandDownload
  924. if pretrainModelPath != "" {
  925. commandDownloadTemp += " '" + pretrainModelPath + "' '" + pretrainModelFileName + "'"
  926. }
  927. commandDownloadTemp += ";"
  928. return commandDownloadTemp
  929. }
  930. func generateDatasetUnzipCommand(datasetName string) string {
  931. var unZipDatasetCommand string
  932. datasetNameArray := strings.Split(datasetName, ";")
  933. if len(datasetNameArray) == 1 { //单数据集
  934. unZipDatasetCommand = "unzip -q '" + datasetName + "';"
  935. if strings.HasSuffix(datasetNameArray[0], ".tar.gz") {
  936. unZipDatasetCommand = "tar --strip-components=1 -zxvf '" + datasetName + "';"
  937. }
  938. } else { //多数据集
  939. for _, datasetNameTemp := range datasetNameArray {
  940. if strings.HasSuffix(datasetNameTemp, ".tar.gz") {
  941. unZipDatasetCommand = unZipDatasetCommand + "tar -zxvf '" + datasetNameTemp + "';"
  942. } else {
  943. unZipDatasetCommand = unZipDatasetCommand + "unzip -q '" + datasetNameTemp + "' -d './" + strings.TrimSuffix(datasetNameTemp, ".zip") + "';"
  944. }
  945. }
  946. }
  947. return unZipDatasetCommand
  948. }
  949. func downloadZipCode(ctx *context.Context, codePath, branchName string) error {
  950. archiveType := git.ZIP
  951. archivePath := codePath
  952. if !com.IsDir(archivePath) {
  953. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  954. log.Error("MkdirAll failed:" + err.Error())
  955. return err
  956. }
  957. }
  958. // Get corresponding commit.
  959. var (
  960. commit *git.Commit
  961. err error
  962. )
  963. gitRepo := ctx.Repo.GitRepo
  964. if err != nil {
  965. log.Error("OpenRepository failed:" + err.Error())
  966. return err
  967. }
  968. if gitRepo.IsBranchExist(branchName) {
  969. commit, err = gitRepo.GetBranchCommit(branchName)
  970. if err != nil {
  971. log.Error("GetBranchCommit failed:" + err.Error())
  972. return err
  973. }
  974. } else {
  975. log.Error("the branch is not exist: " + branchName)
  976. return fmt.Errorf("The branch does not exist.")
  977. }
  978. archivePath = path.Join(archivePath, grampus.CodeArchiveName)
  979. if !com.IsFile(archivePath) {
  980. if err := commit.CreateArchive(archivePath, git.CreateArchiveOpts{
  981. Format: archiveType,
  982. Prefix: setting.Repository.PrefixArchiveFiles,
  983. }); err != nil {
  984. log.Error("CreateArchive failed:" + err.Error())
  985. return err
  986. }
  987. }
  988. return nil
  989. }