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

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